blob: cba5ffe5fa43d64a649a9fe78a9f7a54857436fe [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
Eli Friedmana3d727b2013-09-11 03:49:34 +00001041 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1042 !AtomTy->isScalarType()) {
Richard Smithff34d402012-04-12 05:08:17 +00001043 // For GNU atomics, require a trivially-copyable type. This is not part of
1044 // the GNU atomics specification, but we enforce it for sanity.
1045 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001046 << Ptr->getType() << Ptr->getSourceRange();
1047 return ExprError();
1048 }
1049
Richard Smithff34d402012-04-12 05:08:17 +00001050 // FIXME: For any builtin other than a load, the ValType must not be
1051 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001052
1053 switch (ValType.getObjCLifetime()) {
1054 case Qualifiers::OCL_None:
1055 case Qualifiers::OCL_ExplicitNone:
1056 // okay
1057 break;
1058
1059 case Qualifiers::OCL_Weak:
1060 case Qualifiers::OCL_Strong:
1061 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001062 // FIXME: Can this happen? By this point, ValType should be known
1063 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001064 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1065 << ValType << Ptr->getSourceRange();
1066 return ExprError();
1067 }
1068
1069 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001070 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001071 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001072 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001073 ResultType = Context.BoolTy;
1074
Richard Smithff34d402012-04-12 05:08:17 +00001075 // The type of a parameter passed 'by value'. In the GNU atomics, such
1076 // arguments are actually passed as pointers.
1077 QualType ByValType = ValType; // 'CP'
1078 if (!IsC11 && !IsN)
1079 ByValType = Ptr->getType();
1080
Eli Friedman276b0612011-10-11 02:20:01 +00001081 // The first argument --- the pointer --- has a fixed type; we
1082 // deduce the types of the rest of the arguments accordingly. Walk
1083 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001084 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001085 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001086 if (i < NumVals[Form] + 1) {
1087 switch (i) {
1088 case 1:
1089 // The second argument is the non-atomic operand. For arithmetic, this
1090 // is always passed by value, and for a compare_exchange it is always
1091 // passed by address. For the rest, GNU uses by-address and C11 uses
1092 // by-value.
1093 assert(Form != Load);
1094 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1095 Ty = ValType;
1096 else if (Form == Copy || Form == Xchg)
1097 Ty = ByValType;
1098 else if (Form == Arithmetic)
1099 Ty = Context.getPointerDiffType();
1100 else
1101 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1102 break;
1103 case 2:
1104 // The third argument to compare_exchange / GNU exchange is a
1105 // (pointer to a) desired value.
1106 Ty = ByValType;
1107 break;
1108 case 3:
1109 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1110 Ty = Context.BoolTy;
1111 break;
1112 }
Eli Friedman276b0612011-10-11 02:20:01 +00001113 } else {
1114 // The order(s) are always converted to int.
1115 Ty = Context.IntTy;
1116 }
Richard Smithff34d402012-04-12 05:08:17 +00001117
Eli Friedman276b0612011-10-11 02:20:01 +00001118 InitializedEntity Entity =
1119 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001120 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001121 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1122 if (Arg.isInvalid())
1123 return true;
1124 TheCall->setArg(i, Arg.get());
1125 }
1126
Richard Smithff34d402012-04-12 05:08:17 +00001127 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001128 SmallVector<Expr*, 5> SubExprs;
1129 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001130 switch (Form) {
1131 case Init:
1132 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001133 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001134 break;
1135 case Load:
1136 SubExprs.push_back(TheCall->getArg(1)); // Order
1137 break;
1138 case Copy:
1139 case Arithmetic:
1140 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001141 SubExprs.push_back(TheCall->getArg(2)); // Order
1142 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001143 break;
1144 case GNUXchg:
1145 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1146 SubExprs.push_back(TheCall->getArg(3)); // Order
1147 SubExprs.push_back(TheCall->getArg(1)); // Val1
1148 SubExprs.push_back(TheCall->getArg(2)); // Val2
1149 break;
1150 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001151 SubExprs.push_back(TheCall->getArg(3)); // Order
1152 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001153 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001154 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001155 break;
1156 case GNUCmpXchg:
1157 SubExprs.push_back(TheCall->getArg(4)); // Order
1158 SubExprs.push_back(TheCall->getArg(1)); // Val1
1159 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1160 SubExprs.push_back(TheCall->getArg(2)); // Val2
1161 SubExprs.push_back(TheCall->getArg(3)); // Weak
1162 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001163 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001164
1165 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1166 SubExprs, ResultType, Op,
1167 TheCall->getRParenLoc());
1168
1169 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1170 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1171 Context.AtomicUsesUnsupportedLibcall(AE))
1172 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1173 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001174
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001175 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001176}
1177
1178
John McCall5f8d6042011-08-27 01:09:30 +00001179/// checkBuiltinArgument - Given a call to a builtin function, perform
1180/// normal type-checking on the given argument, updating the call in
1181/// place. This is useful when a builtin function requires custom
1182/// type-checking for some of its arguments but not necessarily all of
1183/// them.
1184///
1185/// Returns true on error.
1186static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1187 FunctionDecl *Fn = E->getDirectCallee();
1188 assert(Fn && "builtin call without direct callee!");
1189
1190 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1191 InitializedEntity Entity =
1192 InitializedEntity::InitializeParameter(S.Context, Param);
1193
1194 ExprResult Arg = E->getArg(0);
1195 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1196 if (Arg.isInvalid())
1197 return true;
1198
1199 E->setArg(ArgIndex, Arg.take());
1200 return false;
1201}
1202
Chris Lattner5caa3702009-05-08 06:58:22 +00001203/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1204/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1205/// type of its first argument. The main ActOnCallExpr routines have already
1206/// promoted the types of arguments because all of these calls are prototyped as
1207/// void(...).
1208///
1209/// This function goes through and does final semantic checking for these
1210/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001211ExprResult
1212Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001213 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001214 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1215 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1216
1217 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001218 if (TheCall->getNumArgs() < 1) {
1219 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1220 << 0 << 1 << TheCall->getNumArgs()
1221 << TheCall->getCallee()->getSourceRange();
1222 return ExprError();
1223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Chris Lattner5caa3702009-05-08 06:58:22 +00001225 // Inspect the first argument of the atomic builtin. This should always be
1226 // a pointer type, whose element is an integral scalar or pointer type.
1227 // Because it is a pointer type, we don't have to worry about any implicit
1228 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001229 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001230 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001231 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1232 if (FirstArgResult.isInvalid())
1233 return ExprError();
1234 FirstArg = FirstArgResult.take();
1235 TheCall->setArg(0, FirstArg);
1236
John McCallf85e1932011-06-15 23:02:42 +00001237 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1238 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001239 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1240 << FirstArg->getType() << FirstArg->getSourceRange();
1241 return ExprError();
1242 }
Mike Stump1eb44332009-09-09 15:08:12 +00001243
John McCallf85e1932011-06-15 23:02:42 +00001244 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001245 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001246 !ValType->isBlockPointerType()) {
1247 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1248 << FirstArg->getType() << FirstArg->getSourceRange();
1249 return ExprError();
1250 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001251
John McCallf85e1932011-06-15 23:02:42 +00001252 switch (ValType.getObjCLifetime()) {
1253 case Qualifiers::OCL_None:
1254 case Qualifiers::OCL_ExplicitNone:
1255 // okay
1256 break;
1257
1258 case Qualifiers::OCL_Weak:
1259 case Qualifiers::OCL_Strong:
1260 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001261 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001262 << ValType << FirstArg->getSourceRange();
1263 return ExprError();
1264 }
1265
John McCallb45ae252011-10-05 07:41:44 +00001266 // Strip any qualifiers off ValType.
1267 ValType = ValType.getUnqualifiedType();
1268
Chandler Carruth8d13d222010-07-18 20:54:12 +00001269 // The majority of builtins return a value, but a few have special return
1270 // types, so allow them to override appropriately below.
1271 QualType ResultType = ValType;
1272
Chris Lattner5caa3702009-05-08 06:58:22 +00001273 // We need to figure out which concrete builtin this maps onto. For example,
1274 // __sync_fetch_and_add with a 2 byte object turns into
1275 // __sync_fetch_and_add_2.
1276#define BUILTIN_ROW(x) \
1277 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1278 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Chris Lattner5caa3702009-05-08 06:58:22 +00001280 static const unsigned BuiltinIndices[][5] = {
1281 BUILTIN_ROW(__sync_fetch_and_add),
1282 BUILTIN_ROW(__sync_fetch_and_sub),
1283 BUILTIN_ROW(__sync_fetch_and_or),
1284 BUILTIN_ROW(__sync_fetch_and_and),
1285 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Chris Lattner5caa3702009-05-08 06:58:22 +00001287 BUILTIN_ROW(__sync_add_and_fetch),
1288 BUILTIN_ROW(__sync_sub_and_fetch),
1289 BUILTIN_ROW(__sync_and_and_fetch),
1290 BUILTIN_ROW(__sync_or_and_fetch),
1291 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001292
Chris Lattner5caa3702009-05-08 06:58:22 +00001293 BUILTIN_ROW(__sync_val_compare_and_swap),
1294 BUILTIN_ROW(__sync_bool_compare_and_swap),
1295 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001296 BUILTIN_ROW(__sync_lock_release),
1297 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001298 };
Mike Stump1eb44332009-09-09 15:08:12 +00001299#undef BUILTIN_ROW
1300
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 // Determine the index of the size.
1302 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001303 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001304 case 1: SizeIndex = 0; break;
1305 case 2: SizeIndex = 1; break;
1306 case 4: SizeIndex = 2; break;
1307 case 8: SizeIndex = 3; break;
1308 case 16: SizeIndex = 4; break;
1309 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001310 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1311 << FirstArg->getType() << FirstArg->getSourceRange();
1312 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001313 }
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Chris Lattner5caa3702009-05-08 06:58:22 +00001315 // Each of these builtins has one pointer argument, followed by some number of
1316 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1317 // that we ignore. Find out which row of BuiltinIndices to read from as well
1318 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001319 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001320 unsigned BuiltinIndex, NumFixed = 1;
1321 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001322 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001323 case Builtin::BI__sync_fetch_and_add:
1324 case Builtin::BI__sync_fetch_and_add_1:
1325 case Builtin::BI__sync_fetch_and_add_2:
1326 case Builtin::BI__sync_fetch_and_add_4:
1327 case Builtin::BI__sync_fetch_and_add_8:
1328 case Builtin::BI__sync_fetch_and_add_16:
1329 BuiltinIndex = 0;
1330 break;
1331
1332 case Builtin::BI__sync_fetch_and_sub:
1333 case Builtin::BI__sync_fetch_and_sub_1:
1334 case Builtin::BI__sync_fetch_and_sub_2:
1335 case Builtin::BI__sync_fetch_and_sub_4:
1336 case Builtin::BI__sync_fetch_and_sub_8:
1337 case Builtin::BI__sync_fetch_and_sub_16:
1338 BuiltinIndex = 1;
1339 break;
1340
1341 case Builtin::BI__sync_fetch_and_or:
1342 case Builtin::BI__sync_fetch_and_or_1:
1343 case Builtin::BI__sync_fetch_and_or_2:
1344 case Builtin::BI__sync_fetch_and_or_4:
1345 case Builtin::BI__sync_fetch_and_or_8:
1346 case Builtin::BI__sync_fetch_and_or_16:
1347 BuiltinIndex = 2;
1348 break;
1349
1350 case Builtin::BI__sync_fetch_and_and:
1351 case Builtin::BI__sync_fetch_and_and_1:
1352 case Builtin::BI__sync_fetch_and_and_2:
1353 case Builtin::BI__sync_fetch_and_and_4:
1354 case Builtin::BI__sync_fetch_and_and_8:
1355 case Builtin::BI__sync_fetch_and_and_16:
1356 BuiltinIndex = 3;
1357 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001358
Douglas Gregora9766412011-11-28 16:30:08 +00001359 case Builtin::BI__sync_fetch_and_xor:
1360 case Builtin::BI__sync_fetch_and_xor_1:
1361 case Builtin::BI__sync_fetch_and_xor_2:
1362 case Builtin::BI__sync_fetch_and_xor_4:
1363 case Builtin::BI__sync_fetch_and_xor_8:
1364 case Builtin::BI__sync_fetch_and_xor_16:
1365 BuiltinIndex = 4;
1366 break;
1367
1368 case Builtin::BI__sync_add_and_fetch:
1369 case Builtin::BI__sync_add_and_fetch_1:
1370 case Builtin::BI__sync_add_and_fetch_2:
1371 case Builtin::BI__sync_add_and_fetch_4:
1372 case Builtin::BI__sync_add_and_fetch_8:
1373 case Builtin::BI__sync_add_and_fetch_16:
1374 BuiltinIndex = 5;
1375 break;
1376
1377 case Builtin::BI__sync_sub_and_fetch:
1378 case Builtin::BI__sync_sub_and_fetch_1:
1379 case Builtin::BI__sync_sub_and_fetch_2:
1380 case Builtin::BI__sync_sub_and_fetch_4:
1381 case Builtin::BI__sync_sub_and_fetch_8:
1382 case Builtin::BI__sync_sub_and_fetch_16:
1383 BuiltinIndex = 6;
1384 break;
1385
1386 case Builtin::BI__sync_and_and_fetch:
1387 case Builtin::BI__sync_and_and_fetch_1:
1388 case Builtin::BI__sync_and_and_fetch_2:
1389 case Builtin::BI__sync_and_and_fetch_4:
1390 case Builtin::BI__sync_and_and_fetch_8:
1391 case Builtin::BI__sync_and_and_fetch_16:
1392 BuiltinIndex = 7;
1393 break;
1394
1395 case Builtin::BI__sync_or_and_fetch:
1396 case Builtin::BI__sync_or_and_fetch_1:
1397 case Builtin::BI__sync_or_and_fetch_2:
1398 case Builtin::BI__sync_or_and_fetch_4:
1399 case Builtin::BI__sync_or_and_fetch_8:
1400 case Builtin::BI__sync_or_and_fetch_16:
1401 BuiltinIndex = 8;
1402 break;
1403
1404 case Builtin::BI__sync_xor_and_fetch:
1405 case Builtin::BI__sync_xor_and_fetch_1:
1406 case Builtin::BI__sync_xor_and_fetch_2:
1407 case Builtin::BI__sync_xor_and_fetch_4:
1408 case Builtin::BI__sync_xor_and_fetch_8:
1409 case Builtin::BI__sync_xor_and_fetch_16:
1410 BuiltinIndex = 9;
1411 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Chris Lattner5caa3702009-05-08 06:58:22 +00001413 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001414 case Builtin::BI__sync_val_compare_and_swap_1:
1415 case Builtin::BI__sync_val_compare_and_swap_2:
1416 case Builtin::BI__sync_val_compare_and_swap_4:
1417 case Builtin::BI__sync_val_compare_and_swap_8:
1418 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001419 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001420 NumFixed = 2;
1421 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001422
Chris Lattner5caa3702009-05-08 06:58:22 +00001423 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001424 case Builtin::BI__sync_bool_compare_and_swap_1:
1425 case Builtin::BI__sync_bool_compare_and_swap_2:
1426 case Builtin::BI__sync_bool_compare_and_swap_4:
1427 case Builtin::BI__sync_bool_compare_and_swap_8:
1428 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001429 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001430 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001431 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001432 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001433
1434 case Builtin::BI__sync_lock_test_and_set:
1435 case Builtin::BI__sync_lock_test_and_set_1:
1436 case Builtin::BI__sync_lock_test_and_set_2:
1437 case Builtin::BI__sync_lock_test_and_set_4:
1438 case Builtin::BI__sync_lock_test_and_set_8:
1439 case Builtin::BI__sync_lock_test_and_set_16:
1440 BuiltinIndex = 12;
1441 break;
1442
Chris Lattner5caa3702009-05-08 06:58:22 +00001443 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001444 case Builtin::BI__sync_lock_release_1:
1445 case Builtin::BI__sync_lock_release_2:
1446 case Builtin::BI__sync_lock_release_4:
1447 case Builtin::BI__sync_lock_release_8:
1448 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001449 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001450 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001451 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001452 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001453
1454 case Builtin::BI__sync_swap:
1455 case Builtin::BI__sync_swap_1:
1456 case Builtin::BI__sync_swap_2:
1457 case Builtin::BI__sync_swap_4:
1458 case Builtin::BI__sync_swap_8:
1459 case Builtin::BI__sync_swap_16:
1460 BuiltinIndex = 14;
1461 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001462 }
Mike Stump1eb44332009-09-09 15:08:12 +00001463
Chris Lattner5caa3702009-05-08 06:58:22 +00001464 // Now that we know how many fixed arguments we expect, first check that we
1465 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001466 if (TheCall->getNumArgs() < 1+NumFixed) {
1467 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1468 << 0 << 1+NumFixed << TheCall->getNumArgs()
1469 << TheCall->getCallee()->getSourceRange();
1470 return ExprError();
1471 }
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001473 // Get the decl for the concrete builtin from this, we can tell what the
1474 // concrete integer type we should convert to is.
1475 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1476 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001477 FunctionDecl *NewBuiltinDecl;
1478 if (NewBuiltinID == BuiltinID)
1479 NewBuiltinDecl = FDecl;
1480 else {
1481 // Perform builtin lookup to avoid redeclaring it.
1482 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1483 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1484 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1485 assert(Res.getFoundDecl());
1486 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1487 if (NewBuiltinDecl == 0)
1488 return ExprError();
1489 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001490
John McCallf871d0c2010-08-07 06:22:56 +00001491 // The first argument --- the pointer --- has a fixed type; we
1492 // deduce the types of the rest of the arguments accordingly. Walk
1493 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001494 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001495 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001496
Chris Lattner5caa3702009-05-08 06:58:22 +00001497 // GCC does an implicit conversion to the pointer or integer ValType. This
1498 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001499 // Initialize the argument.
1500 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1501 ValType, /*consume*/ false);
1502 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001503 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001504 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001505
Chris Lattner5caa3702009-05-08 06:58:22 +00001506 // Okay, we have something that *can* be converted to the right type. Check
1507 // to see if there is a potentially weird extension going on here. This can
1508 // happen when you do an atomic operation on something like an char* and
1509 // pass in 42. The 42 gets converted to char. This is even more strange
1510 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001511 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001512 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001513 }
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001515 ASTContext& Context = this->getASTContext();
1516
1517 // Create a new DeclRefExpr to refer to the new decl.
1518 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1519 Context,
1520 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001521 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001522 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001523 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001524 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001525 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001526 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001527
Chris Lattner5caa3702009-05-08 06:58:22 +00001528 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001529 // FIXME: This loses syntactic information.
1530 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1531 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1532 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001533 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001534
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001535 // Change the result type of the call to match the original value type. This
1536 // is arbitrary, but the codegen for these builtins ins design to handle it
1537 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001538 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001539
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001540 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001541}
1542
Chris Lattner69039812009-02-18 06:01:06 +00001543/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001544/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001545/// Note: It might also make sense to do the UTF-16 conversion here (would
1546/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001547bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001548 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001549 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1550
Douglas Gregor5cee1192011-07-27 05:40:30 +00001551 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001552 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1553 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001554 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001555 }
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001557 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001558 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001559 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001560 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001561 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001562 UTF16 *ToPtr = &ToBuf[0];
1563
1564 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1565 &ToPtr, ToPtr + NumBytes,
1566 strictConversion);
1567 // Check for conversion failure.
1568 if (Result != conversionOK)
1569 Diag(Arg->getLocStart(),
1570 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1571 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001572 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001573}
1574
Chris Lattnerc27c6652007-12-20 00:05:45 +00001575/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1576/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001577bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1578 Expr *Fn = TheCall->getCallee();
1579 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001580 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001581 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001582 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1583 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001584 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001585 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001586 return true;
1587 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001588
1589 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001590 return Diag(TheCall->getLocEnd(),
1591 diag::err_typecheck_call_too_few_args_at_least)
1592 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001593 }
1594
John McCall5f8d6042011-08-27 01:09:30 +00001595 // Type-check the first argument normally.
1596 if (checkBuiltinArgument(*this, TheCall, 0))
1597 return true;
1598
Chris Lattnerc27c6652007-12-20 00:05:45 +00001599 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001600 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001601 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001602 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001603 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001604 else if (FunctionDecl *FD = getCurFunctionDecl())
1605 isVariadic = FD->isVariadic();
1606 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001607 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Chris Lattnerc27c6652007-12-20 00:05:45 +00001609 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001610 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1611 return true;
1612 }
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Chris Lattner30ce3442007-12-19 23:59:04 +00001614 // Verify that the second argument to the builtin is the last argument of the
1615 // current function or method.
1616 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001617 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001618
Nico Weberb07d4482013-05-24 23:31:57 +00001619 // These are valid if SecondArgIsLastNamedArgument is false after the next
1620 // block.
1621 QualType Type;
1622 SourceLocation ParamLoc;
1623
Anders Carlsson88cf2262008-02-11 04:20:54 +00001624 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1625 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001626 // FIXME: This isn't correct for methods (results in bogus warning).
1627 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001628 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001629 if (CurBlock)
1630 LastArg = *(CurBlock->TheDecl->param_end()-1);
1631 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001632 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001633 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001634 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001635 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001636
1637 Type = PV->getType();
1638 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001639 }
1640 }
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Chris Lattner30ce3442007-12-19 23:59:04 +00001642 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001643 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001644 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001645 else if (Type->isReferenceType()) {
1646 Diag(Arg->getLocStart(),
1647 diag::warn_va_start_of_reference_type_is_undefined);
1648 Diag(ParamLoc, diag::note_parameter_type) << Type;
1649 }
1650
Chris Lattner30ce3442007-12-19 23:59:04 +00001651 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001652}
Chris Lattner30ce3442007-12-19 23:59:04 +00001653
Chris Lattner1b9a0792007-12-20 00:26:33 +00001654/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1655/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001656bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1657 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001658 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001659 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001660 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001661 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001662 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001663 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001664 << SourceRange(TheCall->getArg(2)->getLocStart(),
1665 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001666
John Wiegley429bb272011-04-08 18:41:53 +00001667 ExprResult OrigArg0 = TheCall->getArg(0);
1668 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001669
Chris Lattner1b9a0792007-12-20 00:26:33 +00001670 // Do standard promotions between the two arguments, returning their common
1671 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001672 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001673 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1674 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001675
1676 // Make sure any conversions are pushed back into the call; this is
1677 // type safe since unordered compare builtins are declared as "_Bool
1678 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001679 TheCall->setArg(0, OrigArg0.get());
1680 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001681
John Wiegley429bb272011-04-08 18:41:53 +00001682 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001683 return false;
1684
Chris Lattner1b9a0792007-12-20 00:26:33 +00001685 // If the common type isn't a real floating type, then the arguments were
1686 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001687 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001688 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001689 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001690 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1691 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner1b9a0792007-12-20 00:26:33 +00001693 return false;
1694}
1695
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001696/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1697/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001698/// to check everything. We expect the last argument to be a floating point
1699/// value.
1700bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1701 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001702 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001703 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001704 if (TheCall->getNumArgs() > NumArgs)
1705 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001706 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001707 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001708 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 (*(TheCall->arg_end()-1))->getLocEnd());
1710
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001711 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001712
Eli Friedman9ac6f622009-08-31 20:06:00 +00001713 if (OrigArg->isTypeDependent())
1714 return false;
1715
Chris Lattner81368fb2010-05-06 05:50:07 +00001716 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001717 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001718 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001719 diag::err_typecheck_call_invalid_unary_fp)
1720 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Chris Lattner81368fb2010-05-06 05:50:07 +00001722 // If this is an implicit conversion from float -> double, remove it.
1723 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1724 Expr *CastArg = Cast->getSubExpr();
1725 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1726 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1727 "promotion from float to double is the only expected cast here");
1728 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001729 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001730 }
1731 }
1732
Eli Friedman9ac6f622009-08-31 20:06:00 +00001733 return false;
1734}
1735
Eli Friedmand38617c2008-05-14 19:38:39 +00001736/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1737// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001738ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001739 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001740 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001741 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001742 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1743 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001744
Nate Begeman37b6a572010-06-08 00:16:34 +00001745 // Determine which of the following types of shufflevector we're checking:
1746 // 1) unary, vector mask: (lhs, mask)
1747 // 2) binary, vector mask: (lhs, rhs, mask)
1748 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1749 QualType resType = TheCall->getArg(0)->getType();
1750 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001751
Douglas Gregorcde01732009-05-19 22:10:17 +00001752 if (!TheCall->getArg(0)->isTypeDependent() &&
1753 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001754 QualType LHSType = TheCall->getArg(0)->getType();
1755 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001756
Craig Topperbbe759c2013-07-29 06:47:04 +00001757 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1758 return ExprError(Diag(TheCall->getLocStart(),
1759 diag::err_shufflevector_non_vector)
1760 << SourceRange(TheCall->getArg(0)->getLocStart(),
1761 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001762
Nate Begeman37b6a572010-06-08 00:16:34 +00001763 numElements = LHSType->getAs<VectorType>()->getNumElements();
1764 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Nate Begeman37b6a572010-06-08 00:16:34 +00001766 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1767 // with mask. If so, verify that RHS is an integer vector type with the
1768 // same number of elts as lhs.
1769 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001770 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001771 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001772 return ExprError(Diag(TheCall->getLocStart(),
1773 diag::err_shufflevector_incompatible_vector)
1774 << SourceRange(TheCall->getArg(1)->getLocStart(),
1775 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001776 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001777 return ExprError(Diag(TheCall->getLocStart(),
1778 diag::err_shufflevector_incompatible_vector)
1779 << SourceRange(TheCall->getArg(0)->getLocStart(),
1780 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001781 } else if (numElements != numResElements) {
1782 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001783 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001784 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001785 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001786 }
1787
1788 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001789 if (TheCall->getArg(i)->isTypeDependent() ||
1790 TheCall->getArg(i)->isValueDependent())
1791 continue;
1792
Nate Begeman37b6a572010-06-08 00:16:34 +00001793 llvm::APSInt Result(32);
1794 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1795 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001796 diag::err_shufflevector_nonconstant_argument)
1797 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001798
Craig Topper6f4f8082013-08-03 17:40:38 +00001799 // Allow -1 which will be translated to undef in the IR.
1800 if (Result.isSigned() && Result.isAllOnesValue())
1801 continue;
1802
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001803 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001804 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001805 diag::err_shufflevector_argument_too_large)
1806 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001807 }
1808
Chris Lattner5f9e2722011-07-23 10:55:15 +00001809 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001810
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001811 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001812 exprs.push_back(TheCall->getArg(i));
1813 TheCall->setArg(i, 0);
1814 }
1815
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001816 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001817 TheCall->getCallee()->getLocStart(),
1818 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001819}
Chris Lattner30ce3442007-12-19 23:59:04 +00001820
Daniel Dunbar4493f792008-07-21 22:59:13 +00001821/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1822// This is declared to take (const void*, ...) and can take two
1823// optional constant int args.
1824bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001825 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001826
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001827 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001828 return Diag(TheCall->getLocEnd(),
1829 diag::err_typecheck_call_too_many_args_at_most)
1830 << 0 /*function call*/ << 3 << NumArgs
1831 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001832
1833 // Argument 0 is checked for us and the remaining arguments must be
1834 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001835 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001836 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001837
1838 // We can't check the value of a dependent argument.
1839 if (Arg->isTypeDependent() || Arg->isValueDependent())
1840 continue;
1841
Eli Friedman9aef7262009-12-04 00:30:06 +00001842 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001843 if (SemaBuiltinConstantArg(TheCall, i, Result))
1844 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Daniel Dunbar4493f792008-07-21 22:59:13 +00001846 // FIXME: gcc issues a warning and rewrites these to 0. These
1847 // seems especially odd for the third argument since the default
1848 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001849 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001850 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001851 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001852 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001853 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001854 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001855 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001856 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001857 }
1858 }
1859
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001860 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001861}
1862
Eric Christopher691ebc32010-04-17 02:26:23 +00001863/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1864/// TheCall is a constant expression.
1865bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1866 llvm::APSInt &Result) {
1867 Expr *Arg = TheCall->getArg(ArgNum);
1868 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1869 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1870
1871 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1872
1873 if (!Arg->isIntegerConstantExpr(Result, Context))
1874 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001875 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001876
Chris Lattner21fb98e2009-09-23 06:06:36 +00001877 return false;
1878}
1879
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001880/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1881/// int type). This simply type checks that type is one of the defined
1882/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001883// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001884bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001885 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001886
1887 // We can't check the value of a dependent argument.
1888 if (TheCall->getArg(1)->isTypeDependent() ||
1889 TheCall->getArg(1)->isValueDependent())
1890 return false;
1891
Eric Christopher691ebc32010-04-17 02:26:23 +00001892 // Check constant-ness first.
1893 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1894 return true;
1895
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001896 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001897 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001898 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1899 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001900 }
1901
1902 return false;
1903}
1904
Eli Friedman586d6a82009-05-03 06:04:26 +00001905/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001906/// This checks that val is a constant 1.
1907bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1908 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001909 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001910
Eric Christopher691ebc32010-04-17 02:26:23 +00001911 // TODO: This is less than ideal. Overload this to take a value.
1912 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1913 return true;
1914
1915 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001916 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1917 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1918
1919 return false;
1920}
1921
Richard Smith0e218972013-08-05 18:49:43 +00001922namespace {
1923enum StringLiteralCheckType {
1924 SLCT_NotALiteral,
1925 SLCT_UncheckedLiteral,
1926 SLCT_CheckedLiteral
1927};
1928}
1929
Richard Smith831421f2012-06-25 20:30:08 +00001930// Determine if an expression is a string literal or constant string.
1931// If this function returns false on the arguments to a function expecting a
1932// format string, we will usually need to emit a warning.
1933// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001934static StringLiteralCheckType
1935checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1936 bool HasVAListArg, unsigned format_idx,
1937 unsigned firstDataArg, Sema::FormatStringType Type,
1938 Sema::VariadicCallType CallType, bool InFunctionCall,
1939 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001940 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001941 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001942 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001943
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001944 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001945
Richard Smith0e218972013-08-05 18:49:43 +00001946 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001947 // Technically -Wformat-nonliteral does not warn about this case.
1948 // The behavior of printf and friends in this case is implementation
1949 // dependent. Ideally if the format string cannot be null then
1950 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001951 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001952
Ted Kremenekd30ef872009-01-12 23:09:09 +00001953 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001954 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001955 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001956 // The expression is a literal if both sub-expressions were, and it was
1957 // completely checked only if both sub-expressions were checked.
1958 const AbstractConditionalOperator *C =
1959 cast<AbstractConditionalOperator>(E);
1960 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001961 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001962 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001963 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001964 if (Left == SLCT_NotALiteral)
1965 return SLCT_NotALiteral;
1966 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00001967 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001968 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001969 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001970 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001971 }
1972
1973 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001974 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1975 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001976 }
1977
John McCall56ca35d2011-02-17 10:25:35 +00001978 case Stmt::OpaqueValueExprClass:
1979 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1980 E = src;
1981 goto tryAgain;
1982 }
Richard Smith831421f2012-06-25 20:30:08 +00001983 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001984
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001985 case Stmt::PredefinedExprClass:
1986 // While __func__, etc., are technically not string literals, they
1987 // cannot contain format specifiers and thus are not a security
1988 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001989 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001990
Ted Kremenek082d9362009-03-20 21:35:28 +00001991 case Stmt::DeclRefExprClass: {
1992 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Ted Kremenek082d9362009-03-20 21:35:28 +00001994 // As an exception, do not flag errors for variables binding to
1995 // const string literals.
1996 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1997 bool isConstant = false;
1998 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001999
Richard Smith0e218972013-08-05 18:49:43 +00002000 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2001 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002002 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00002003 isConstant = T.isConstant(S.Context) &&
2004 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002005 } else if (T->isObjCObjectPointerType()) {
2006 // In ObjC, there is usually no "const ObjectPointer" type,
2007 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002008 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002009 }
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenek082d9362009-03-20 21:35:28 +00002011 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002012 if (const Expr *Init = VD->getAnyInitializer()) {
2013 // Look through initializers like const char c[] = { "foo" }
2014 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2015 if (InitList->isStringLiteralInit())
2016 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2017 }
Richard Smith0e218972013-08-05 18:49:43 +00002018 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002019 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002020 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002021 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002022 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002023 }
Mike Stump1eb44332009-09-09 15:08:12 +00002024
Anders Carlssond966a552009-06-28 19:55:58 +00002025 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2026 // special check to see if the format string is a function parameter
2027 // of the function calling the printf function. If the function
2028 // has an attribute indicating it is a printf-like function, then we
2029 // should suppress warnings concerning non-literals being used in a call
2030 // to a vprintf function. For example:
2031 //
2032 // void
2033 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2034 // va_list ap;
2035 // va_start(ap, fmt);
2036 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2037 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002038 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002039 if (HasVAListArg) {
2040 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2041 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2042 int PVIndex = PV->getFunctionScopeIndex() + 1;
2043 for (specific_attr_iterator<FormatAttr>
2044 i = ND->specific_attr_begin<FormatAttr>(),
2045 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2046 FormatAttr *PVFormat = *i;
2047 // adjust for implicit parameter
2048 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2049 if (MD->isInstance())
2050 ++PVIndex;
2051 // We also check if the formats are compatible.
2052 // We can't pass a 'scanf' string to a 'printf' function.
2053 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002054 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002055 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002056 }
2057 }
2058 }
2059 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002060 }
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Richard Smith831421f2012-06-25 20:30:08 +00002062 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002063 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002064
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002065 case Stmt::CallExprClass:
2066 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002067 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002068 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2069 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2070 unsigned ArgIndex = FA->getFormatIdx();
2071 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2072 if (MD->isInstance())
2073 --ArgIndex;
2074 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Richard Smith0e218972013-08-05 18:49:43 +00002076 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002077 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002078 Type, CallType, InFunctionCall,
2079 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002080 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2081 unsigned BuiltinID = FD->getBuiltinID();
2082 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2083 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2084 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002085 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002086 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002087 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002088 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002089 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002090 }
2091 }
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Richard Smith831421f2012-06-25 20:30:08 +00002093 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002094 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002095 case Stmt::ObjCStringLiteralClass:
2096 case Stmt::StringLiteralClass: {
2097 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Ted Kremenek082d9362009-03-20 21:35:28 +00002099 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002100 StrE = ObjCFExpr->getString();
2101 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002102 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Ted Kremenekd30ef872009-01-12 23:09:09 +00002104 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002105 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2106 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002107 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002108 }
Mike Stump1eb44332009-09-09 15:08:12 +00002109
Richard Smith831421f2012-06-25 20:30:08 +00002110 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Ted Kremenek082d9362009-03-20 21:35:28 +00002113 default:
Richard Smith831421f2012-06-25 20:30:08 +00002114 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002115 }
2116}
2117
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002118void
Mike Stump1eb44332009-09-09 15:08:12 +00002119Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002120 const Expr * const *ExprArgs,
2121 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002122 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2123 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002124 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002125 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002126
2127 // As a special case, transparent unions initialized with zero are
2128 // considered null for the purposes of the nonnull attribute.
2129 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2130 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2131 if (const CompoundLiteralExpr *CLE =
2132 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2133 if (const InitListExpr *ILE =
2134 dyn_cast<InitListExpr>(CLE->getInitializer()))
2135 ArgExpr = ILE->getInit(0);
2136 }
2137
2138 bool Result;
2139 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002140 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002141 }
2142}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002143
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002144Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmancaa5ab22013-09-03 21:02:22 +00002145 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002146 .Case("scanf", FST_Scanf)
2147 .Cases("printf", "printf0", FST_Printf)
2148 .Cases("NSString", "CFString", FST_NSString)
2149 .Case("strftime", FST_Strftime)
2150 .Case("strfmon", FST_Strfmon)
2151 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2152 .Default(FST_Unknown);
2153}
2154
Jordan Roseddcfbc92012-07-19 18:10:23 +00002155/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002156/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002157/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002158bool Sema::CheckFormatArguments(const FormatAttr *Format,
2159 ArrayRef<const Expr *> Args,
2160 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002161 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002162 SourceLocation Loc, SourceRange Range,
2163 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002164 FormatStringInfo FSI;
2165 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002166 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002167 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002168 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002169 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002170}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002171
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002172bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002173 bool HasVAListArg, unsigned format_idx,
2174 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002175 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002176 SourceLocation Loc, SourceRange Range,
2177 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002178 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002179 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002180 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002181 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002182 }
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002184 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Chris Lattner59907c42007-08-10 20:18:51 +00002186 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002187 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002188 // Dynamically generated format strings are difficult to
2189 // automatically vet at compile time. Requiring that format strings
2190 // are string literals: (1) permits the checking of format strings by
2191 // the compiler and thereby (2) can practically remove the source of
2192 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002193
Mike Stump1eb44332009-09-09 15:08:12 +00002194 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002195 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002196 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002197 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002198 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002199 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2200 format_idx, firstDataArg, Type, CallType,
2201 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002202 if (CT != SLCT_NotALiteral)
2203 // Literal format string found, check done!
2204 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002205
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002206 // Strftime is particular as it always uses a single 'time' argument,
2207 // so it is safe to pass a non-literal string.
2208 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002209 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002210
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002211 // Do not emit diag when the string param is a macro expansion and the
2212 // format is either NSString or CFString. This is a hack to prevent
2213 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2214 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002215 if (Type == FST_NSString &&
2216 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002217 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002218
Chris Lattner655f1412009-04-29 04:59:47 +00002219 // If there are no arguments specified, warn with -Wformat-security, otherwise
2220 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002221 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002222 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002223 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002224 << OrigFormatExpr->getSourceRange();
2225 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002226 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002227 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002228 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002229 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002230}
Ted Kremenek71895b92007-08-14 17:39:48 +00002231
Ted Kremeneke0e53132010-01-28 23:39:18 +00002232namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002233class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2234protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002235 Sema &S;
2236 const StringLiteral *FExpr;
2237 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002238 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002239 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002240 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002241 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002242 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002243 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002244 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002245 bool usesPositionalArgs;
2246 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002247 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002248 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002249 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002250public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002251 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002252 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002253 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002254 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002255 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002256 Sema::VariadicCallType callType,
2257 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002258 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002259 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2260 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002261 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002262 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002263 inFunctionCall(inFunctionCall), CallType(callType),
2264 CheckedVarArgs(CheckedVarArgs) {
2265 CoveredArgs.resize(numDataArgs);
2266 CoveredArgs.reset();
2267 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002268
Ted Kremenek07d161f2010-01-29 01:50:07 +00002269 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002270
Ted Kremenek826a3452010-07-16 02:11:22 +00002271 void HandleIncompleteSpecifier(const char *startSpecifier,
2272 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002273
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002274 void HandleInvalidLengthModifier(
2275 const analyze_format_string::FormatSpecifier &FS,
2276 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002277 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002278
Hans Wennborg76517422012-02-22 10:17:01 +00002279 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002280 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002281 const char *startSpecifier, unsigned specifierLen);
2282
2283 void HandleNonStandardConversionSpecifier(
2284 const analyze_format_string::ConversionSpecifier &CS,
2285 const char *startSpecifier, unsigned specifierLen);
2286
Hans Wennborgf8562642012-03-09 10:10:54 +00002287 virtual void HandlePosition(const char *startPos, unsigned posLen);
2288
Ted Kremenekefaff192010-02-27 01:41:03 +00002289 virtual void HandleInvalidPosition(const char *startSpecifier,
2290 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002291 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002292
2293 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2294
Ted Kremeneke0e53132010-01-28 23:39:18 +00002295 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002296
Richard Trieu55733de2011-10-28 00:41:25 +00002297 template <typename Range>
2298 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2299 const Expr *ArgumentExpr,
2300 PartialDiagnostic PDiag,
2301 SourceLocation StringLoc,
2302 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002303 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002304
Ted Kremenek826a3452010-07-16 02:11:22 +00002305protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002306 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2307 const char *startSpec,
2308 unsigned specifierLen,
2309 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002310
2311 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2312 const char *startSpec,
2313 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002314
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002315 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002316 CharSourceRange getSpecifierRange(const char *startSpecifier,
2317 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002318 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002319
Ted Kremenek0d277352010-01-29 01:06:55 +00002320 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002321
2322 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2323 const analyze_format_string::ConversionSpecifier &CS,
2324 const char *startSpecifier, unsigned specifierLen,
2325 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002326
2327 template <typename Range>
2328 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2329 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002330 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002331
2332 void CheckPositionalAndNonpositionalArgs(
2333 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002334};
2335}
2336
Ted Kremenek826a3452010-07-16 02:11:22 +00002337SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002338 return OrigFormatExpr->getSourceRange();
2339}
2340
Ted Kremenek826a3452010-07-16 02:11:22 +00002341CharSourceRange CheckFormatHandler::
2342getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002343 SourceLocation Start = getLocationOfByte(startSpecifier);
2344 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2345
2346 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002347 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002348
2349 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002350}
2351
Ted Kremenek826a3452010-07-16 02:11:22 +00002352SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002353 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002354}
2355
Ted Kremenek826a3452010-07-16 02:11:22 +00002356void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2357 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002358 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2359 getLocationOfByte(startSpecifier),
2360 /*IsStringLocation*/true,
2361 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002362}
2363
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002364void CheckFormatHandler::HandleInvalidLengthModifier(
2365 const analyze_format_string::FormatSpecifier &FS,
2366 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002367 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002368 using namespace analyze_format_string;
2369
2370 const LengthModifier &LM = FS.getLengthModifier();
2371 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2372
2373 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002374 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002375 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002376 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002377 getLocationOfByte(LM.getStart()),
2378 /*IsStringLocation*/true,
2379 getSpecifierRange(startSpecifier, specifierLen));
2380
2381 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2382 << FixedLM->toString()
2383 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2384
2385 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002386 FixItHint Hint;
2387 if (DiagID == diag::warn_format_nonsensical_length)
2388 Hint = FixItHint::CreateRemoval(LMRange);
2389
2390 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002391 getLocationOfByte(LM.getStart()),
2392 /*IsStringLocation*/true,
2393 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002394 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002395 }
2396}
2397
Hans Wennborg76517422012-02-22 10:17:01 +00002398void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002399 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002400 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002401 using namespace analyze_format_string;
2402
2403 const LengthModifier &LM = FS.getLengthModifier();
2404 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2405
2406 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002407 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002408 if (FixedLM) {
2409 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2410 << LM.toString() << 0,
2411 getLocationOfByte(LM.getStart()),
2412 /*IsStringLocation*/true,
2413 getSpecifierRange(startSpecifier, specifierLen));
2414
2415 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2416 << FixedLM->toString()
2417 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2418
2419 } else {
2420 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2421 << LM.toString() << 0,
2422 getLocationOfByte(LM.getStart()),
2423 /*IsStringLocation*/true,
2424 getSpecifierRange(startSpecifier, specifierLen));
2425 }
Hans Wennborg76517422012-02-22 10:17:01 +00002426}
2427
2428void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2429 const analyze_format_string::ConversionSpecifier &CS,
2430 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002431 using namespace analyze_format_string;
2432
2433 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002434 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002435 if (FixedCS) {
2436 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2437 << CS.toString() << /*conversion specifier*/1,
2438 getLocationOfByte(CS.getStart()),
2439 /*IsStringLocation*/true,
2440 getSpecifierRange(startSpecifier, specifierLen));
2441
2442 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2443 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2444 << FixedCS->toString()
2445 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2446 } else {
2447 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2448 << CS.toString() << /*conversion specifier*/1,
2449 getLocationOfByte(CS.getStart()),
2450 /*IsStringLocation*/true,
2451 getSpecifierRange(startSpecifier, specifierLen));
2452 }
Hans Wennborg76517422012-02-22 10:17:01 +00002453}
2454
Hans Wennborgf8562642012-03-09 10:10:54 +00002455void CheckFormatHandler::HandlePosition(const char *startPos,
2456 unsigned posLen) {
2457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2458 getLocationOfByte(startPos),
2459 /*IsStringLocation*/true,
2460 getSpecifierRange(startPos, posLen));
2461}
2462
Ted Kremenekefaff192010-02-27 01:41:03 +00002463void
Ted Kremenek826a3452010-07-16 02:11:22 +00002464CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2465 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002466 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2467 << (unsigned) p,
2468 getLocationOfByte(startPos), /*IsStringLocation*/true,
2469 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002470}
2471
Ted Kremenek826a3452010-07-16 02:11:22 +00002472void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002473 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002474 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2475 getLocationOfByte(startPos),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002478}
2479
Ted Kremenek826a3452010-07-16 02:11:22 +00002480void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002481 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002482 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002483 EmitFormatDiagnostic(
2484 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2485 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2486 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002487 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002488}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002489
Jordan Rose48716662012-07-19 18:10:08 +00002490// Note that this may return NULL if there was an error parsing or building
2491// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002492const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002493 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002494}
2495
2496void CheckFormatHandler::DoneProcessing() {
2497 // Does the number of data arguments exceed the number of
2498 // format conversions in the format string?
2499 if (!HasVAListArg) {
2500 // Find any arguments that weren't covered.
2501 CoveredArgs.flip();
2502 signed notCoveredArg = CoveredArgs.find_first();
2503 if (notCoveredArg >= 0) {
2504 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002505 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2506 SourceLocation Loc = E->getLocStart();
2507 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2508 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2509 Loc, /*IsStringLocation*/false,
2510 getFormatStringRange());
2511 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002512 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002513 }
2514 }
2515}
2516
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002517bool
2518CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2519 SourceLocation Loc,
2520 const char *startSpec,
2521 unsigned specifierLen,
2522 const char *csStart,
2523 unsigned csLen) {
2524
2525 bool keepGoing = true;
2526 if (argIndex < NumDataArgs) {
2527 // Consider the argument coverered, even though the specifier doesn't
2528 // make sense.
2529 CoveredArgs.set(argIndex);
2530 }
2531 else {
2532 // If argIndex exceeds the number of data arguments we
2533 // don't issue a warning because that is just a cascade of warnings (and
2534 // they may have intended '%%' anyway). We don't want to continue processing
2535 // the format string after this point, however, as we will like just get
2536 // gibberish when trying to match arguments.
2537 keepGoing = false;
2538 }
2539
Richard Trieu55733de2011-10-28 00:41:25 +00002540 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2541 << StringRef(csStart, csLen),
2542 Loc, /*IsStringLocation*/true,
2543 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002544
2545 return keepGoing;
2546}
2547
Richard Trieu55733de2011-10-28 00:41:25 +00002548void
2549CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2550 const char *startSpec,
2551 unsigned specifierLen) {
2552 EmitFormatDiagnostic(
2553 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2554 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2555}
2556
Ted Kremenek666a1972010-07-26 19:45:42 +00002557bool
2558CheckFormatHandler::CheckNumArgs(
2559 const analyze_format_string::FormatSpecifier &FS,
2560 const analyze_format_string::ConversionSpecifier &CS,
2561 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2562
2563 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002564 PartialDiagnostic PDiag = FS.usesPositionalArg()
2565 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2566 << (argIndex+1) << NumDataArgs)
2567 : S.PDiag(diag::warn_printf_insufficient_data_args);
2568 EmitFormatDiagnostic(
2569 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2570 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002571 return false;
2572 }
2573 return true;
2574}
2575
Richard Trieu55733de2011-10-28 00:41:25 +00002576template<typename Range>
2577void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2578 SourceLocation Loc,
2579 bool IsStringLocation,
2580 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002581 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002582 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002583 Loc, IsStringLocation, StringRange, FixIt);
2584}
2585
2586/// \brief If the format string is not within the funcion call, emit a note
2587/// so that the function call and string are in diagnostic messages.
2588///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002589/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002590/// call and only one diagnostic message will be produced. Otherwise, an
2591/// extra note will be emitted pointing to location of the format string.
2592///
2593/// \param ArgumentExpr the expression that is passed as the format string
2594/// argument in the function call. Used for getting locations when two
2595/// diagnostics are emitted.
2596///
2597/// \param PDiag the callee should already have provided any strings for the
2598/// diagnostic message. This function only adds locations and fixits
2599/// to diagnostics.
2600///
2601/// \param Loc primary location for diagnostic. If two diagnostics are
2602/// required, one will be at Loc and a new SourceLocation will be created for
2603/// the other one.
2604///
2605/// \param IsStringLocation if true, Loc points to the format string should be
2606/// used for the note. Otherwise, Loc points to the argument list and will
2607/// be used with PDiag.
2608///
2609/// \param StringRange some or all of the string to highlight. This is
2610/// templated so it can accept either a CharSourceRange or a SourceRange.
2611///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002612/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002613template<typename Range>
2614void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2615 const Expr *ArgumentExpr,
2616 PartialDiagnostic PDiag,
2617 SourceLocation Loc,
2618 bool IsStringLocation,
2619 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002620 ArrayRef<FixItHint> FixIt) {
2621 if (InFunctionCall) {
2622 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2623 D << StringRange;
2624 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2625 I != E; ++I) {
2626 D << *I;
2627 }
2628 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002629 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2630 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002631
2632 const Sema::SemaDiagnosticBuilder &Note =
2633 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2634 diag::note_format_string_defined);
2635
2636 Note << StringRange;
2637 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2638 I != E; ++I) {
2639 Note << *I;
2640 }
Richard Trieu55733de2011-10-28 00:41:25 +00002641 }
2642}
2643
Ted Kremenek826a3452010-07-16 02:11:22 +00002644//===--- CHECK: Printf format string checking ------------------------------===//
2645
2646namespace {
2647class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002648 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002649public:
2650 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2651 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002652 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002653 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002654 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002655 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002656 Sema::VariadicCallType CallType,
2657 llvm::SmallBitVector &CheckedVarArgs)
2658 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2659 numDataArgs, beg, hasVAListArg, Args,
2660 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2661 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002662 {}
2663
Ted Kremenek826a3452010-07-16 02:11:22 +00002664
2665 bool HandleInvalidPrintfConversionSpecifier(
2666 const analyze_printf::PrintfSpecifier &FS,
2667 const char *startSpecifier,
2668 unsigned specifierLen);
2669
2670 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2671 const char *startSpecifier,
2672 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002673 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2674 const char *StartSpecifier,
2675 unsigned SpecifierLen,
2676 const Expr *E);
2677
Ted Kremenek826a3452010-07-16 02:11:22 +00002678 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2679 const char *startSpecifier, unsigned specifierLen);
2680 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2681 const analyze_printf::OptionalAmount &Amt,
2682 unsigned type,
2683 const char *startSpecifier, unsigned specifierLen);
2684 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2685 const analyze_printf::OptionalFlag &flag,
2686 const char *startSpecifier, unsigned specifierLen);
2687 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2688 const analyze_printf::OptionalFlag &ignoredFlag,
2689 const analyze_printf::OptionalFlag &flag,
2690 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002691 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002692 const Expr *E, const CharSourceRange &CSR);
2693
Ted Kremenek826a3452010-07-16 02:11:22 +00002694};
2695}
2696
2697bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2698 const analyze_printf::PrintfSpecifier &FS,
2699 const char *startSpecifier,
2700 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002701 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002702 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002703
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002704 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2705 getLocationOfByte(CS.getStart()),
2706 startSpecifier, specifierLen,
2707 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002708}
2709
Ted Kremenek826a3452010-07-16 02:11:22 +00002710bool CheckPrintfHandler::HandleAmount(
2711 const analyze_format_string::OptionalAmount &Amt,
2712 unsigned k, const char *startSpecifier,
2713 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002714
2715 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002716 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002717 unsigned argIndex = Amt.getArgIndex();
2718 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2720 << k,
2721 getLocationOfByte(Amt.getStart()),
2722 /*IsStringLocation*/true,
2723 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002724 // Don't do any more checking. We will just emit
2725 // spurious errors.
2726 return false;
2727 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002728
Ted Kremenek0d277352010-01-29 01:06:55 +00002729 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002730 // Although not in conformance with C99, we also allow the argument to be
2731 // an 'unsigned int' as that is a reasonably safe case. GCC also
2732 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002733 CoveredArgs.set(argIndex);
2734 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002735 if (!Arg)
2736 return false;
2737
Ted Kremenek0d277352010-01-29 01:06:55 +00002738 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002739
Hans Wennborgf3749f42012-08-07 08:11:26 +00002740 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2741 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002742
Hans Wennborgf3749f42012-08-07 08:11:26 +00002743 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002744 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002745 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002746 << T << Arg->getSourceRange(),
2747 getLocationOfByte(Amt.getStart()),
2748 /*IsStringLocation*/true,
2749 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002750 // Don't do any more checking. We will just emit
2751 // spurious errors.
2752 return false;
2753 }
2754 }
2755 }
2756 return true;
2757}
Ted Kremenek0d277352010-01-29 01:06:55 +00002758
Tom Caree4ee9662010-06-17 19:00:27 +00002759void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002760 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002761 const analyze_printf::OptionalAmount &Amt,
2762 unsigned type,
2763 const char *startSpecifier,
2764 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002765 const analyze_printf::PrintfConversionSpecifier &CS =
2766 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002767
Richard Trieu55733de2011-10-28 00:41:25 +00002768 FixItHint fixit =
2769 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2770 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2771 Amt.getConstantLength()))
2772 : FixItHint();
2773
2774 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2775 << type << CS.toString(),
2776 getLocationOfByte(Amt.getStart()),
2777 /*IsStringLocation*/true,
2778 getSpecifierRange(startSpecifier, specifierLen),
2779 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002780}
2781
Ted Kremenek826a3452010-07-16 02:11:22 +00002782void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002783 const analyze_printf::OptionalFlag &flag,
2784 const char *startSpecifier,
2785 unsigned specifierLen) {
2786 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002787 const analyze_printf::PrintfConversionSpecifier &CS =
2788 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002789 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2790 << flag.toString() << CS.toString(),
2791 getLocationOfByte(flag.getPosition()),
2792 /*IsStringLocation*/true,
2793 getSpecifierRange(startSpecifier, specifierLen),
2794 FixItHint::CreateRemoval(
2795 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002796}
2797
2798void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002799 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002800 const analyze_printf::OptionalFlag &ignoredFlag,
2801 const analyze_printf::OptionalFlag &flag,
2802 const char *startSpecifier,
2803 unsigned specifierLen) {
2804 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002805 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2806 << ignoredFlag.toString() << flag.toString(),
2807 getLocationOfByte(ignoredFlag.getPosition()),
2808 /*IsStringLocation*/true,
2809 getSpecifierRange(startSpecifier, specifierLen),
2810 FixItHint::CreateRemoval(
2811 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002812}
2813
Richard Smith831421f2012-06-25 20:30:08 +00002814// Determines if the specified is a C++ class or struct containing
2815// a member with the specified name and kind (e.g. a CXXMethodDecl named
2816// "c_str()").
2817template<typename MemberKind>
2818static llvm::SmallPtrSet<MemberKind*, 1>
2819CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2820 const RecordType *RT = Ty->getAs<RecordType>();
2821 llvm::SmallPtrSet<MemberKind*, 1> Results;
2822
2823 if (!RT)
2824 return Results;
2825 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2826 if (!RD)
2827 return Results;
2828
2829 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2830 Sema::LookupMemberName);
2831
2832 // We just need to include all members of the right kind turned up by the
2833 // filter, at this point.
2834 if (S.LookupQualifiedName(R, RT->getDecl()))
2835 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2836 NamedDecl *decl = (*I)->getUnderlyingDecl();
2837 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2838 Results.insert(FK);
2839 }
2840 return Results;
2841}
2842
2843// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002844// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002845// Returns true when a c_str() conversion method is found.
2846bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002847 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002848 const CharSourceRange &CSR) {
2849 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2850
2851 MethodSet Results =
2852 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2853
2854 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2855 MI != ME; ++MI) {
2856 const CXXMethodDecl *Method = *MI;
2857 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002858 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002859 // FIXME: Suggest parens if the expression needs them.
2860 SourceLocation EndLoc =
2861 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2862 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2863 << "c_str()"
2864 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2865 return true;
2866 }
2867 }
2868
2869 return false;
2870}
2871
Ted Kremeneke0e53132010-01-28 23:39:18 +00002872bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002873CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002874 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002875 const char *startSpecifier,
2876 unsigned specifierLen) {
2877
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002878 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002879 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002880 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002881
Ted Kremenekbaa40062010-07-19 22:01:06 +00002882 if (FS.consumesDataArgument()) {
2883 if (atFirstArg) {
2884 atFirstArg = false;
2885 usesPositionalArgs = FS.usesPositionalArg();
2886 }
2887 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002888 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2889 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002890 return false;
2891 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002892 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002893
Ted Kremenekefaff192010-02-27 01:41:03 +00002894 // First check if the field width, precision, and conversion specifier
2895 // have matching data arguments.
2896 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2897 startSpecifier, specifierLen)) {
2898 return false;
2899 }
2900
2901 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2902 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002903 return false;
2904 }
2905
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002906 if (!CS.consumesDataArgument()) {
2907 // FIXME: Technically specifying a precision or field width here
2908 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002909 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002910 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002911
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002912 // Consume the argument.
2913 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002914 if (argIndex < NumDataArgs) {
2915 // The check to see if the argIndex is valid will come later.
2916 // We set the bit here because we may exit early from this
2917 // function if we encounter some other error.
2918 CoveredArgs.set(argIndex);
2919 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002920
2921 // Check for using an Objective-C specific conversion specifier
2922 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002923 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002924 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2925 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002926 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002927
Tom Caree4ee9662010-06-17 19:00:27 +00002928 // Check for invalid use of field width
2929 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002930 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002931 startSpecifier, specifierLen);
2932 }
2933
2934 // Check for invalid use of precision
2935 if (!FS.hasValidPrecision()) {
2936 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2937 startSpecifier, specifierLen);
2938 }
2939
2940 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002941 if (!FS.hasValidThousandsGroupingPrefix())
2942 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002943 if (!FS.hasValidLeadingZeros())
2944 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2945 if (!FS.hasValidPlusPrefix())
2946 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002947 if (!FS.hasValidSpacePrefix())
2948 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002949 if (!FS.hasValidAlternativeForm())
2950 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2951 if (!FS.hasValidLeftJustified())
2952 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2953
2954 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002955 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2956 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2957 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002958 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2959 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2960 startSpecifier, specifierLen);
2961
2962 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002963 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002964 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2965 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002966 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002967 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002968 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002969 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2970 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002971
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002972 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2973 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2974
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002975 // The remaining checks depend on the data arguments.
2976 if (HasVAListArg)
2977 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002978
Ted Kremenek666a1972010-07-26 19:45:42 +00002979 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002980 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002981
Jordan Rose48716662012-07-19 18:10:08 +00002982 const Expr *Arg = getDataArg(argIndex);
2983 if (!Arg)
2984 return true;
2985
2986 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002987}
2988
Jordan Roseec087352012-09-05 22:56:26 +00002989static bool requiresParensToAddCast(const Expr *E) {
2990 // FIXME: We should have a general way to reason about operator
2991 // precedence and whether parens are actually needed here.
2992 // Take care of a few common cases where they aren't.
2993 const Expr *Inside = E->IgnoreImpCasts();
2994 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2995 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2996
2997 switch (Inside->getStmtClass()) {
2998 case Stmt::ArraySubscriptExprClass:
2999 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003000 case Stmt::CharacterLiteralClass:
3001 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003002 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003003 case Stmt::FloatingLiteralClass:
3004 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003005 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003006 case Stmt::ObjCArrayLiteralClass:
3007 case Stmt::ObjCBoolLiteralExprClass:
3008 case Stmt::ObjCBoxedExprClass:
3009 case Stmt::ObjCDictionaryLiteralClass:
3010 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003011 case Stmt::ObjCIvarRefExprClass:
3012 case Stmt::ObjCMessageExprClass:
3013 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003014 case Stmt::ObjCStringLiteralClass:
3015 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003016 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003017 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003018 case Stmt::UnaryOperatorClass:
3019 return false;
3020 default:
3021 return true;
3022 }
3023}
3024
Richard Smith831421f2012-06-25 20:30:08 +00003025bool
3026CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3027 const char *StartSpecifier,
3028 unsigned SpecifierLen,
3029 const Expr *E) {
3030 using namespace analyze_format_string;
3031 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003032 // Now type check the data expression that matches the
3033 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003034 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3035 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003036 if (!AT.isValid())
3037 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003038
Jordan Rose448ac3e2012-12-05 18:44:40 +00003039 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003040 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3041 ExprTy = TET->getUnderlyingExpr()->getType();
3042 }
3043
Jordan Rose448ac3e2012-12-05 18:44:40 +00003044 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003045 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003046
Jordan Rose614a8652012-09-05 22:56:19 +00003047 // Look through argument promotions for our error message's reported type.
3048 // This includes the integral and floating promotions, but excludes array
3049 // and function pointer decay; seeing that an argument intended to be a
3050 // string has type 'char [6]' is probably more confusing than 'char *'.
3051 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3052 if (ICE->getCastKind() == CK_IntegralCast ||
3053 ICE->getCastKind() == CK_FloatingCast) {
3054 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003055 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003056
3057 // Check if we didn't match because of an implicit cast from a 'char'
3058 // or 'short' to an 'int'. This is done because printf is a varargs
3059 // function.
3060 if (ICE->getType() == S.Context.IntTy ||
3061 ICE->getType() == S.Context.UnsignedIntTy) {
3062 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003063 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003064 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003065 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003066 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003067 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3068 // Special case for 'a', which has type 'int' in C.
3069 // Note, however, that we do /not/ want to treat multibyte constants like
3070 // 'MooV' as characters! This form is deprecated but still exists.
3071 if (ExprTy == S.Context.IntTy)
3072 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3073 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003074 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003075
Jordan Rose2cd34402012-12-05 18:44:49 +00003076 // %C in an Objective-C context prints a unichar, not a wchar_t.
3077 // If the argument is an integer of some kind, believe the %C and suggest
3078 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003079 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003080 if (ObjCContext &&
3081 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3082 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3083 !ExprTy->isCharType()) {
3084 // 'unichar' is defined as a typedef of unsigned short, but we should
3085 // prefer using the typedef if it is visible.
3086 IntendedTy = S.Context.UnsignedShortTy;
3087
3088 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3089 Sema::LookupOrdinaryName);
3090 if (S.LookupName(Result, S.getCurScope())) {
3091 NamedDecl *ND = Result.getFoundDecl();
3092 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3093 if (TD->getUnderlyingType() == IntendedTy)
3094 IntendedTy = S.Context.getTypedefType(TD);
3095 }
3096 }
3097 }
3098
3099 // Special-case some of Darwin's platform-independence types by suggesting
3100 // casts to primitive types that are known to be large enough.
3101 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003102 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003103 // Use a 'while' to peel off layers of typedefs.
3104 QualType TyTy = IntendedTy;
3105 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003106 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003107 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003108 .Case("NSInteger", S.Context.LongTy)
3109 .Case("NSUInteger", S.Context.UnsignedLongTy)
3110 .Case("SInt32", S.Context.IntTy)
3111 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003112 .Default(QualType());
3113
3114 if (!CastTy.isNull()) {
3115 ShouldNotPrintDirectly = true;
3116 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003117 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003118 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003119 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003120 }
3121 }
3122
Jordan Rose614a8652012-09-05 22:56:19 +00003123 // We may be able to offer a FixItHint if it is a supported type.
3124 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003125 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003126 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003127
Jordan Rose614a8652012-09-05 22:56:19 +00003128 if (success) {
3129 // Get the fix string from the fixed format specifier
3130 SmallString<16> buf;
3131 llvm::raw_svector_ostream os(buf);
3132 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003133
Jordan Roseec087352012-09-05 22:56:26 +00003134 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3135
Jordan Rose2cd34402012-12-05 18:44:49 +00003136 if (IntendedTy == ExprTy) {
3137 // In this case, the specifier is wrong and should be changed to match
3138 // the argument.
3139 EmitFormatDiagnostic(
3140 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3141 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3142 << E->getSourceRange(),
3143 E->getLocStart(),
3144 /*IsStringLocation*/false,
3145 SpecRange,
3146 FixItHint::CreateReplacement(SpecRange, os.str()));
3147
3148 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003149 // The canonical type for formatting this value is different from the
3150 // actual type of the expression. (This occurs, for example, with Darwin's
3151 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3152 // should be printed as 'long' for 64-bit compatibility.)
3153 // Rather than emitting a normal format/argument mismatch, we want to
3154 // add a cast to the recommended type (and correct the format string
3155 // if necessary).
3156 SmallString<16> CastBuf;
3157 llvm::raw_svector_ostream CastFix(CastBuf);
3158 CastFix << "(";
3159 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3160 CastFix << ")";
3161
3162 SmallVector<FixItHint,4> Hints;
3163 if (!AT.matchesType(S.Context, IntendedTy))
3164 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3165
3166 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3167 // If there's already a cast present, just replace it.
3168 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3169 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3170
3171 } else if (!requiresParensToAddCast(E)) {
3172 // If the expression has high enough precedence,
3173 // just write the C-style cast.
3174 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3175 CastFix.str()));
3176 } else {
3177 // Otherwise, add parens around the expression as well as the cast.
3178 CastFix << "(";
3179 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3180 CastFix.str()));
3181
3182 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3183 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3184 }
3185
Jordan Rose2cd34402012-12-05 18:44:49 +00003186 if (ShouldNotPrintDirectly) {
3187 // The expression has a type that should not be printed directly.
3188 // We extract the name from the typedef because we don't want to show
3189 // the underlying type in the diagnostic.
3190 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003191
Jordan Rose2cd34402012-12-05 18:44:49 +00003192 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3193 << Name << IntendedTy
3194 << E->getSourceRange(),
3195 E->getLocStart(), /*IsStringLocation=*/false,
3196 SpecRange, Hints);
3197 } else {
3198 // In this case, the expression could be printed using a different
3199 // specifier, but we've decided that the specifier is probably correct
3200 // and we should cast instead. Just use the normal warning message.
3201 EmitFormatDiagnostic(
3202 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3203 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3204 << E->getSourceRange(),
3205 E->getLocStart(), /*IsStringLocation*/false,
3206 SpecRange, Hints);
3207 }
Jordan Roseec087352012-09-05 22:56:26 +00003208 }
Jordan Rose614a8652012-09-05 22:56:19 +00003209 } else {
3210 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3211 SpecifierLen);
3212 // Since the warning for passing non-POD types to variadic functions
3213 // was deferred until now, we emit a warning for non-POD
3214 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003215 switch (S.isValidVarArgType(ExprTy)) {
3216 case Sema::VAK_Valid:
3217 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003218 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003219 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3220 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3221 << CSR
3222 << E->getSourceRange(),
3223 E->getLocStart(), /*IsStringLocation*/false, CSR);
3224 break;
3225
3226 case Sema::VAK_Undefined:
3227 EmitFormatDiagnostic(
3228 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003229 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003230 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003231 << CallType
3232 << AT.getRepresentativeTypeName(S.Context)
3233 << CSR
3234 << E->getSourceRange(),
3235 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003236 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003237 break;
3238
3239 case Sema::VAK_Invalid:
3240 if (ExprTy->isObjCObjectType())
3241 EmitFormatDiagnostic(
3242 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3243 << S.getLangOpts().CPlusPlus11
3244 << ExprTy
3245 << CallType
3246 << AT.getRepresentativeTypeName(S.Context)
3247 << CSR
3248 << E->getSourceRange(),
3249 E->getLocStart(), /*IsStringLocation*/false, CSR);
3250 else
3251 // FIXME: If this is an initializer list, suggest removing the braces
3252 // or inserting a cast to the target type.
3253 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3254 << isa<InitListExpr>(E) << ExprTy << CallType
3255 << AT.getRepresentativeTypeName(S.Context)
3256 << E->getSourceRange();
3257 break;
3258 }
3259
3260 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3261 "format string specifier index out of range");
3262 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003263 }
3264
Ted Kremeneke0e53132010-01-28 23:39:18 +00003265 return true;
3266}
3267
Ted Kremenek826a3452010-07-16 02:11:22 +00003268//===--- CHECK: Scanf format string checking ------------------------------===//
3269
3270namespace {
3271class CheckScanfHandler : public CheckFormatHandler {
3272public:
3273 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3274 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003275 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003276 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003277 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003278 Sema::VariadicCallType CallType,
3279 llvm::SmallBitVector &CheckedVarArgs)
3280 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3281 numDataArgs, beg, hasVAListArg,
3282 Args, formatIdx, inFunctionCall, CallType,
3283 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003284 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003285
3286 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3287 const char *startSpecifier,
3288 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003289
3290 bool HandleInvalidScanfConversionSpecifier(
3291 const analyze_scanf::ScanfSpecifier &FS,
3292 const char *startSpecifier,
3293 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003294
3295 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003296};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003297}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003298
Ted Kremenekb7c21012010-07-16 18:28:03 +00003299void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3300 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003301 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3302 getLocationOfByte(end), /*IsStringLocation*/true,
3303 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003304}
3305
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003306bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3307 const analyze_scanf::ScanfSpecifier &FS,
3308 const char *startSpecifier,
3309 unsigned specifierLen) {
3310
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003311 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003312 FS.getConversionSpecifier();
3313
3314 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3315 getLocationOfByte(CS.getStart()),
3316 startSpecifier, specifierLen,
3317 CS.getStart(), CS.getLength());
3318}
3319
Ted Kremenek826a3452010-07-16 02:11:22 +00003320bool CheckScanfHandler::HandleScanfSpecifier(
3321 const analyze_scanf::ScanfSpecifier &FS,
3322 const char *startSpecifier,
3323 unsigned specifierLen) {
3324
3325 using namespace analyze_scanf;
3326 using namespace analyze_format_string;
3327
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003328 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003329
Ted Kremenekbaa40062010-07-19 22:01:06 +00003330 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3331 // be used to decide if we are using positional arguments consistently.
3332 if (FS.consumesDataArgument()) {
3333 if (atFirstArg) {
3334 atFirstArg = false;
3335 usesPositionalArgs = FS.usesPositionalArg();
3336 }
3337 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003338 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3339 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003340 return false;
3341 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003342 }
3343
3344 // Check if the field with is non-zero.
3345 const OptionalAmount &Amt = FS.getFieldWidth();
3346 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3347 if (Amt.getConstantAmount() == 0) {
3348 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3349 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003350 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3351 getLocationOfByte(Amt.getStart()),
3352 /*IsStringLocation*/true, R,
3353 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003354 }
3355 }
3356
3357 if (!FS.consumesDataArgument()) {
3358 // FIXME: Technically specifying a precision or field width here
3359 // makes no sense. Worth issuing a warning at some point.
3360 return true;
3361 }
3362
3363 // Consume the argument.
3364 unsigned argIndex = FS.getArgIndex();
3365 if (argIndex < NumDataArgs) {
3366 // The check to see if the argIndex is valid will come later.
3367 // We set the bit here because we may exit early from this
3368 // function if we encounter some other error.
3369 CoveredArgs.set(argIndex);
3370 }
3371
Ted Kremenek1e51c202010-07-20 20:04:47 +00003372 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003373 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003374 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3375 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003376 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003377 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003378 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003379 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3380 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003381
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003382 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3383 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3384
Ted Kremenek826a3452010-07-16 02:11:22 +00003385 // The remaining checks depend on the data arguments.
3386 if (HasVAListArg)
3387 return true;
3388
Ted Kremenek666a1972010-07-26 19:45:42 +00003389 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003390 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003391
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003392 // Check that the argument type matches the format specifier.
3393 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003394 if (!Ex)
3395 return true;
3396
Hans Wennborg58e1e542012-08-07 08:59:46 +00003397 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3398 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003399 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003400 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003401 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003402
3403 if (success) {
3404 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003405 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003406 llvm::raw_svector_ostream os(buf);
3407 fixedFS.toString(os);
3408
3409 EmitFormatDiagnostic(
3410 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003411 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003412 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003413 Ex->getLocStart(),
3414 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003415 getSpecifierRange(startSpecifier, specifierLen),
3416 FixItHint::CreateReplacement(
3417 getSpecifierRange(startSpecifier, specifierLen),
3418 os.str()));
3419 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003420 EmitFormatDiagnostic(
3421 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003422 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003423 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003424 Ex->getLocStart(),
3425 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003426 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003427 }
3428 }
3429
Ted Kremenek826a3452010-07-16 02:11:22 +00003430 return true;
3431}
3432
3433void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003434 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003435 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003436 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003437 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003438 bool inFunctionCall, VariadicCallType CallType,
3439 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003440
Ted Kremeneke0e53132010-01-28 23:39:18 +00003441 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003442 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003443 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003444 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003445 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3446 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003447 return;
3448 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003449
Ted Kremeneke0e53132010-01-28 23:39:18 +00003450 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003451 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003452 const char *Str = StrRef.data();
3453 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003454 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003455
Ted Kremeneke0e53132010-01-28 23:39:18 +00003456 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003457 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003458 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003459 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003460 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3461 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003462 return;
3463 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003464
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003465 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003466 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003467 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003468 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003469 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003470
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003471 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003472 getLangOpts(),
3473 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003474 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003475 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003476 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003477 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003478 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003479
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003480 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003481 getLangOpts(),
3482 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003483 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003484 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003485}
3486
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003487//===--- CHECK: Standard memory functions ---------------------------------===//
3488
Douglas Gregor2a053a32011-05-03 20:05:22 +00003489/// \brief Determine whether the given type is a dynamic class type (e.g.,
3490/// whether it has a vtable).
3491static bool isDynamicClassType(QualType T) {
3492 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3493 if (CXXRecordDecl *Definition = Record->getDefinition())
3494 if (Definition->isDynamicClass())
3495 return true;
3496
3497 return false;
3498}
3499
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003500/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003501/// otherwise returns NULL.
3502static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003503 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003504 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3505 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3506 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003507
Chandler Carruth000d4282011-06-16 09:09:40 +00003508 return 0;
3509}
3510
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003511/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003512static QualType getSizeOfArgType(const Expr* E) {
3513 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3514 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3515 if (SizeOf->getKind() == clang::UETT_SizeOf)
3516 return SizeOf->getTypeOfArgument();
3517
3518 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003519}
3520
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003521/// \brief Check for dangerous or invalid arguments to memset().
3522///
Chandler Carruth929f0132011-06-03 06:23:57 +00003523/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003524/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3525/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003526///
3527/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003528void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003529 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003530 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003531 assert(BId != 0);
3532
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003533 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003534 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003535 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003536 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003537 return;
3538
Anna Zaks0a151a12012-01-17 00:37:07 +00003539 unsigned LastArg = (BId == Builtin::BImemset ||
3540 BId == Builtin::BIstrndup ? 1 : 2);
3541 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003542 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003543
3544 // We have special checking when the length is a sizeof expression.
3545 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3546 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3547 llvm::FoldingSetNodeID SizeOfArgID;
3548
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003549 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3550 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003551 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003552
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003553 QualType DestTy = Dest->getType();
3554 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3555 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003556
Chandler Carruth000d4282011-06-16 09:09:40 +00003557 // Never warn about void type pointers. This can be used to suppress
3558 // false positives.
3559 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003560 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003561
Chandler Carruth000d4282011-06-16 09:09:40 +00003562 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3563 // actually comparing the expressions for equality. Because computing the
3564 // expression IDs can be expensive, we only do this if the diagnostic is
3565 // enabled.
3566 if (SizeOfArg &&
3567 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3568 SizeOfArg->getExprLoc())) {
3569 // We only compute IDs for expressions if the warning is enabled, and
3570 // cache the sizeof arg's ID.
3571 if (SizeOfArgID == llvm::FoldingSetNodeID())
3572 SizeOfArg->Profile(SizeOfArgID, Context, true);
3573 llvm::FoldingSetNodeID DestID;
3574 Dest->Profile(DestID, Context, true);
3575 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003576 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3577 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003578 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003579 StringRef ReadableName = FnName->getName();
3580
Chandler Carruth000d4282011-06-16 09:09:40 +00003581 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003582 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003583 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003584 if (!PointeeTy->isIncompleteType() &&
3585 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003586 ActionIdx = 2; // If the pointee's size is sizeof(char),
3587 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003588
3589 // If the function is defined as a builtin macro, do not show macro
3590 // expansion.
3591 SourceLocation SL = SizeOfArg->getExprLoc();
3592 SourceRange DSR = Dest->getSourceRange();
3593 SourceRange SSR = SizeOfArg->getSourceRange();
3594 SourceManager &SM = PP.getSourceManager();
3595
3596 if (SM.isMacroArgExpansion(SL)) {
3597 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3598 SL = SM.getSpellingLoc(SL);
3599 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3600 SM.getSpellingLoc(DSR.getEnd()));
3601 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3602 SM.getSpellingLoc(SSR.getEnd()));
3603 }
3604
Anna Zaks90c78322012-05-30 23:14:52 +00003605 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003606 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003607 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003608 << PointeeTy
3609 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003610 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003611 << SSR);
3612 DiagRuntimeBehavior(SL, SizeOfArg,
3613 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3614 << ActionIdx
3615 << SSR);
3616
Chandler Carruth000d4282011-06-16 09:09:40 +00003617 break;
3618 }
3619 }
3620
3621 // Also check for cases where the sizeof argument is the exact same
3622 // type as the memory argument, and where it points to a user-defined
3623 // record type.
3624 if (SizeOfArgTy != QualType()) {
3625 if (PointeeTy->isRecordType() &&
3626 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3627 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3628 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3629 << FnName << SizeOfArgTy << ArgIdx
3630 << PointeeTy << Dest->getSourceRange()
3631 << LenExpr->getSourceRange());
3632 break;
3633 }
Nico Webere4a1c642011-06-14 16:14:58 +00003634 }
3635
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003636 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003637 if (isDynamicClassType(PointeeTy)) {
3638
3639 unsigned OperationType = 0;
3640 // "overwritten" if we're warning about the destination for any call
3641 // but memcmp; otherwise a verb appropriate to the call.
3642 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3643 if (BId == Builtin::BImemcpy)
3644 OperationType = 1;
3645 else if(BId == Builtin::BImemmove)
3646 OperationType = 2;
3647 else if (BId == Builtin::BImemcmp)
3648 OperationType = 3;
3649 }
3650
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003651 DiagRuntimeBehavior(
3652 Dest->getExprLoc(), Dest,
3653 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003654 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003655 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003656 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003657 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003658 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3659 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003660 DiagRuntimeBehavior(
3661 Dest->getExprLoc(), Dest,
3662 PDiag(diag::warn_arc_object_memaccess)
3663 << ArgIdx << FnName << PointeeTy
3664 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003665 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003666 continue;
John McCallf85e1932011-06-15 23:02:42 +00003667
3668 DiagRuntimeBehavior(
3669 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003670 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003671 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3672 break;
3673 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003674 }
3675}
3676
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003677// A little helper routine: ignore addition and subtraction of integer literals.
3678// This intentionally does not ignore all integer constant expressions because
3679// we don't want to remove sizeof().
3680static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3681 Ex = Ex->IgnoreParenCasts();
3682
3683 for (;;) {
3684 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3685 if (!BO || !BO->isAdditiveOp())
3686 break;
3687
3688 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3689 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3690
3691 if (isa<IntegerLiteral>(RHS))
3692 Ex = LHS;
3693 else if (isa<IntegerLiteral>(LHS))
3694 Ex = RHS;
3695 else
3696 break;
3697 }
3698
3699 return Ex;
3700}
3701
Anna Zaks0f38ace2012-08-08 21:42:23 +00003702static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3703 ASTContext &Context) {
3704 // Only handle constant-sized or VLAs, but not flexible members.
3705 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3706 // Only issue the FIXIT for arrays of size > 1.
3707 if (CAT->getSize().getSExtValue() <= 1)
3708 return false;
3709 } else if (!Ty->isVariableArrayType()) {
3710 return false;
3711 }
3712 return true;
3713}
3714
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003715// Warn if the user has made the 'size' argument to strlcpy or strlcat
3716// be the size of the source, instead of the destination.
3717void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3718 IdentifierInfo *FnName) {
3719
3720 // Don't crash if the user has the wrong number of arguments
3721 if (Call->getNumArgs() != 3)
3722 return;
3723
3724 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3725 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3726 const Expr *CompareWithSrc = NULL;
3727
3728 // Look for 'strlcpy(dst, x, sizeof(x))'
3729 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3730 CompareWithSrc = Ex;
3731 else {
3732 // Look for 'strlcpy(dst, x, strlen(x))'
3733 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003734 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003735 && SizeCall->getNumArgs() == 1)
3736 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3737 }
3738 }
3739
3740 if (!CompareWithSrc)
3741 return;
3742
3743 // Determine if the argument to sizeof/strlen is equal to the source
3744 // argument. In principle there's all kinds of things you could do
3745 // here, for instance creating an == expression and evaluating it with
3746 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3747 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3748 if (!SrcArgDRE)
3749 return;
3750
3751 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3752 if (!CompareWithSrcDRE ||
3753 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3754 return;
3755
3756 const Expr *OriginalSizeArg = Call->getArg(2);
3757 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3758 << OriginalSizeArg->getSourceRange() << FnName;
3759
3760 // Output a FIXIT hint if the destination is an array (rather than a
3761 // pointer to an array). This could be enhanced to handle some
3762 // pointers if we know the actual size, like if DstArg is 'array+2'
3763 // we could say 'sizeof(array)-2'.
3764 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003765 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003766 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003767
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003768 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003769 llvm::raw_svector_ostream OS(sizeString);
3770 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003771 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003772 OS << ")";
3773
3774 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3775 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3776 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003777}
3778
Anna Zaksc36bedc2012-02-01 19:08:57 +00003779/// Check if two expressions refer to the same declaration.
3780static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3781 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3782 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3783 return D1->getDecl() == D2->getDecl();
3784 return false;
3785}
3786
3787static const Expr *getStrlenExprArg(const Expr *E) {
3788 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3789 const FunctionDecl *FD = CE->getDirectCallee();
3790 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3791 return 0;
3792 return CE->getArg(0)->IgnoreParenCasts();
3793 }
3794 return 0;
3795}
3796
3797// Warn on anti-patterns as the 'size' argument to strncat.
3798// The correct size argument should look like following:
3799// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3800void Sema::CheckStrncatArguments(const CallExpr *CE,
3801 IdentifierInfo *FnName) {
3802 // Don't crash if the user has the wrong number of arguments.
3803 if (CE->getNumArgs() < 3)
3804 return;
3805 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3806 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3807 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3808
3809 // Identify common expressions, which are wrongly used as the size argument
3810 // to strncat and may lead to buffer overflows.
3811 unsigned PatternType = 0;
3812 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3813 // - sizeof(dst)
3814 if (referToTheSameDecl(SizeOfArg, DstArg))
3815 PatternType = 1;
3816 // - sizeof(src)
3817 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3818 PatternType = 2;
3819 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3820 if (BE->getOpcode() == BO_Sub) {
3821 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3822 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3823 // - sizeof(dst) - strlen(dst)
3824 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3825 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3826 PatternType = 1;
3827 // - sizeof(src) - (anything)
3828 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3829 PatternType = 2;
3830 }
3831 }
3832
3833 if (PatternType == 0)
3834 return;
3835
Anna Zaksafdb0412012-02-03 01:27:37 +00003836 // Generate the diagnostic.
3837 SourceLocation SL = LenArg->getLocStart();
3838 SourceRange SR = LenArg->getSourceRange();
3839 SourceManager &SM = PP.getSourceManager();
3840
3841 // If the function is defined as a builtin macro, do not show macro expansion.
3842 if (SM.isMacroArgExpansion(SL)) {
3843 SL = SM.getSpellingLoc(SL);
3844 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3845 SM.getSpellingLoc(SR.getEnd()));
3846 }
3847
Anna Zaks0f38ace2012-08-08 21:42:23 +00003848 // Check if the destination is an array (rather than a pointer to an array).
3849 QualType DstTy = DstArg->getType();
3850 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3851 Context);
3852 if (!isKnownSizeArray) {
3853 if (PatternType == 1)
3854 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3855 else
3856 Diag(SL, diag::warn_strncat_src_size) << SR;
3857 return;
3858 }
3859
Anna Zaksc36bedc2012-02-01 19:08:57 +00003860 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003861 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003862 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003863 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003864
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003865 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003866 llvm::raw_svector_ostream OS(sizeString);
3867 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003868 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003869 OS << ") - ";
3870 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003871 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003872 OS << ") - 1";
3873
Anna Zaksafdb0412012-02-03 01:27:37 +00003874 Diag(SL, diag::note_strncat_wrong_size)
3875 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003876}
3877
Ted Kremenek06de2762007-08-17 16:46:58 +00003878//===--- CHECK: Return Address of Stack Variable --------------------------===//
3879
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003880static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3881 Decl *ParentDecl);
3882static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3883 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003884
3885/// CheckReturnStackAddr - Check if a return statement returns the address
3886/// of a stack variable.
3887void
3888Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3889 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003890
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003891 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003892 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003893
3894 // Perform checking for returned stack addresses, local blocks,
3895 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003896 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003897 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003898 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003899 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003900 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003901 }
3902
3903 if (stackE == 0)
3904 return; // Nothing suspicious was found.
3905
3906 SourceLocation diagLoc;
3907 SourceRange diagRange;
3908 if (refVars.empty()) {
3909 diagLoc = stackE->getLocStart();
3910 diagRange = stackE->getSourceRange();
3911 } else {
3912 // We followed through a reference variable. 'stackE' contains the
3913 // problematic expression but we will warn at the return statement pointing
3914 // at the reference variable. We will later display the "trail" of
3915 // reference variables using notes.
3916 diagLoc = refVars[0]->getLocStart();
3917 diagRange = refVars[0]->getSourceRange();
3918 }
3919
3920 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3921 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3922 : diag::warn_ret_stack_addr)
3923 << DR->getDecl()->getDeclName() << diagRange;
3924 } else if (isa<BlockExpr>(stackE)) { // local block.
3925 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3926 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3927 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3928 } else { // local temporary.
3929 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3930 : diag::warn_ret_local_temp_addr)
3931 << diagRange;
3932 }
3933
3934 // Display the "trail" of reference variables that we followed until we
3935 // found the problematic expression using notes.
3936 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3937 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3938 // If this var binds to another reference var, show the range of the next
3939 // var, otherwise the var binds to the problematic expression, in which case
3940 // show the range of the expression.
3941 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3942 : stackE->getSourceRange();
3943 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3944 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003945 }
3946}
3947
3948/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3949/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003950/// to a location on the stack, a local block, an address of a label, or a
3951/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003952/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003953/// encounter a subexpression that (1) clearly does not lead to one of the
3954/// above problematic expressions (2) is something we cannot determine leads to
3955/// a problematic expression based on such local checking.
3956///
3957/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3958/// the expression that they point to. Such variables are added to the
3959/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003960///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003961/// EvalAddr processes expressions that are pointers that are used as
3962/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003963/// At the base case of the recursion is a check for the above problematic
3964/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003965///
3966/// This implementation handles:
3967///
3968/// * pointer-to-pointer casts
3969/// * implicit conversions from array references to pointers
3970/// * taking the address of fields
3971/// * arbitrary interplay between "&" and "*" operators
3972/// * pointer arithmetic from an address of a stack variable
3973/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003974static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3975 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003976 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00003977 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003978
Ted Kremenek06de2762007-08-17 16:46:58 +00003979 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003980 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003981 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003982 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003983 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003984
Peter Collingbournef111d932011-04-15 00:35:48 +00003985 E = E->IgnoreParens();
3986
Ted Kremenek06de2762007-08-17 16:46:58 +00003987 // Our "symbolic interpreter" is just a dispatch off the currently
3988 // viewed AST node. We then recursively traverse the AST by calling
3989 // EvalAddr and EvalVal appropriately.
3990 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003991 case Stmt::DeclRefExprClass: {
3992 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3993
3994 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3995 // If this is a reference variable, follow through to the expression that
3996 // it points to.
3997 if (V->hasLocalStorage() &&
3998 V->getType()->isReferenceType() && V->hasInit()) {
3999 // Add the reference variable to the "trail".
4000 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004001 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004002 }
4003
4004 return NULL;
4005 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004006
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004007 case Stmt::UnaryOperatorClass: {
4008 // The only unary operator that make sense to handle here
4009 // is AddrOf. All others don't make sense as pointers.
4010 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004011
John McCall2de56d12010-08-25 11:45:40 +00004012 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004013 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004014 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004015 return NULL;
4016 }
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004018 case Stmt::BinaryOperatorClass: {
4019 // Handle pointer arithmetic. All other binary operators are not valid
4020 // in this context.
4021 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004022 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004023
John McCall2de56d12010-08-25 11:45:40 +00004024 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004025 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004027 Expr *Base = B->getLHS();
4028
4029 // Determine which argument is the real pointer base. It could be
4030 // the RHS argument instead of the LHS.
4031 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004032
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004033 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004034 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004035 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004036
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004037 // For conditional operators we need to see if either the LHS or RHS are
4038 // valid DeclRefExpr*s. If one of them is valid, we return it.
4039 case Stmt::ConditionalOperatorClass: {
4040 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004042 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004043 if (Expr *lhsExpr = C->getLHS()) {
4044 // In C++, we can have a throw-expression, which has 'void' type.
4045 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004046 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004047 return LHS;
4048 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004049
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004050 // In C++, we can have a throw-expression, which has 'void' type.
4051 if (C->getRHS()->getType()->isVoidType())
4052 return NULL;
4053
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004054 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004055 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004056
4057 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004058 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004059 return E; // local block.
4060 return NULL;
4061
4062 case Stmt::AddrLabelExprClass:
4063 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004064
John McCall80ee6e82011-11-10 05:35:25 +00004065 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004066 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4067 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004068
Ted Kremenek54b52742008-08-07 00:49:01 +00004069 // For casts, we need to handle conversions from arrays to
4070 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004071 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004072 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004073 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004074 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004075 case Stmt::CXXStaticCastExprClass:
4076 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004077 case Stmt::CXXConstCastExprClass:
4078 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004079 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4080 switch (cast<CastExpr>(E)->getCastKind()) {
4081 case CK_BitCast:
4082 case CK_LValueToRValue:
4083 case CK_NoOp:
4084 case CK_BaseToDerived:
4085 case CK_DerivedToBase:
4086 case CK_UncheckedDerivedToBase:
4087 case CK_Dynamic:
4088 case CK_CPointerToObjCPointerCast:
4089 case CK_BlockPointerToObjCPointerCast:
4090 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004091 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004092
4093 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004094 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004095
4096 default:
4097 return 0;
4098 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004099 }
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Douglas Gregor03e80032011-06-21 17:03:29 +00004101 case Stmt::MaterializeTemporaryExprClass:
4102 if (Expr *Result = EvalAddr(
4103 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004104 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004105 return Result;
4106
4107 return E;
4108
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004109 // Everything else: we simply don't reason about them.
4110 default:
4111 return NULL;
4112 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004113}
Mike Stump1eb44332009-09-09 15:08:12 +00004114
Ted Kremenek06de2762007-08-17 16:46:58 +00004115
4116/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4117/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004118static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4119 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004120do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004121 // We should only be called for evaluating non-pointer expressions, or
4122 // expressions with a pointer type that are not used as references but instead
4123 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Ted Kremenek06de2762007-08-17 16:46:58 +00004125 // Our "symbolic interpreter" is just a dispatch off the currently
4126 // viewed AST node. We then recursively traverse the AST by calling
4127 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004128
4129 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004130 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004131 case Stmt::ImplicitCastExprClass: {
4132 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004133 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004134 E = IE->getSubExpr();
4135 continue;
4136 }
4137 return NULL;
4138 }
4139
John McCall80ee6e82011-11-10 05:35:25 +00004140 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004141 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004142
Douglas Gregora2813ce2009-10-23 18:54:35 +00004143 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004144 // When we hit a DeclRefExpr we are looking at code that refers to a
4145 // variable's name. If it's not a reference variable we check if it has
4146 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004147 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004148
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004149 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4150 // Check if it refers to itself, e.g. "int& i = i;".
4151 if (V == ParentDecl)
4152 return DR;
4153
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004154 if (V->hasLocalStorage()) {
4155 if (!V->getType()->isReferenceType())
4156 return DR;
4157
4158 // Reference variable, follow through to the expression that
4159 // it points to.
4160 if (V->hasInit()) {
4161 // Add the reference variable to the "trail".
4162 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004163 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004164 }
4165 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004166 }
Mike Stump1eb44332009-09-09 15:08:12 +00004167
Ted Kremenek06de2762007-08-17 16:46:58 +00004168 return NULL;
4169 }
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Ted Kremenek06de2762007-08-17 16:46:58 +00004171 case Stmt::UnaryOperatorClass: {
4172 // The only unary operator that make sense to handle here
4173 // is Deref. All others don't resolve to a "name." This includes
4174 // handling all sorts of rvalues passed to a unary operator.
4175 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004176
John McCall2de56d12010-08-25 11:45:40 +00004177 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004178 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004179
4180 return NULL;
4181 }
Mike Stump1eb44332009-09-09 15:08:12 +00004182
Ted Kremenek06de2762007-08-17 16:46:58 +00004183 case Stmt::ArraySubscriptExprClass: {
4184 // Array subscripts are potential references to data on the stack. We
4185 // retrieve the DeclRefExpr* for the array variable if it indeed
4186 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004187 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004188 }
Mike Stump1eb44332009-09-09 15:08:12 +00004189
Ted Kremenek06de2762007-08-17 16:46:58 +00004190 case Stmt::ConditionalOperatorClass: {
4191 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004192 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004193 ConditionalOperator *C = cast<ConditionalOperator>(E);
4194
Anders Carlsson39073232007-11-30 19:04:31 +00004195 // Handle the GNU extension for missing LHS.
4196 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004197 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004198 return LHS;
4199
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004200 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004201 }
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Ted Kremenek06de2762007-08-17 16:46:58 +00004203 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004204 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004205 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004206
Ted Kremenek06de2762007-08-17 16:46:58 +00004207 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004208 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004209 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004210
4211 // Check whether the member type is itself a reference, in which case
4212 // we're not going to refer to the member, but to what the member refers to.
4213 if (M->getMemberDecl()->getType()->isReferenceType())
4214 return NULL;
4215
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004216 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004217 }
Mike Stump1eb44332009-09-09 15:08:12 +00004218
Douglas Gregor03e80032011-06-21 17:03:29 +00004219 case Stmt::MaterializeTemporaryExprClass:
4220 if (Expr *Result = EvalVal(
4221 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004222 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004223 return Result;
4224
4225 return E;
4226
Ted Kremenek06de2762007-08-17 16:46:58 +00004227 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004228 // Check that we don't return or take the address of a reference to a
4229 // temporary. This is only useful in C++.
4230 if (!E->isTypeDependent() && E->isRValue())
4231 return E;
4232
4233 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004234 return NULL;
4235 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004236} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004237}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004238
4239//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4240
4241/// Check for comparisons of floating point operands using != and ==.
4242/// Issue a warning if these are no self-comparisons, as they are not likely
4243/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004244void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004245 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4246 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004247
4248 // Special case: check for x == x (which is OK).
4249 // Do not emit warnings for such cases.
4250 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4251 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4252 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004253 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004254
4255
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004256 // Special case: check for comparisons against literals that can be exactly
4257 // represented by APFloat. In such cases, do not emit a warning. This
4258 // is a heuristic: often comparison against such literals are used to
4259 // detect if a value in a variable has not changed. This clearly can
4260 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004261 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4262 if (FLL->isExact())
4263 return;
4264 } else
4265 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4266 if (FLR->isExact())
4267 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004268
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004269 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004270 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4271 if (CL->isBuiltinCall())
4272 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
David Blaikie980343b2012-07-16 20:47:22 +00004274 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4275 if (CR->isBuiltinCall())
4276 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004278 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004279 Diag(Loc, diag::warn_floatingpoint_eq)
4280 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004281}
John McCallba26e582010-01-04 23:21:16 +00004282
John McCallf2370c92010-01-06 05:24:50 +00004283//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4284//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004285
John McCallf2370c92010-01-06 05:24:50 +00004286namespace {
John McCallba26e582010-01-04 23:21:16 +00004287
John McCallf2370c92010-01-06 05:24:50 +00004288/// Structure recording the 'active' range of an integer-valued
4289/// expression.
4290struct IntRange {
4291 /// The number of bits active in the int.
4292 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004293
John McCallf2370c92010-01-06 05:24:50 +00004294 /// True if the int is known not to have negative values.
4295 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004296
John McCallf2370c92010-01-06 05:24:50 +00004297 IntRange(unsigned Width, bool NonNegative)
4298 : Width(Width), NonNegative(NonNegative)
4299 {}
John McCallba26e582010-01-04 23:21:16 +00004300
John McCall1844a6e2010-11-10 23:38:19 +00004301 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004302 static IntRange forBoolType() {
4303 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004304 }
4305
John McCall1844a6e2010-11-10 23:38:19 +00004306 /// Returns the range of an opaque value of the given integral type.
4307 static IntRange forValueOfType(ASTContext &C, QualType T) {
4308 return forValueOfCanonicalType(C,
4309 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004310 }
4311
John McCall1844a6e2010-11-10 23:38:19 +00004312 /// Returns the range of an opaque value of a canonical integral type.
4313 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004314 assert(T->isCanonicalUnqualified());
4315
4316 if (const VectorType *VT = dyn_cast<VectorType>(T))
4317 T = VT->getElementType().getTypePtr();
4318 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4319 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004320
David Majnemerf9eaf982013-06-07 22:07:20 +00004321 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004322 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004323 EnumDecl *Enum = ET->getDecl();
4324 if (!Enum->isCompleteDefinition())
4325 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004326
David Majnemerf9eaf982013-06-07 22:07:20 +00004327 unsigned NumPositive = Enum->getNumPositiveBits();
4328 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004329
David Majnemerf9eaf982013-06-07 22:07:20 +00004330 if (NumNegative == 0)
4331 return IntRange(NumPositive, true/*NonNegative*/);
4332 else
4333 return IntRange(std::max(NumPositive + 1, NumNegative),
4334 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004335 }
John McCallf2370c92010-01-06 05:24:50 +00004336
4337 const BuiltinType *BT = cast<BuiltinType>(T);
4338 assert(BT->isInteger());
4339
4340 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4341 }
4342
John McCall1844a6e2010-11-10 23:38:19 +00004343 /// Returns the "target" range of a canonical integral type, i.e.
4344 /// the range of values expressible in the type.
4345 ///
4346 /// This matches forValueOfCanonicalType except that enums have the
4347 /// full range of their type, not the range of their enumerators.
4348 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4349 assert(T->isCanonicalUnqualified());
4350
4351 if (const VectorType *VT = dyn_cast<VectorType>(T))
4352 T = VT->getElementType().getTypePtr();
4353 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4354 T = CT->getElementType().getTypePtr();
4355 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004356 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004357
4358 const BuiltinType *BT = cast<BuiltinType>(T);
4359 assert(BT->isInteger());
4360
4361 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4362 }
4363
4364 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004365 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004366 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004367 L.NonNegative && R.NonNegative);
4368 }
4369
John McCall1844a6e2010-11-10 23:38:19 +00004370 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004371 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004372 return IntRange(std::min(L.Width, R.Width),
4373 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004374 }
4375};
4376
Ted Kremenek0692a192012-01-31 05:37:37 +00004377static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4378 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004379 if (value.isSigned() && value.isNegative())
4380 return IntRange(value.getMinSignedBits(), false);
4381
4382 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004383 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004384
4385 // isNonNegative() just checks the sign bit without considering
4386 // signedness.
4387 return IntRange(value.getActiveBits(), true);
4388}
4389
Ted Kremenek0692a192012-01-31 05:37:37 +00004390static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4391 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004392 if (result.isInt())
4393 return GetValueRange(C, result.getInt(), MaxWidth);
4394
4395 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004396 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4397 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4398 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4399 R = IntRange::join(R, El);
4400 }
John McCallf2370c92010-01-06 05:24:50 +00004401 return R;
4402 }
4403
4404 if (result.isComplexInt()) {
4405 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4406 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4407 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004408 }
4409
4410 // This can happen with lossless casts to intptr_t of "based" lvalues.
4411 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004412 // FIXME: The only reason we need to pass the type in here is to get
4413 // the sign right on this one case. It would be nice if APValue
4414 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004415 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004416 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004417}
John McCallf2370c92010-01-06 05:24:50 +00004418
Eli Friedman09bddcf2013-07-08 20:20:06 +00004419static QualType GetExprType(Expr *E) {
4420 QualType Ty = E->getType();
4421 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4422 Ty = AtomicRHS->getValueType();
4423 return Ty;
4424}
4425
John McCallf2370c92010-01-06 05:24:50 +00004426/// Pseudo-evaluate the given integer expression, estimating the
4427/// range of values it might take.
4428///
4429/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004430static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004431 E = E->IgnoreParens();
4432
4433 // Try a full evaluation first.
4434 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004435 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004436 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004437
4438 // I think we only want to look through implicit casts here; if the
4439 // user has an explicit widening cast, we should treat the value as
4440 // being of the new, wider type.
4441 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004442 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004443 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4444
Eli Friedman09bddcf2013-07-08 20:20:06 +00004445 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004446
John McCall2de56d12010-08-25 11:45:40 +00004447 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004448
John McCallf2370c92010-01-06 05:24:50 +00004449 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004450 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004451 return OutputTypeRange;
4452
4453 IntRange SubRange
4454 = GetExprRange(C, CE->getSubExpr(),
4455 std::min(MaxWidth, OutputTypeRange.Width));
4456
4457 // Bail out if the subexpr's range is as wide as the cast type.
4458 if (SubRange.Width >= OutputTypeRange.Width)
4459 return OutputTypeRange;
4460
4461 // Otherwise, we take the smaller width, and we're non-negative if
4462 // either the output type or the subexpr is.
4463 return IntRange(SubRange.Width,
4464 SubRange.NonNegative || OutputTypeRange.NonNegative);
4465 }
4466
4467 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4468 // If we can fold the condition, just take that operand.
4469 bool CondResult;
4470 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4471 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4472 : CO->getFalseExpr(),
4473 MaxWidth);
4474
4475 // Otherwise, conservatively merge.
4476 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4477 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4478 return IntRange::join(L, R);
4479 }
4480
4481 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4482 switch (BO->getOpcode()) {
4483
4484 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004485 case BO_LAnd:
4486 case BO_LOr:
4487 case BO_LT:
4488 case BO_GT:
4489 case BO_LE:
4490 case BO_GE:
4491 case BO_EQ:
4492 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004493 return IntRange::forBoolType();
4494
John McCall862ff872011-07-13 06:35:24 +00004495 // The type of the assignments is the type of the LHS, so the RHS
4496 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004497 case BO_MulAssign:
4498 case BO_DivAssign:
4499 case BO_RemAssign:
4500 case BO_AddAssign:
4501 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004502 case BO_XorAssign:
4503 case BO_OrAssign:
4504 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004505 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004506
John McCall862ff872011-07-13 06:35:24 +00004507 // Simple assignments just pass through the RHS, which will have
4508 // been coerced to the LHS type.
4509 case BO_Assign:
4510 // TODO: bitfields?
4511 return GetExprRange(C, BO->getRHS(), MaxWidth);
4512
John McCallf2370c92010-01-06 05:24:50 +00004513 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004514 case BO_PtrMemD:
4515 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004516 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004517
John McCall60fad452010-01-06 22:07:33 +00004518 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004519 case BO_And:
4520 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004521 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4522 GetExprRange(C, BO->getRHS(), MaxWidth));
4523
John McCallf2370c92010-01-06 05:24:50 +00004524 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004525 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004526 // ...except that we want to treat '1 << (blah)' as logically
4527 // positive. It's an important idiom.
4528 if (IntegerLiteral *I
4529 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4530 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004531 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004532 return IntRange(R.Width, /*NonNegative*/ true);
4533 }
4534 }
4535 // fallthrough
4536
John McCall2de56d12010-08-25 11:45:40 +00004537 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004538 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004539
John McCall60fad452010-01-06 22:07:33 +00004540 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004541 case BO_Shr:
4542 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004543 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4544
4545 // If the shift amount is a positive constant, drop the width by
4546 // that much.
4547 llvm::APSInt shift;
4548 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4549 shift.isNonNegative()) {
4550 unsigned zext = shift.getZExtValue();
4551 if (zext >= L.Width)
4552 L.Width = (L.NonNegative ? 0 : 1);
4553 else
4554 L.Width -= zext;
4555 }
4556
4557 return L;
4558 }
4559
4560 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004561 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004562 return GetExprRange(C, BO->getRHS(), MaxWidth);
4563
John McCall60fad452010-01-06 22:07:33 +00004564 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004565 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004566 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004567 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004568 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004569
John McCall00fe7612011-07-14 22:39:48 +00004570 // The width of a division result is mostly determined by the size
4571 // of the LHS.
4572 case BO_Div: {
4573 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004574 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004575 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4576
4577 // If the divisor is constant, use that.
4578 llvm::APSInt divisor;
4579 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4580 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4581 if (log2 >= L.Width)
4582 L.Width = (L.NonNegative ? 0 : 1);
4583 else
4584 L.Width = std::min(L.Width - log2, MaxWidth);
4585 return L;
4586 }
4587
4588 // Otherwise, just use the LHS's width.
4589 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4590 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4591 }
4592
4593 // The result of a remainder can't be larger than the result of
4594 // either side.
4595 case BO_Rem: {
4596 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004597 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004598 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4599 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4600
4601 IntRange meet = IntRange::meet(L, R);
4602 meet.Width = std::min(meet.Width, MaxWidth);
4603 return meet;
4604 }
4605
4606 // The default behavior is okay for these.
4607 case BO_Mul:
4608 case BO_Add:
4609 case BO_Xor:
4610 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004611 break;
4612 }
4613
John McCall00fe7612011-07-14 22:39:48 +00004614 // The default case is to treat the operation as if it were closed
4615 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004616 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4617 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4618 return IntRange::join(L, R);
4619 }
4620
4621 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4622 switch (UO->getOpcode()) {
4623 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004624 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004625 return IntRange::forBoolType();
4626
4627 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004628 case UO_Deref:
4629 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004630 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004631
4632 default:
4633 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4634 }
4635 }
4636
John McCall993f43f2013-05-06 21:39:12 +00004637 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004638 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004639 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004640
Eli Friedman09bddcf2013-07-08 20:20:06 +00004641 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004642}
John McCall51313c32010-01-04 23:31:57 +00004643
Ted Kremenek0692a192012-01-31 05:37:37 +00004644static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004645 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004646}
4647
John McCall51313c32010-01-04 23:31:57 +00004648/// Checks whether the given value, which currently has the given
4649/// source semantics, has the same value when coerced through the
4650/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004651static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4652 const llvm::fltSemantics &Src,
4653 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004654 llvm::APFloat truncated = value;
4655
4656 bool ignored;
4657 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4658 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4659
4660 return truncated.bitwiseIsEqual(value);
4661}
4662
4663/// Checks whether the given value, which currently has the given
4664/// source semantics, has the same value when coerced through the
4665/// target semantics.
4666///
4667/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004668static bool IsSameFloatAfterCast(const APValue &value,
4669 const llvm::fltSemantics &Src,
4670 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004671 if (value.isFloat())
4672 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4673
4674 if (value.isVector()) {
4675 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4676 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4677 return false;
4678 return true;
4679 }
4680
4681 assert(value.isComplexFloat());
4682 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4683 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4684}
4685
Ted Kremenek0692a192012-01-31 05:37:37 +00004686static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004687
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004688static bool IsZero(Sema &S, Expr *E) {
4689 // Suppress cases where we are comparing against an enum constant.
4690 if (const DeclRefExpr *DR =
4691 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4692 if (isa<EnumConstantDecl>(DR->getDecl()))
4693 return false;
4694
4695 // Suppress cases where the '0' value is expanded from a macro.
4696 if (E->getLocStart().isMacroID())
4697 return false;
4698
John McCall323ed742010-05-06 08:58:33 +00004699 llvm::APSInt Value;
4700 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4701}
4702
John McCall372e1032010-10-06 00:25:24 +00004703static bool HasEnumType(Expr *E) {
4704 // Strip off implicit integral promotions.
4705 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004706 if (ICE->getCastKind() != CK_IntegralCast &&
4707 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004708 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004709 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004710 }
4711
4712 return E->getType()->isEnumeralType();
4713}
4714
Ted Kremenek0692a192012-01-31 05:37:37 +00004715static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004716 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004717 if (E->isValueDependent())
4718 return;
4719
John McCall2de56d12010-08-25 11:45:40 +00004720 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004721 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004722 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004723 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004724 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004725 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004726 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004727 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004728 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004729 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004730 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004731 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004732 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004733 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004734 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004735 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4736 }
4737}
4738
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004739static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004740 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004741 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004742 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004743 // 0 values are handled later by CheckTrivialUnsignedComparison().
4744 if (Value == 0)
4745 return;
4746
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004747 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004748 QualType OtherT = Other->getType();
4749 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004750 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004751 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004752 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004753 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004754 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004755
4756 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004757 bool CommonSigned = CommonT->isSignedIntegerType();
4758
4759 bool EqualityOnly = false;
4760
4761 // TODO: Investigate using GetExprRange() to get tighter bounds on
4762 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004763 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004764 unsigned OtherWidth = OtherRange.Width;
4765
4766 if (CommonSigned) {
4767 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004768 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004769 // Check that the constant is representable in type OtherT.
4770 if (ConstantSigned) {
4771 if (OtherWidth >= Value.getMinSignedBits())
4772 return;
4773 } else { // !ConstantSigned
4774 if (OtherWidth >= Value.getActiveBits() + 1)
4775 return;
4776 }
4777 } else { // !OtherSigned
4778 // Check that the constant is representable in type OtherT.
4779 // Negative values are out of range.
4780 if (ConstantSigned) {
4781 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4782 return;
4783 } else { // !ConstantSigned
4784 if (OtherWidth >= Value.getActiveBits())
4785 return;
4786 }
4787 }
4788 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004789 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004790 if (OtherWidth >= Value.getActiveBits())
4791 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004792 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004793 // Check to see if the constant is representable in OtherT.
4794 if (OtherWidth > Value.getActiveBits())
4795 return;
4796 // Check to see if the constant is equivalent to a negative value
4797 // cast to CommonT.
4798 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004799 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004800 return;
4801 // The constant value rests between values that OtherT can represent after
4802 // conversion. Relational comparison still works, but equality
4803 // comparisons will be tautological.
4804 EqualityOnly = true;
4805 } else { // OtherSigned && ConstantSigned
4806 assert(0 && "Two signed types converted to unsigned types.");
4807 }
4808 }
4809
4810 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4811
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004812 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004813 if (op == BO_EQ || op == BO_NE) {
4814 IsTrue = op == BO_NE;
4815 } else if (EqualityOnly) {
4816 return;
4817 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004818 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004819 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004820 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004821 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004822 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004823 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004824 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004825 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004826 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004827 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004828
4829 // If this is a comparison to an enum constant, include that
4830 // constant in the diagnostic.
4831 const EnumConstantDecl *ED = 0;
4832 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4833 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4834
4835 SmallString<64> PrettySourceValue;
4836 llvm::raw_svector_ostream OS(PrettySourceValue);
4837 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004838 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004839 else
4840 OS << Value;
4841
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004842 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004843 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004844 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004845}
4846
John McCall323ed742010-05-06 08:58:33 +00004847/// Analyze the operands of the given comparison. Implements the
4848/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004849static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004850 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4851 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004852}
John McCall51313c32010-01-04 23:31:57 +00004853
John McCallba26e582010-01-04 23:21:16 +00004854/// \brief Implements -Wsign-compare.
4855///
Richard Trieudd225092011-09-15 21:56:47 +00004856/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004857static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004858 // The type the comparison is being performed in.
4859 QualType T = E->getLHS()->getType();
4860 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4861 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004862 if (E->isValueDependent())
4863 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004864
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004865 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4866 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004867
4868 bool IsComparisonConstant = false;
4869
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004870 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004871 // of 'true' or 'false'.
4872 if (T->isIntegralType(S.Context)) {
4873 llvm::APSInt RHSValue;
4874 bool IsRHSIntegralLiteral =
4875 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4876 llvm::APSInt LHSValue;
4877 bool IsLHSIntegralLiteral =
4878 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4879 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4880 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4881 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4882 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4883 else
4884 IsComparisonConstant =
4885 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004886 } else if (!T->hasUnsignedIntegerRepresentation())
4887 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004888
John McCall323ed742010-05-06 08:58:33 +00004889 // We don't do anything special if this isn't an unsigned integral
4890 // comparison: we're only interested in integral comparisons, and
4891 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004892 //
4893 // We also don't care about value-dependent expressions or expressions
4894 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004895 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004896 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004897
John McCall323ed742010-05-06 08:58:33 +00004898 // Check to see if one of the (unmodified) operands is of different
4899 // signedness.
4900 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004901 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4902 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004903 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004904 signedOperand = LHS;
4905 unsignedOperand = RHS;
4906 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4907 signedOperand = RHS;
4908 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004909 } else {
John McCall323ed742010-05-06 08:58:33 +00004910 CheckTrivialUnsignedComparison(S, E);
4911 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004912 }
4913
John McCall323ed742010-05-06 08:58:33 +00004914 // Otherwise, calculate the effective range of the signed operand.
4915 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004916
John McCall323ed742010-05-06 08:58:33 +00004917 // Go ahead and analyze implicit conversions in the operands. Note
4918 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004919 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4920 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004921
John McCall323ed742010-05-06 08:58:33 +00004922 // If the signed range is non-negative, -Wsign-compare won't fire,
4923 // but we should still check for comparisons which are always true
4924 // or false.
4925 if (signedRange.NonNegative)
4926 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004927
4928 // For (in)equality comparisons, if the unsigned operand is a
4929 // constant which cannot collide with a overflowed signed operand,
4930 // then reinterpreting the signed operand as unsigned will not
4931 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004932 if (E->isEqualityOp()) {
4933 unsigned comparisonWidth = S.Context.getIntWidth(T);
4934 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004935
John McCall323ed742010-05-06 08:58:33 +00004936 // We should never be unable to prove that the unsigned operand is
4937 // non-negative.
4938 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4939
4940 if (unsignedRange.Width < comparisonWidth)
4941 return;
4942 }
4943
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004944 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4945 S.PDiag(diag::warn_mixed_sign_comparison)
4946 << LHS->getType() << RHS->getType()
4947 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004948}
4949
John McCall15d7d122010-11-11 03:21:53 +00004950/// Analyzes an attempt to assign the given value to a bitfield.
4951///
4952/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004953static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4954 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004955 assert(Bitfield->isBitField());
4956 if (Bitfield->isInvalidDecl())
4957 return false;
4958
John McCall91b60142010-11-11 05:33:51 +00004959 // White-list bool bitfields.
4960 if (Bitfield->getType()->isBooleanType())
4961 return false;
4962
Douglas Gregor46ff3032011-02-04 13:09:01 +00004963 // Ignore value- or type-dependent expressions.
4964 if (Bitfield->getBitWidth()->isValueDependent() ||
4965 Bitfield->getBitWidth()->isTypeDependent() ||
4966 Init->isValueDependent() ||
4967 Init->isTypeDependent())
4968 return false;
4969
John McCall15d7d122010-11-11 03:21:53 +00004970 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4971
Richard Smith80d4b552011-12-28 19:48:30 +00004972 llvm::APSInt Value;
4973 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004974 return false;
4975
John McCall15d7d122010-11-11 03:21:53 +00004976 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004977 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004978
4979 if (OriginalWidth <= FieldWidth)
4980 return false;
4981
Eli Friedman3a643af2012-01-26 23:11:39 +00004982 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004983 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004984 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004985
Eli Friedman3a643af2012-01-26 23:11:39 +00004986 // Check whether the stored value is equal to the original value.
4987 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004988 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004989 return false;
4990
Eli Friedman3a643af2012-01-26 23:11:39 +00004991 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004992 // therefore don't strictly fit into a signed bitfield of width 1.
4993 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004994 return false;
4995
John McCall15d7d122010-11-11 03:21:53 +00004996 std::string PrettyValue = Value.toString(10);
4997 std::string PrettyTrunc = TruncatedValue.toString(10);
4998
4999 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5000 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5001 << Init->getSourceRange();
5002
5003 return true;
5004}
5005
John McCallbeb22aa2010-11-09 23:24:47 +00005006/// Analyze the given simple or compound assignment for warning-worthy
5007/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005008static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005009 // Just recurse on the LHS.
5010 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5011
5012 // We want to recurse on the RHS as normal unless we're assigning to
5013 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005014 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005015 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005016 E->getOperatorLoc())) {
5017 // Recurse, ignoring any implicit conversions on the RHS.
5018 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5019 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005020 }
5021 }
5022
5023 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5024}
5025
John McCall51313c32010-01-04 23:31:57 +00005026/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005027static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005028 SourceLocation CContext, unsigned diag,
5029 bool pruneControlFlow = false) {
5030 if (pruneControlFlow) {
5031 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5032 S.PDiag(diag)
5033 << SourceType << T << E->getSourceRange()
5034 << SourceRange(CContext));
5035 return;
5036 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005037 S.Diag(E->getExprLoc(), diag)
5038 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5039}
5040
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005041/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005042static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005043 SourceLocation CContext, unsigned diag,
5044 bool pruneControlFlow = false) {
5045 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005046}
5047
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005048/// Diagnose an implicit cast from a literal expression. Does not warn when the
5049/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005050void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5051 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005052 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005053 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005054 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005055 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5056 T->hasUnsignedIntegerRepresentation());
5057 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005058 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005059 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005060 return;
5061
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005062 // FIXME: Force the precision of the source value down so we don't print
5063 // digits which are usually useless (we don't really care here if we
5064 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5065 // would automatically print the shortest representation, but it's a bit
5066 // tricky to implement.
David Blaikiebe0ee872012-05-15 16:56:36 +00005067 SmallString<16> PrettySourceValue;
Eli Friedman4e1a82c2013-08-29 23:44:43 +00005068 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5069 precision = (precision * 59 + 195) / 196;
5070 Value.toString(PrettySourceValue, precision);
5071
David Blaikiede7e7b82012-05-15 17:18:27 +00005072 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005073 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5074 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5075 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005076 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005077
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005078 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005079 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5080 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005081}
5082
John McCall091f23f2010-11-09 22:22:12 +00005083std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5084 if (!Range.Width) return "0";
5085
5086 llvm::APSInt ValueInRange = Value;
5087 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005088 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005089 return ValueInRange.toString(10);
5090}
5091
Hans Wennborg88617a22012-08-28 15:44:30 +00005092static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5093 if (!isa<ImplicitCastExpr>(Ex))
5094 return false;
5095
5096 Expr *InnerE = Ex->IgnoreParenImpCasts();
5097 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5098 const Type *Source =
5099 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5100 if (Target->isDependentType())
5101 return false;
5102
5103 const BuiltinType *FloatCandidateBT =
5104 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5105 const Type *BoolCandidateType = ToBool ? Target : Source;
5106
5107 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5108 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5109}
5110
5111void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5112 SourceLocation CC) {
5113 unsigned NumArgs = TheCall->getNumArgs();
5114 for (unsigned i = 0; i < NumArgs; ++i) {
5115 Expr *CurrA = TheCall->getArg(i);
5116 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5117 continue;
5118
5119 bool IsSwapped = ((i > 0) &&
5120 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5121 IsSwapped |= ((i < (NumArgs - 1)) &&
5122 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5123 if (IsSwapped) {
5124 // Warn on this floating-point to bool conversion.
5125 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5126 CurrA->getType(), CC,
5127 diag::warn_impcast_floating_point_to_bool);
5128 }
5129 }
5130}
5131
John McCall323ed742010-05-06 08:58:33 +00005132void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005133 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005134 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005135
John McCall323ed742010-05-06 08:58:33 +00005136 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5137 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5138 if (Source == Target) return;
5139 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005140
Chandler Carruth108f7562011-07-26 05:40:03 +00005141 // If the conversion context location is invalid don't complain. We also
5142 // don't want to emit a warning if the issue occurs from the expansion of
5143 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5144 // delay this check as long as possible. Once we detect we are in that
5145 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005146 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005147 return;
5148
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005149 // Diagnose implicit casts to bool.
5150 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5151 if (isa<StringLiteral>(E))
5152 // Warn on string literal to bool. Checks for string literals in logical
5153 // expressions, for instances, assert(0 && "error here"), is prevented
5154 // by a check in AnalyzeImplicitConversions().
5155 return DiagnoseImpCast(S, E, T, CC,
5156 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005157 if (Source->isFunctionType()) {
5158 // Warn on function to bool. Checks free functions and static member
5159 // functions. Weakly imported functions are excluded from the check,
5160 // since it's common to test their value to check whether the linker
5161 // found a definition for them.
5162 ValueDecl *D = 0;
5163 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5164 D = R->getDecl();
5165 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5166 D = M->getMemberDecl();
5167 }
5168
5169 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005170 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5171 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5172 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005173 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5174 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5175 QualType ReturnType;
5176 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005177 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005178 if (!ReturnType.isNull()
5179 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5180 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5181 << FixItHint::CreateInsertion(
5182 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005183 return;
5184 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005185 }
5186 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005187 }
John McCall51313c32010-01-04 23:31:57 +00005188
5189 // Strip vector types.
5190 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005191 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005192 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005193 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005194 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005195 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005196
5197 // If the vector cast is cast between two vectors of the same size, it is
5198 // a bitcast, not a conversion.
5199 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5200 return;
John McCall51313c32010-01-04 23:31:57 +00005201
5202 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5203 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5204 }
5205
5206 // Strip complex types.
5207 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005208 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005209 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005210 return;
5211
John McCallb4eb64d2010-10-08 02:01:28 +00005212 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005213 }
John McCall51313c32010-01-04 23:31:57 +00005214
5215 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5216 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5217 }
5218
5219 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5220 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5221
5222 // If the source is floating point...
5223 if (SourceBT && SourceBT->isFloatingPoint()) {
5224 // ...and the target is floating point...
5225 if (TargetBT && TargetBT->isFloatingPoint()) {
5226 // ...then warn if we're dropping FP rank.
5227
5228 // Builtin FP kinds are ordered by increasing FP rank.
5229 if (SourceBT->getKind() > TargetBT->getKind()) {
5230 // Don't warn about float constants that are precisely
5231 // representable in the target type.
5232 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005233 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005234 // Value might be a float, a float vector, or a float complex.
5235 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005236 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5237 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005238 return;
5239 }
5240
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005241 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005242 return;
5243
John McCallb4eb64d2010-10-08 02:01:28 +00005244 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005245 }
5246 return;
5247 }
5248
Ted Kremenekef9ff882011-03-10 20:03:42 +00005249 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005250 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005251 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005252 return;
5253
Chandler Carrutha5b93322011-02-17 11:05:49 +00005254 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005255 // We also want to warn on, e.g., "int i = -1.234"
5256 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5257 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5258 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5259
Chandler Carruthf65076e2011-04-10 08:36:24 +00005260 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5261 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005262 } else {
5263 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5264 }
5265 }
John McCall51313c32010-01-04 23:31:57 +00005266
Hans Wennborg88617a22012-08-28 15:44:30 +00005267 // If the target is bool, warn if expr is a function or method call.
5268 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5269 isa<CallExpr>(E)) {
5270 // Check last argument of function call to see if it is an
5271 // implicit cast from a type matching the type the result
5272 // is being cast to.
5273 CallExpr *CEx = cast<CallExpr>(E);
5274 unsigned NumArgs = CEx->getNumArgs();
5275 if (NumArgs > 0) {
5276 Expr *LastA = CEx->getArg(NumArgs - 1);
5277 Expr *InnerE = LastA->IgnoreParenImpCasts();
5278 const Type *InnerType =
5279 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5280 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5281 // Warn on this floating-point to bool conversion
5282 DiagnoseImpCast(S, E, T, CC,
5283 diag::warn_impcast_floating_point_to_bool);
5284 }
5285 }
5286 }
John McCall51313c32010-01-04 23:31:57 +00005287 return;
5288 }
5289
Richard Trieu1838ca52011-05-29 19:59:02 +00005290 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005291 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005292 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005293 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005294 SourceLocation Loc = E->getSourceRange().getBegin();
5295 if (Loc.isMacroID())
5296 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005297 if (!Loc.isMacroID() || CC.isMacroID())
5298 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5299 << T << clang::SourceRange(CC)
5300 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005301 }
5302
David Blaikieb26331b2012-06-19 21:19:06 +00005303 if (!Source->isIntegerType() || !Target->isIntegerType())
5304 return;
5305
David Blaikiebe0ee872012-05-15 16:56:36 +00005306 // TODO: remove this early return once the false positives for constant->bool
5307 // in templates, macros, etc, are reduced or removed.
5308 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5309 return;
5310
John McCall323ed742010-05-06 08:58:33 +00005311 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005312 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005313
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005314 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005315 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005316 // TODO: this should happen for bitfield stores, too.
5317 llvm::APSInt Value(32);
5318 if (E->isIntegerConstantExpr(Value, S.Context)) {
5319 if (S.SourceMgr.isInSystemMacro(CC))
5320 return;
5321
John McCall091f23f2010-11-09 22:22:12 +00005322 std::string PrettySourceValue = Value.toString(10);
5323 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005324
Ted Kremenek5e745da2011-10-22 02:37:33 +00005325 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5326 S.PDiag(diag::warn_impcast_integer_precision_constant)
5327 << PrettySourceValue << PrettyTargetValue
5328 << E->getType() << T << E->getSourceRange()
5329 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005330 return;
5331 }
5332
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005333 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5334 if (S.SourceMgr.isInSystemMacro(CC))
5335 return;
5336
David Blaikie37050842012-04-12 22:40:54 +00005337 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005338 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5339 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005340 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005341 }
5342
5343 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5344 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5345 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005346
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005347 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005348 return;
5349
John McCall323ed742010-05-06 08:58:33 +00005350 unsigned DiagID = diag::warn_impcast_integer_sign;
5351
5352 // Traditionally, gcc has warned about this under -Wsign-compare.
5353 // We also want to warn about it in -Wconversion.
5354 // So if -Wconversion is off, use a completely identical diagnostic
5355 // in the sign-compare group.
5356 // The conditional-checking code will
5357 if (ICContext) {
5358 DiagID = diag::warn_impcast_integer_sign_conditional;
5359 *ICContext = true;
5360 }
5361
John McCallb4eb64d2010-10-08 02:01:28 +00005362 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005363 }
5364
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005365 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005366 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5367 // type, to give us better diagnostics.
5368 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005369 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005370 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5371 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5372 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5373 SourceType = S.Context.getTypeDeclType(Enum);
5374 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5375 }
5376 }
5377
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005378 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5379 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005380 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5381 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005382 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005383 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005384 return;
5385
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005386 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005387 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005388 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005389
John McCall51313c32010-01-04 23:31:57 +00005390 return;
5391}
5392
David Blaikie9fb1ac52012-05-15 21:57:38 +00005393void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5394 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005395
5396void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005397 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005398 E = E->IgnoreParenImpCasts();
5399
5400 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005401 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005402
John McCallb4eb64d2010-10-08 02:01:28 +00005403 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005404 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005405 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005406 return;
5407}
5408
David Blaikie9fb1ac52012-05-15 21:57:38 +00005409void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5410 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005411 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005412
5413 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005414 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5415 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005416
5417 // If -Wconversion would have warned about either of the candidates
5418 // for a signedness conversion to the context type...
5419 if (!Suspicious) return;
5420
5421 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005422 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5423 CC))
John McCall323ed742010-05-06 08:58:33 +00005424 return;
5425
John McCall323ed742010-05-06 08:58:33 +00005426 // ...then check whether it would have warned about either of the
5427 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005428 if (E->getType() == T) return;
5429
5430 Suspicious = false;
5431 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5432 E->getType(), CC, &Suspicious);
5433 if (!Suspicious)
5434 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005435 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005436}
5437
5438/// AnalyzeImplicitConversions - Find and report any interesting
5439/// implicit conversions in the given expression. There are a couple
5440/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005441void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005442 QualType T = OrigE->getType();
5443 Expr *E = OrigE->IgnoreParenImpCasts();
5444
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005445 if (E->isTypeDependent() || E->isValueDependent())
5446 return;
5447
John McCall323ed742010-05-06 08:58:33 +00005448 // For conditional operators, we analyze the arguments as if they
5449 // were being fed directly into the output.
5450 if (isa<ConditionalOperator>(E)) {
5451 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005452 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005453 return;
5454 }
5455
Hans Wennborg88617a22012-08-28 15:44:30 +00005456 // Check implicit argument conversions for function calls.
5457 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5458 CheckImplicitArgumentConversions(S, Call, CC);
5459
John McCall323ed742010-05-06 08:58:33 +00005460 // Go ahead and check any implicit conversions we might have skipped.
5461 // The non-canonical typecheck is just an optimization;
5462 // CheckImplicitConversion will filter out dead implicit conversions.
5463 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005464 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005465
5466 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005467
5468 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005469 if (POE->getResultExpr())
5470 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005471 }
5472
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005473 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5474 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5475
John McCall323ed742010-05-06 08:58:33 +00005476 // Skip past explicit casts.
5477 if (isa<ExplicitCastExpr>(E)) {
5478 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005479 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005480 }
5481
John McCallbeb22aa2010-11-09 23:24:47 +00005482 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5483 // Do a somewhat different check with comparison operators.
5484 if (BO->isComparisonOp())
5485 return AnalyzeComparison(S, BO);
5486
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005487 // And with simple assignments.
5488 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005489 return AnalyzeAssignment(S, BO);
5490 }
John McCall323ed742010-05-06 08:58:33 +00005491
5492 // These break the otherwise-useful invariant below. Fortunately,
5493 // we don't really need to recurse into them, because any internal
5494 // expressions should have been analyzed already when they were
5495 // built into statements.
5496 if (isa<StmtExpr>(E)) return;
5497
5498 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005499 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005500
5501 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005502 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005503 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5504 bool IsLogicalOperator = BO && BO->isLogicalOp();
5505 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005506 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005507 if (!ChildExpr)
5508 continue;
5509
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005510 if (IsLogicalOperator &&
5511 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5512 // Ignore checking string literals that are in logical operators.
5513 continue;
5514 AnalyzeImplicitConversions(S, ChildExpr, CC);
5515 }
John McCall323ed742010-05-06 08:58:33 +00005516}
5517
5518} // end anonymous namespace
5519
5520/// Diagnoses "dangerous" implicit conversions within the given
5521/// expression (which is a full expression). Implements -Wconversion
5522/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005523///
5524/// \param CC the "context" location of the implicit conversion, i.e.
5525/// the most location of the syntactic entity requiring the implicit
5526/// conversion
5527void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005528 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005529 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005530 return;
5531
5532 // Don't diagnose for value- or type-dependent expressions.
5533 if (E->isTypeDependent() || E->isValueDependent())
5534 return;
5535
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005536 // Check for array bounds violations in cases where the check isn't triggered
5537 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5538 // ArraySubscriptExpr is on the RHS of a variable initialization.
5539 CheckArrayAccess(E);
5540
John McCallb4eb64d2010-10-08 02:01:28 +00005541 // This is not the right CC for (e.g.) a variable initialization.
5542 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005543}
5544
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005545/// Diagnose when expression is an integer constant expression and its evaluation
5546/// results in integer overflow
5547void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005548 if (isa<BinaryOperator>(E->IgnoreParens())) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00005549 SmallVector<PartialDiagnosticAt, 4> Diags;
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005550 E->EvaluateForOverflow(Context, &Diags);
5551 }
5552}
5553
Richard Smith6c3af3d2013-01-17 01:17:56 +00005554namespace {
5555/// \brief Visitor for expressions which looks for unsequenced operations on the
5556/// same object.
5557class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005558 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5559
Richard Smith6c3af3d2013-01-17 01:17:56 +00005560 /// \brief A tree of sequenced regions within an expression. Two regions are
5561 /// unsequenced if one is an ancestor or a descendent of the other. When we
5562 /// finish processing an expression with sequencing, such as a comma
5563 /// expression, we fold its tree nodes into its parent, since they are
5564 /// unsequenced with respect to nodes we will visit later.
5565 class SequenceTree {
5566 struct Value {
5567 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5568 unsigned Parent : 31;
5569 bool Merged : 1;
5570 };
Robert Wilhelme7205c02013-08-10 12:33:24 +00005571 SmallVector<Value, 8> Values;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005572
5573 public:
5574 /// \brief A region within an expression which may be sequenced with respect
5575 /// to some other region.
5576 class Seq {
5577 explicit Seq(unsigned N) : Index(N) {}
5578 unsigned Index;
5579 friend class SequenceTree;
5580 public:
5581 Seq() : Index(0) {}
5582 };
5583
5584 SequenceTree() { Values.push_back(Value(0)); }
5585 Seq root() const { return Seq(0); }
5586
5587 /// \brief Create a new sequence of operations, which is an unsequenced
5588 /// subset of \p Parent. This sequence of operations is sequenced with
5589 /// respect to other children of \p Parent.
5590 Seq allocate(Seq Parent) {
5591 Values.push_back(Value(Parent.Index));
5592 return Seq(Values.size() - 1);
5593 }
5594
5595 /// \brief Merge a sequence of operations into its parent.
5596 void merge(Seq S) {
5597 Values[S.Index].Merged = true;
5598 }
5599
5600 /// \brief Determine whether two operations are unsequenced. This operation
5601 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5602 /// should have been merged into its parent as appropriate.
5603 bool isUnsequenced(Seq Cur, Seq Old) {
5604 unsigned C = representative(Cur.Index);
5605 unsigned Target = representative(Old.Index);
5606 while (C >= Target) {
5607 if (C == Target)
5608 return true;
5609 C = Values[C].Parent;
5610 }
5611 return false;
5612 }
5613
5614 private:
5615 /// \brief Pick a representative for a sequence.
5616 unsigned representative(unsigned K) {
5617 if (Values[K].Merged)
5618 // Perform path compression as we go.
5619 return Values[K].Parent = representative(Values[K].Parent);
5620 return K;
5621 }
5622 };
5623
5624 /// An object for which we can track unsequenced uses.
5625 typedef NamedDecl *Object;
5626
5627 /// Different flavors of object usage which we track. We only track the
5628 /// least-sequenced usage of each kind.
5629 enum UsageKind {
5630 /// A read of an object. Multiple unsequenced reads are OK.
5631 UK_Use,
5632 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005633 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005634 UK_ModAsValue,
5635 /// A modification of an object which is not sequenced before the value
5636 /// computation of the expression, such as n++.
5637 UK_ModAsSideEffect,
5638
5639 UK_Count = UK_ModAsSideEffect + 1
5640 };
5641
5642 struct Usage {
5643 Usage() : Use(0), Seq() {}
5644 Expr *Use;
5645 SequenceTree::Seq Seq;
5646 };
5647
5648 struct UsageInfo {
5649 UsageInfo() : Diagnosed(false) {}
5650 Usage Uses[UK_Count];
5651 /// Have we issued a diagnostic for this variable already?
5652 bool Diagnosed;
5653 };
5654 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5655
5656 Sema &SemaRef;
5657 /// Sequenced regions within the expression.
5658 SequenceTree Tree;
5659 /// Declaration modifications and references which we have seen.
5660 UsageInfoMap UsageMap;
5661 /// The region we are currently within.
5662 SequenceTree::Seq Region;
5663 /// Filled in with declarations which were modified as a side-effect
5664 /// (that is, post-increment operations).
Robert Wilhelme7205c02013-08-10 12:33:24 +00005665 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005666 /// Expressions to check later. We defer checking these to reduce
5667 /// stack usage.
Robert Wilhelme7205c02013-08-10 12:33:24 +00005668 SmallVectorImpl<Expr *> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005669
5670 /// RAII object wrapping the visitation of a sequenced subexpression of an
5671 /// expression. At the end of this process, the side-effects of the evaluation
5672 /// become sequenced with respect to the value computation of the result, so
5673 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5674 /// UK_ModAsValue.
5675 struct SequencedSubexpression {
5676 SequencedSubexpression(SequenceChecker &Self)
5677 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5678 Self.ModAsSideEffect = &ModAsSideEffect;
5679 }
5680 ~SequencedSubexpression() {
5681 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5682 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5683 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5684 Self.addUsage(U, ModAsSideEffect[I].first,
5685 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5686 }
5687 Self.ModAsSideEffect = OldModAsSideEffect;
5688 }
5689
5690 SequenceChecker &Self;
Robert Wilhelme7205c02013-08-10 12:33:24 +00005691 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5692 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005693 };
5694
Richard Smith67470052013-06-20 22:21:56 +00005695 /// RAII object wrapping the visitation of a subexpression which we might
5696 /// choose to evaluate as a constant. If any subexpression is evaluated and
5697 /// found to be non-constant, this allows us to suppress the evaluation of
5698 /// the outer expression.
5699 class EvaluationTracker {
5700 public:
5701 EvaluationTracker(SequenceChecker &Self)
5702 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5703 Self.EvalTracker = this;
5704 }
5705 ~EvaluationTracker() {
5706 Self.EvalTracker = Prev;
5707 if (Prev)
5708 Prev->EvalOK &= EvalOK;
5709 }
5710
5711 bool evaluate(const Expr *E, bool &Result) {
5712 if (!EvalOK || E->isValueDependent())
5713 return false;
5714 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5715 return EvalOK;
5716 }
5717
5718 private:
5719 SequenceChecker &Self;
5720 EvaluationTracker *Prev;
5721 bool EvalOK;
5722 } *EvalTracker;
5723
Richard Smith6c3af3d2013-01-17 01:17:56 +00005724 /// \brief Find the object which is produced by the specified expression,
5725 /// if any.
5726 Object getObject(Expr *E, bool Mod) const {
5727 E = E->IgnoreParenCasts();
5728 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5729 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5730 return getObject(UO->getSubExpr(), Mod);
5731 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5732 if (BO->getOpcode() == BO_Comma)
5733 return getObject(BO->getRHS(), Mod);
5734 if (Mod && BO->isAssignmentOp())
5735 return getObject(BO->getLHS(), Mod);
5736 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5737 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5738 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5739 return ME->getMemberDecl();
5740 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5741 // FIXME: If this is a reference, map through to its value.
5742 return DRE->getDecl();
5743 return 0;
5744 }
5745
5746 /// \brief Note that an object was modified or used by an expression.
5747 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5748 Usage &U = UI.Uses[UK];
5749 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5750 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5751 ModAsSideEffect->push_back(std::make_pair(O, U));
5752 U.Use = Ref;
5753 U.Seq = Region;
5754 }
5755 }
5756 /// \brief Check whether a modification or use conflicts with a prior usage.
5757 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5758 bool IsModMod) {
5759 if (UI.Diagnosed)
5760 return;
5761
5762 const Usage &U = UI.Uses[OtherKind];
5763 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5764 return;
5765
5766 Expr *Mod = U.Use;
5767 Expr *ModOrUse = Ref;
5768 if (OtherKind == UK_Use)
5769 std::swap(Mod, ModOrUse);
5770
5771 SemaRef.Diag(Mod->getExprLoc(),
5772 IsModMod ? diag::warn_unsequenced_mod_mod
5773 : diag::warn_unsequenced_mod_use)
5774 << O << SourceRange(ModOrUse->getExprLoc());
5775 UI.Diagnosed = true;
5776 }
5777
5778 void notePreUse(Object O, Expr *Use) {
5779 UsageInfo &U = UsageMap[O];
5780 // Uses conflict with other modifications.
5781 checkUsage(O, U, Use, UK_ModAsValue, false);
5782 }
5783 void notePostUse(Object O, Expr *Use) {
5784 UsageInfo &U = UsageMap[O];
5785 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5786 addUsage(U, O, Use, UK_Use);
5787 }
5788
5789 void notePreMod(Object O, Expr *Mod) {
5790 UsageInfo &U = UsageMap[O];
5791 // Modifications conflict with other modifications and with uses.
5792 checkUsage(O, U, Mod, UK_ModAsValue, true);
5793 checkUsage(O, U, Mod, UK_Use, false);
5794 }
5795 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5796 UsageInfo &U = UsageMap[O];
5797 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5798 addUsage(U, O, Use, UK);
5799 }
5800
5801public:
Robert Wilhelme7205c02013-08-10 12:33:24 +00005802 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5803 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5804 WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005805 Visit(E);
5806 }
5807
5808 void VisitStmt(Stmt *S) {
5809 // Skip all statements which aren't expressions for now.
5810 }
5811
5812 void VisitExpr(Expr *E) {
5813 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005814 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005815 }
5816
5817 void VisitCastExpr(CastExpr *E) {
5818 Object O = Object();
5819 if (E->getCastKind() == CK_LValueToRValue)
5820 O = getObject(E->getSubExpr(), false);
5821
5822 if (O)
5823 notePreUse(O, E);
5824 VisitExpr(E);
5825 if (O)
5826 notePostUse(O, E);
5827 }
5828
5829 void VisitBinComma(BinaryOperator *BO) {
5830 // C++11 [expr.comma]p1:
5831 // Every value computation and side effect associated with the left
5832 // expression is sequenced before every value computation and side
5833 // effect associated with the right expression.
5834 SequenceTree::Seq LHS = Tree.allocate(Region);
5835 SequenceTree::Seq RHS = Tree.allocate(Region);
5836 SequenceTree::Seq OldRegion = Region;
5837
5838 {
5839 SequencedSubexpression SeqLHS(*this);
5840 Region = LHS;
5841 Visit(BO->getLHS());
5842 }
5843
5844 Region = RHS;
5845 Visit(BO->getRHS());
5846
5847 Region = OldRegion;
5848
5849 // Forget that LHS and RHS are sequenced. They are both unsequenced
5850 // with respect to other stuff.
5851 Tree.merge(LHS);
5852 Tree.merge(RHS);
5853 }
5854
5855 void VisitBinAssign(BinaryOperator *BO) {
5856 // The modification is sequenced after the value computation of the LHS
5857 // and RHS, so check it before inspecting the operands and update the
5858 // map afterwards.
5859 Object O = getObject(BO->getLHS(), true);
5860 if (!O)
5861 return VisitExpr(BO);
5862
5863 notePreMod(O, BO);
5864
5865 // C++11 [expr.ass]p7:
5866 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5867 // only once.
5868 //
5869 // Therefore, for a compound assignment operator, O is considered used
5870 // everywhere except within the evaluation of E1 itself.
5871 if (isa<CompoundAssignOperator>(BO))
5872 notePreUse(O, BO);
5873
5874 Visit(BO->getLHS());
5875
5876 if (isa<CompoundAssignOperator>(BO))
5877 notePostUse(O, BO);
5878
5879 Visit(BO->getRHS());
5880
Richard Smith418dd3e2013-06-26 23:16:51 +00005881 // C++11 [expr.ass]p1:
5882 // the assignment is sequenced [...] before the value computation of the
5883 // assignment expression.
5884 // C11 6.5.16/3 has no such rule.
5885 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5886 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005887 }
5888 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5889 VisitBinAssign(CAO);
5890 }
5891
5892 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5893 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5894 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5895 Object O = getObject(UO->getSubExpr(), true);
5896 if (!O)
5897 return VisitExpr(UO);
5898
5899 notePreMod(O, UO);
5900 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005901 // C++11 [expr.pre.incr]p1:
5902 // the expression ++x is equivalent to x+=1
5903 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5904 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005905 }
5906
5907 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5908 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5909 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5910 Object O = getObject(UO->getSubExpr(), true);
5911 if (!O)
5912 return VisitExpr(UO);
5913
5914 notePreMod(O, UO);
5915 Visit(UO->getSubExpr());
5916 notePostMod(O, UO, UK_ModAsSideEffect);
5917 }
5918
5919 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5920 void VisitBinLOr(BinaryOperator *BO) {
5921 // The side-effects of the LHS of an '&&' are sequenced before the
5922 // value computation of the RHS, and hence before the value computation
5923 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5924 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005925 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005926 {
5927 SequencedSubexpression Sequenced(*this);
5928 Visit(BO->getLHS());
5929 }
5930
5931 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005932 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005933 if (!Result)
5934 Visit(BO->getRHS());
5935 } else {
5936 // Check for unsequenced operations in the RHS, treating it as an
5937 // entirely separate evaluation.
5938 //
5939 // FIXME: If there are operations in the RHS which are unsequenced
5940 // with respect to operations outside the RHS, and those operations
5941 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005942 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005943 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005944 }
5945 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005946 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005947 {
5948 SequencedSubexpression Sequenced(*this);
5949 Visit(BO->getLHS());
5950 }
5951
5952 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005953 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005954 if (Result)
5955 Visit(BO->getRHS());
5956 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005957 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005958 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005959 }
5960
5961 // Only visit the condition, unless we can be sure which subexpression will
5962 // be chosen.
5963 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005964 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005965 {
5966 SequencedSubexpression Sequenced(*this);
5967 Visit(CO->getCond());
5968 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005969
5970 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005971 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005972 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005973 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005974 WorkList.push_back(CO->getTrueExpr());
5975 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005976 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005977 }
5978
Richard Smith0c0b3902013-06-30 10:40:20 +00005979 void VisitCallExpr(CallExpr *CE) {
5980 // C++11 [intro.execution]p15:
5981 // When calling a function [...], every value computation and side effect
5982 // associated with any argument expression, or with the postfix expression
5983 // designating the called function, is sequenced before execution of every
5984 // expression or statement in the body of the function [and thus before
5985 // the value computation of its result].
5986 SequencedSubexpression Sequenced(*this);
5987 Base::VisitCallExpr(CE);
5988
5989 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5990 }
5991
Richard Smith6c3af3d2013-01-17 01:17:56 +00005992 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005993 // This is a call, so all subexpressions are sequenced before the result.
5994 SequencedSubexpression Sequenced(*this);
5995
Richard Smith6c3af3d2013-01-17 01:17:56 +00005996 if (!CCE->isListInitialization())
5997 return VisitExpr(CCE);
5998
5999 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006000 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006001 SequenceTree::Seq Parent = Region;
6002 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6003 E = CCE->arg_end();
6004 I != E; ++I) {
6005 Region = Tree.allocate(Parent);
6006 Elts.push_back(Region);
6007 Visit(*I);
6008 }
6009
6010 // Forget that the initializers are sequenced.
6011 Region = Parent;
6012 for (unsigned I = 0; I < Elts.size(); ++I)
6013 Tree.merge(Elts[I]);
6014 }
6015
6016 void VisitInitListExpr(InitListExpr *ILE) {
6017 if (!SemaRef.getLangOpts().CPlusPlus11)
6018 return VisitExpr(ILE);
6019
6020 // In C++11, list initializations are sequenced.
Robert Wilhelme7205c02013-08-10 12:33:24 +00006021 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smith6c3af3d2013-01-17 01:17:56 +00006022 SequenceTree::Seq Parent = Region;
6023 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6024 Expr *E = ILE->getInit(I);
6025 if (!E) continue;
6026 Region = Tree.allocate(Parent);
6027 Elts.push_back(Region);
6028 Visit(E);
6029 }
6030
6031 // Forget that the initializers are sequenced.
6032 Region = Parent;
6033 for (unsigned I = 0; I < Elts.size(); ++I)
6034 Tree.merge(Elts[I]);
6035 }
6036};
6037}
6038
6039void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelme7205c02013-08-10 12:33:24 +00006040 SmallVector<Expr *, 8> WorkList;
Richard Smith1a2dcd52013-01-17 23:18:09 +00006041 WorkList.push_back(E);
6042 while (!WorkList.empty()) {
Robert Wilhelm344472e2013-08-23 16:11:15 +00006043 Expr *Item = WorkList.pop_back_val();
Richard Smith1a2dcd52013-01-17 23:18:09 +00006044 SequenceChecker(*this, Item, WorkList);
6045 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006046}
6047
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006048void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6049 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006050 CheckImplicitConversions(E, CheckLoc);
6051 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006052 if (!IsConstexpr && !E->isValueDependent())
6053 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006054}
6055
John McCall15d7d122010-11-11 03:21:53 +00006056void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6057 FieldDecl *BitField,
6058 Expr *Init) {
6059 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6060}
6061
Mike Stumpf8c49212010-01-21 03:59:47 +00006062/// CheckParmsForFunctionDef - Check that the parameters of the given
6063/// function are appropriate for the definition of a function. This
6064/// takes care of any checks that cannot be performed on the
6065/// declaration itself, e.g., that the types of each of the function
6066/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006067bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6068 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006069 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006070 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006071 for (; P != PEnd; ++P) {
6072 ParmVarDecl *Param = *P;
6073
Mike Stumpf8c49212010-01-21 03:59:47 +00006074 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6075 // function declarator that is part of a function definition of
6076 // that function shall not have incomplete type.
6077 //
6078 // This is also C++ [dcl.fct]p6.
6079 if (!Param->isInvalidDecl() &&
6080 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006081 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006082 Param->setInvalidDecl();
6083 HasInvalidParm = true;
6084 }
6085
6086 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6087 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006088 if (CheckParameterNames &&
6089 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006090 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006091 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006092 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006093
6094 // C99 6.7.5.3p12:
6095 // If the function declarator is not part of a definition of that
6096 // function, parameters may have incomplete type and may use the [*]
6097 // notation in their sequences of declarator specifiers to specify
6098 // variable length array types.
6099 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006100 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006101 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006102 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006103 // information is added for it.
6104 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006105 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006106 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006107 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006108 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006109
6110 // MSVC destroys objects passed by value in the callee. Therefore a
6111 // function definition which takes such a parameter must be able to call the
6112 // object's destructor.
6113 if (getLangOpts().CPlusPlus &&
6114 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6115 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6116 FinalizeVarWithDestructor(Param, RT);
6117 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006118 }
6119
6120 return HasInvalidParm;
6121}
John McCallb7f4ffe2010-08-12 21:44:57 +00006122
6123/// CheckCastAlign - Implements -Wcast-align, which warns when a
6124/// pointer cast increases the alignment requirements.
6125void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6126 // This is actually a lot of work to potentially be doing on every
6127 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006128 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6129 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006130 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006131 return;
6132
6133 // Ignore dependent types.
6134 if (T->isDependentType() || Op->getType()->isDependentType())
6135 return;
6136
6137 // Require that the destination be a pointer type.
6138 const PointerType *DestPtr = T->getAs<PointerType>();
6139 if (!DestPtr) return;
6140
6141 // If the destination has alignment 1, we're done.
6142 QualType DestPointee = DestPtr->getPointeeType();
6143 if (DestPointee->isIncompleteType()) return;
6144 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6145 if (DestAlign.isOne()) return;
6146
6147 // Require that the source be a pointer type.
6148 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6149 if (!SrcPtr) return;
6150 QualType SrcPointee = SrcPtr->getPointeeType();
6151
6152 // Whitelist casts from cv void*. We already implicitly
6153 // whitelisted casts to cv void*, since they have alignment 1.
6154 // Also whitelist casts involving incomplete types, which implicitly
6155 // includes 'void'.
6156 if (SrcPointee->isIncompleteType()) return;
6157
6158 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6159 if (SrcAlign >= DestAlign) return;
6160
6161 Diag(TRange.getBegin(), diag::warn_cast_align)
6162 << Op->getType() << T
6163 << static_cast<unsigned>(SrcAlign.getQuantity())
6164 << static_cast<unsigned>(DestAlign.getQuantity())
6165 << TRange << Op->getSourceRange();
6166}
6167
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006168static const Type* getElementType(const Expr *BaseExpr) {
6169 const Type* EltType = BaseExpr->getType().getTypePtr();
6170 if (EltType->isAnyPointerType())
6171 return EltType->getPointeeType().getTypePtr();
6172 else if (EltType->isArrayType())
6173 return EltType->getBaseElementTypeUnsafe();
6174 return EltType;
6175}
6176
Chandler Carruthc2684342011-08-05 09:10:50 +00006177/// \brief Check whether this array fits the idiom of a size-one tail padded
6178/// array member of a struct.
6179///
6180/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6181/// commonly used to emulate flexible arrays in C89 code.
6182static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6183 const NamedDecl *ND) {
6184 if (Size != 1 || !ND) return false;
6185
6186 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6187 if (!FD) return false;
6188
6189 // Don't consider sizes resulting from macro expansions or template argument
6190 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006191
6192 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006193 while (TInfo) {
6194 TypeLoc TL = TInfo->getTypeLoc();
6195 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006196 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6197 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006198 TInfo = TDL->getTypeSourceInfo();
6199 continue;
6200 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006201 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6202 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006203 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6204 return false;
6205 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006206 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006207 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006208
6209 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006210 if (!RD) return false;
6211 if (RD->isUnion()) return false;
6212 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6213 if (!CRD->isStandardLayout()) return false;
6214 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006215
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006216 // See if this is the last field decl in the record.
6217 const Decl *D = FD;
6218 while ((D = D->getNextDeclInContext()))
6219 if (isa<FieldDecl>(D))
6220 return false;
6221 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006222}
6223
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006224void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006225 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006226 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006227 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006228 if (IndexExpr->isValueDependent())
6229 return;
6230
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006231 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006232 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006233 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006234 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006235 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006236 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006237
Chandler Carruth34064582011-02-17 20:55:08 +00006238 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006239 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006240 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006241 if (IndexNegated)
6242 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006243
Chandler Carruthba447122011-08-05 08:07:29 +00006244 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006245 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6246 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006247 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006248 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006249
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006250 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006251 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006252 if (!size.isStrictlyPositive())
6253 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006254
6255 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006256 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006257 // Make sure we're comparing apples to apples when comparing index to size
6258 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6259 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006260 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006261 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006262 if (ptrarith_typesize != array_typesize) {
6263 // There's a cast to a different size type involved
6264 uint64_t ratio = array_typesize / ptrarith_typesize;
6265 // TODO: Be smarter about handling cases where array_typesize is not a
6266 // multiple of ptrarith_typesize
6267 if (ptrarith_typesize * ratio == array_typesize)
6268 size *= llvm::APInt(size.getBitWidth(), ratio);
6269 }
6270 }
6271
Chandler Carruth34064582011-02-17 20:55:08 +00006272 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006273 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006274 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006275 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006276
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006277 // For array subscripting the index must be less than size, but for pointer
6278 // arithmetic also allow the index (offset) to be equal to size since
6279 // computing the next address after the end of the array is legal and
6280 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006281 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006282 return;
6283
6284 // Also don't warn for arrays of size 1 which are members of some
6285 // structure. These are often used to approximate flexible arrays in C89
6286 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006287 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006288 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006289
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006290 // Suppress the warning if the subscript expression (as identified by the
6291 // ']' location) and the index expression are both from macro expansions
6292 // within a system header.
6293 if (ASE) {
6294 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6295 ASE->getRBracketLoc());
6296 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6297 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6298 IndexExpr->getLocStart());
Eli Friedman24146972013-08-22 00:27:10 +00006299 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006300 return;
6301 }
6302 }
6303
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006304 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006305 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006306 DiagID = diag::warn_array_index_exceeds_bounds;
6307
6308 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6309 PDiag(DiagID) << index.toString(10, true)
6310 << size.toString(10, true)
6311 << (unsigned)size.getLimitedValue(~0U)
6312 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006313 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006314 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006315 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006316 DiagID = diag::warn_ptr_arith_precedes_bounds;
6317 if (index.isNegative()) index = -index;
6318 }
6319
6320 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6321 PDiag(DiagID) << index.toString(10, true)
6322 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006323 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006324
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006325 if (!ND) {
6326 // Try harder to find a NamedDecl to point at in the note.
6327 while (const ArraySubscriptExpr *ASE =
6328 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6329 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6330 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6331 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6332 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6333 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6334 }
6335
Chandler Carruth35001ca2011-02-17 21:10:52 +00006336 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006337 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6338 PDiag(diag::note_array_index_out_of_bounds)
6339 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006340}
6341
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006342void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006343 int AllowOnePastEnd = 0;
6344 while (expr) {
6345 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006346 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006347 case Stmt::ArraySubscriptExprClass: {
6348 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006349 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006350 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006351 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006352 }
6353 case Stmt::UnaryOperatorClass: {
6354 // Only unwrap the * and & unary operators
6355 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6356 expr = UO->getSubExpr();
6357 switch (UO->getOpcode()) {
6358 case UO_AddrOf:
6359 AllowOnePastEnd++;
6360 break;
6361 case UO_Deref:
6362 AllowOnePastEnd--;
6363 break;
6364 default:
6365 return;
6366 }
6367 break;
6368 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006369 case Stmt::ConditionalOperatorClass: {
6370 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6371 if (const Expr *lhs = cond->getLHS())
6372 CheckArrayAccess(lhs);
6373 if (const Expr *rhs = cond->getRHS())
6374 CheckArrayAccess(rhs);
6375 return;
6376 }
6377 default:
6378 return;
6379 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006380 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006381}
John McCallf85e1932011-06-15 23:02:42 +00006382
6383//===--- CHECK: Objective-C retain cycles ----------------------------------//
6384
6385namespace {
6386 struct RetainCycleOwner {
6387 RetainCycleOwner() : Variable(0), Indirect(false) {}
6388 VarDecl *Variable;
6389 SourceRange Range;
6390 SourceLocation Loc;
6391 bool Indirect;
6392
6393 void setLocsFrom(Expr *e) {
6394 Loc = e->getExprLoc();
6395 Range = e->getSourceRange();
6396 }
6397 };
6398}
6399
6400/// Consider whether capturing the given variable can possibly lead to
6401/// a retain cycle.
6402static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006403 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006404 // lifetime. In MRR, it's captured strongly if the variable is
6405 // __block and has an appropriate type.
6406 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6407 return false;
6408
6409 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006410 if (ref)
6411 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006412 return true;
6413}
6414
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006415static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006416 while (true) {
6417 e = e->IgnoreParens();
6418 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6419 switch (cast->getCastKind()) {
6420 case CK_BitCast:
6421 case CK_LValueBitCast:
6422 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006423 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006424 e = cast->getSubExpr();
6425 continue;
6426
John McCallf85e1932011-06-15 23:02:42 +00006427 default:
6428 return false;
6429 }
6430 }
6431
6432 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6433 ObjCIvarDecl *ivar = ref->getDecl();
6434 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6435 return false;
6436
6437 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006438 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006439 return false;
6440
6441 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6442 owner.Indirect = true;
6443 return true;
6444 }
6445
6446 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6447 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6448 if (!var) return false;
6449 return considerVariable(var, ref, owner);
6450 }
6451
John McCallf85e1932011-06-15 23:02:42 +00006452 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6453 if (member->isArrow()) return false;
6454
6455 // Don't count this as an indirect ownership.
6456 e = member->getBase();
6457 continue;
6458 }
6459
John McCall4b9c2d22011-11-06 09:01:30 +00006460 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6461 // Only pay attention to pseudo-objects on property references.
6462 ObjCPropertyRefExpr *pre
6463 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6464 ->IgnoreParens());
6465 if (!pre) return false;
6466 if (pre->isImplicitProperty()) return false;
6467 ObjCPropertyDecl *property = pre->getExplicitProperty();
6468 if (!property->isRetaining() &&
6469 !(property->getPropertyIvarDecl() &&
6470 property->getPropertyIvarDecl()->getType()
6471 .getObjCLifetime() == Qualifiers::OCL_Strong))
6472 return false;
6473
6474 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006475 if (pre->isSuperReceiver()) {
6476 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6477 if (!owner.Variable)
6478 return false;
6479 owner.Loc = pre->getLocation();
6480 owner.Range = pre->getSourceRange();
6481 return true;
6482 }
John McCall4b9c2d22011-11-06 09:01:30 +00006483 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6484 ->getSourceExpr());
6485 continue;
6486 }
6487
John McCallf85e1932011-06-15 23:02:42 +00006488 // Array ivars?
6489
6490 return false;
6491 }
6492}
6493
6494namespace {
6495 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6496 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6497 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6498 Variable(variable), Capturer(0) {}
6499
6500 VarDecl *Variable;
6501 Expr *Capturer;
6502
6503 void VisitDeclRefExpr(DeclRefExpr *ref) {
6504 if (ref->getDecl() == Variable && !Capturer)
6505 Capturer = ref;
6506 }
6507
John McCallf85e1932011-06-15 23:02:42 +00006508 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6509 if (Capturer) return;
6510 Visit(ref->getBase());
6511 if (Capturer && ref->isFreeIvar())
6512 Capturer = ref;
6513 }
6514
6515 void VisitBlockExpr(BlockExpr *block) {
6516 // Look inside nested blocks
6517 if (block->getBlockDecl()->capturesVariable(Variable))
6518 Visit(block->getBlockDecl()->getBody());
6519 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006520
6521 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6522 if (Capturer) return;
6523 if (OVE->getSourceExpr())
6524 Visit(OVE->getSourceExpr());
6525 }
John McCallf85e1932011-06-15 23:02:42 +00006526 };
6527}
6528
6529/// Check whether the given argument is a block which captures a
6530/// variable.
6531static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6532 assert(owner.Variable && owner.Loc.isValid());
6533
6534 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006535
6536 // Look through [^{...} copy] and Block_copy(^{...}).
6537 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6538 Selector Cmd = ME->getSelector();
6539 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6540 e = ME->getInstanceReceiver();
6541 if (!e)
6542 return 0;
6543 e = e->IgnoreParenCasts();
6544 }
6545 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6546 if (CE->getNumArgs() == 1) {
6547 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006548 if (Fn) {
6549 const IdentifierInfo *FnI = Fn->getIdentifier();
6550 if (FnI && FnI->isStr("_Block_copy")) {
6551 e = CE->getArg(0)->IgnoreParenCasts();
6552 }
6553 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006554 }
6555 }
6556
John McCallf85e1932011-06-15 23:02:42 +00006557 BlockExpr *block = dyn_cast<BlockExpr>(e);
6558 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6559 return 0;
6560
6561 FindCaptureVisitor visitor(S.Context, owner.Variable);
6562 visitor.Visit(block->getBlockDecl()->getBody());
6563 return visitor.Capturer;
6564}
6565
6566static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6567 RetainCycleOwner &owner) {
6568 assert(capturer);
6569 assert(owner.Variable && owner.Loc.isValid());
6570
6571 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6572 << owner.Variable << capturer->getSourceRange();
6573 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6574 << owner.Indirect << owner.Range;
6575}
6576
6577/// Check for a keyword selector that starts with the word 'add' or
6578/// 'set'.
6579static bool isSetterLikeSelector(Selector sel) {
6580 if (sel.isUnarySelector()) return false;
6581
Chris Lattner5f9e2722011-07-23 10:55:15 +00006582 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006583 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006584 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006585 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006586 else if (str.startswith("add")) {
6587 // Specially whitelist 'addOperationWithBlock:'.
6588 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6589 return false;
6590 str = str.substr(3);
6591 }
John McCallf85e1932011-06-15 23:02:42 +00006592 else
6593 return false;
6594
6595 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006596 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006597}
6598
6599/// Check a message send to see if it's likely to cause a retain cycle.
6600void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6601 // Only check instance methods whose selector looks like a setter.
6602 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6603 return;
6604
6605 // Try to find a variable that the receiver is strongly owned by.
6606 RetainCycleOwner owner;
6607 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006608 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006609 return;
6610 } else {
6611 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6612 owner.Variable = getCurMethodDecl()->getSelfDecl();
6613 owner.Loc = msg->getSuperLoc();
6614 owner.Range = msg->getSuperLoc();
6615 }
6616
6617 // Check whether the receiver is captured by any of the arguments.
6618 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6619 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6620 return diagnoseRetainCycle(*this, capturer, owner);
6621}
6622
6623/// Check a property assign to see if it's likely to cause a retain cycle.
6624void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6625 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006626 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006627 return;
6628
6629 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6630 diagnoseRetainCycle(*this, capturer, owner);
6631}
6632
Jordan Rosee10f4d32012-09-15 02:48:31 +00006633void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6634 RetainCycleOwner Owner;
6635 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6636 return;
6637
6638 // Because we don't have an expression for the variable, we have to set the
6639 // location explicitly here.
6640 Owner.Loc = Var->getLocation();
6641 Owner.Range = Var->getSourceRange();
6642
6643 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6644 diagnoseRetainCycle(*this, Capturer, Owner);
6645}
6646
Ted Kremenek9d084012012-12-21 08:04:28 +00006647static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6648 Expr *RHS, bool isProperty) {
6649 // Check if RHS is an Objective-C object literal, which also can get
6650 // immediately zapped in a weak reference. Note that we explicitly
6651 // allow ObjCStringLiterals, since those are designed to never really die.
6652 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006653
Ted Kremenekd3292c82012-12-21 22:46:35 +00006654 // This enum needs to match with the 'select' in
6655 // warn_objc_arc_literal_assign (off-by-1).
6656 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6657 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6658 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006659
6660 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006661 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006662 << (isProperty ? 0 : 1)
6663 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006664
6665 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006666}
6667
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006668static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6669 Qualifiers::ObjCLifetime LT,
6670 Expr *RHS, bool isProperty) {
6671 // Strip off any implicit cast added to get to the one ARC-specific.
6672 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6673 if (cast->getCastKind() == CK_ARCConsumeObject) {
6674 S.Diag(Loc, diag::warn_arc_retained_assign)
6675 << (LT == Qualifiers::OCL_ExplicitNone)
6676 << (isProperty ? 0 : 1)
6677 << RHS->getSourceRange();
6678 return true;
6679 }
6680 RHS = cast->getSubExpr();
6681 }
6682
6683 if (LT == Qualifiers::OCL_Weak &&
6684 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6685 return true;
6686
6687 return false;
6688}
6689
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006690bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6691 QualType LHS, Expr *RHS) {
6692 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6693
6694 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6695 return false;
6696
6697 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6698 return true;
6699
6700 return false;
6701}
6702
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006703void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6704 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006705 QualType LHSType;
6706 // PropertyRef on LHS type need be directly obtained from
6707 // its declaration as it has a PsuedoType.
6708 ObjCPropertyRefExpr *PRE
6709 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6710 if (PRE && !PRE->isImplicitProperty()) {
6711 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6712 if (PD)
6713 LHSType = PD->getType();
6714 }
6715
6716 if (LHSType.isNull())
6717 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006718
6719 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6720
6721 if (LT == Qualifiers::OCL_Weak) {
6722 DiagnosticsEngine::Level Level =
6723 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6724 if (Level != DiagnosticsEngine::Ignored)
6725 getCurFunction()->markSafeWeakUse(LHS);
6726 }
6727
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006728 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6729 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006730
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006731 // FIXME. Check for other life times.
6732 if (LT != Qualifiers::OCL_None)
6733 return;
6734
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006735 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006736 if (PRE->isImplicitProperty())
6737 return;
6738 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6739 if (!PD)
6740 return;
6741
Bill Wendlingad017fa2012-12-20 19:22:21 +00006742 unsigned Attributes = PD->getPropertyAttributes();
6743 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006744 // when 'assign' attribute was not explicitly specified
6745 // by user, ignore it and rely on property type itself
6746 // for lifetime info.
6747 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6748 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6749 LHSType->isObjCRetainableType())
6750 return;
6751
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006752 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006753 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006754 Diag(Loc, diag::warn_arc_retained_property_assign)
6755 << RHS->getSourceRange();
6756 return;
6757 }
6758 RHS = cast->getSubExpr();
6759 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006760 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006761 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006762 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6763 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006764 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006765 }
6766}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006767
6768//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6769
6770namespace {
6771bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6772 SourceLocation StmtLoc,
6773 const NullStmt *Body) {
6774 // Do not warn if the body is a macro that expands to nothing, e.g:
6775 //
6776 // #define CALL(x)
6777 // if (condition)
6778 // CALL(0);
6779 //
6780 if (Body->hasLeadingEmptyMacro())
6781 return false;
6782
6783 // Get line numbers of statement and body.
6784 bool StmtLineInvalid;
6785 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6786 &StmtLineInvalid);
6787 if (StmtLineInvalid)
6788 return false;
6789
6790 bool BodyLineInvalid;
6791 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6792 &BodyLineInvalid);
6793 if (BodyLineInvalid)
6794 return false;
6795
6796 // Warn if null statement and body are on the same line.
6797 if (StmtLine != BodyLine)
6798 return false;
6799
6800 return true;
6801}
6802} // Unnamed namespace
6803
6804void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6805 const Stmt *Body,
6806 unsigned DiagID) {
6807 // Since this is a syntactic check, don't emit diagnostic for template
6808 // instantiations, this just adds noise.
6809 if (CurrentInstantiationScope)
6810 return;
6811
6812 // The body should be a null statement.
6813 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6814 if (!NBody)
6815 return;
6816
6817 // Do the usual checks.
6818 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6819 return;
6820
6821 Diag(NBody->getSemiLoc(), DiagID);
6822 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6823}
6824
6825void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6826 const Stmt *PossibleBody) {
6827 assert(!CurrentInstantiationScope); // Ensured by caller
6828
6829 SourceLocation StmtLoc;
6830 const Stmt *Body;
6831 unsigned DiagID;
6832 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6833 StmtLoc = FS->getRParenLoc();
6834 Body = FS->getBody();
6835 DiagID = diag::warn_empty_for_body;
6836 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6837 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6838 Body = WS->getBody();
6839 DiagID = diag::warn_empty_while_body;
6840 } else
6841 return; // Neither `for' nor `while'.
6842
6843 // The body should be a null statement.
6844 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6845 if (!NBody)
6846 return;
6847
6848 // Skip expensive checks if diagnostic is disabled.
6849 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6850 DiagnosticsEngine::Ignored)
6851 return;
6852
6853 // Do the usual checks.
6854 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6855 return;
6856
6857 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6858 // noise level low, emit diagnostics only if for/while is followed by a
6859 // CompoundStmt, e.g.:
6860 // for (int i = 0; i < n; i++);
6861 // {
6862 // a(i);
6863 // }
6864 // or if for/while is followed by a statement with more indentation
6865 // than for/while itself:
6866 // for (int i = 0; i < n; i++);
6867 // a(i);
6868 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6869 if (!ProbableTypo) {
6870 bool BodyColInvalid;
6871 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6872 PossibleBody->getLocStart(),
6873 &BodyColInvalid);
6874 if (BodyColInvalid)
6875 return;
6876
6877 bool StmtColInvalid;
6878 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6879 S->getLocStart(),
6880 &StmtColInvalid);
6881 if (StmtColInvalid)
6882 return;
6883
6884 if (BodyCol > StmtCol)
6885 ProbableTypo = true;
6886 }
6887
6888 if (ProbableTypo) {
6889 Diag(NBody->getSemiLoc(), DiagID);
6890 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6891 }
6892}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006893
6894//===--- Layout compatibility ----------------------------------------------//
6895
6896namespace {
6897
6898bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6899
6900/// \brief Check if two enumeration types are layout-compatible.
6901bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6902 // C++11 [dcl.enum] p8:
6903 // Two enumeration types are layout-compatible if they have the same
6904 // underlying type.
6905 return ED1->isComplete() && ED2->isComplete() &&
6906 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6907}
6908
6909/// \brief Check if two fields are layout-compatible.
6910bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6911 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6912 return false;
6913
6914 if (Field1->isBitField() != Field2->isBitField())
6915 return false;
6916
6917 if (Field1->isBitField()) {
6918 // Make sure that the bit-fields are the same length.
6919 unsigned Bits1 = Field1->getBitWidthValue(C);
6920 unsigned Bits2 = Field2->getBitWidthValue(C);
6921
6922 if (Bits1 != Bits2)
6923 return false;
6924 }
6925
6926 return true;
6927}
6928
6929/// \brief Check if two standard-layout structs are layout-compatible.
6930/// (C++11 [class.mem] p17)
6931bool isLayoutCompatibleStruct(ASTContext &C,
6932 RecordDecl *RD1,
6933 RecordDecl *RD2) {
6934 // If both records are C++ classes, check that base classes match.
6935 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6936 // If one of records is a CXXRecordDecl we are in C++ mode,
6937 // thus the other one is a CXXRecordDecl, too.
6938 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6939 // Check number of base classes.
6940 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6941 return false;
6942
6943 // Check the base classes.
6944 for (CXXRecordDecl::base_class_const_iterator
6945 Base1 = D1CXX->bases_begin(),
6946 BaseEnd1 = D1CXX->bases_end(),
6947 Base2 = D2CXX->bases_begin();
6948 Base1 != BaseEnd1;
6949 ++Base1, ++Base2) {
6950 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6951 return false;
6952 }
6953 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6954 // If only RD2 is a C++ class, it should have zero base classes.
6955 if (D2CXX->getNumBases() > 0)
6956 return false;
6957 }
6958
6959 // Check the fields.
6960 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6961 Field2End = RD2->field_end(),
6962 Field1 = RD1->field_begin(),
6963 Field1End = RD1->field_end();
6964 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6965 if (!isLayoutCompatible(C, *Field1, *Field2))
6966 return false;
6967 }
6968 if (Field1 != Field1End || Field2 != Field2End)
6969 return false;
6970
6971 return true;
6972}
6973
6974/// \brief Check if two standard-layout unions are layout-compatible.
6975/// (C++11 [class.mem] p18)
6976bool isLayoutCompatibleUnion(ASTContext &C,
6977 RecordDecl *RD1,
6978 RecordDecl *RD2) {
6979 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6980 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6981 Field2End = RD2->field_end();
6982 Field2 != Field2End; ++Field2) {
6983 UnmatchedFields.insert(*Field2);
6984 }
6985
6986 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6987 Field1End = RD1->field_end();
6988 Field1 != Field1End; ++Field1) {
6989 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6990 I = UnmatchedFields.begin(),
6991 E = UnmatchedFields.end();
6992
6993 for ( ; I != E; ++I) {
6994 if (isLayoutCompatible(C, *Field1, *I)) {
6995 bool Result = UnmatchedFields.erase(*I);
6996 (void) Result;
6997 assert(Result);
6998 break;
6999 }
7000 }
7001 if (I == E)
7002 return false;
7003 }
7004
7005 return UnmatchedFields.empty();
7006}
7007
7008bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7009 if (RD1->isUnion() != RD2->isUnion())
7010 return false;
7011
7012 if (RD1->isUnion())
7013 return isLayoutCompatibleUnion(C, RD1, RD2);
7014 else
7015 return isLayoutCompatibleStruct(C, RD1, RD2);
7016}
7017
7018/// \brief Check if two types are layout-compatible in C++11 sense.
7019bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7020 if (T1.isNull() || T2.isNull())
7021 return false;
7022
7023 // C++11 [basic.types] p11:
7024 // If two types T1 and T2 are the same type, then T1 and T2 are
7025 // layout-compatible types.
7026 if (C.hasSameType(T1, T2))
7027 return true;
7028
7029 T1 = T1.getCanonicalType().getUnqualifiedType();
7030 T2 = T2.getCanonicalType().getUnqualifiedType();
7031
7032 const Type::TypeClass TC1 = T1->getTypeClass();
7033 const Type::TypeClass TC2 = T2->getTypeClass();
7034
7035 if (TC1 != TC2)
7036 return false;
7037
7038 if (TC1 == Type::Enum) {
7039 return isLayoutCompatible(C,
7040 cast<EnumType>(T1)->getDecl(),
7041 cast<EnumType>(T2)->getDecl());
7042 } else if (TC1 == Type::Record) {
7043 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7044 return false;
7045
7046 return isLayoutCompatible(C,
7047 cast<RecordType>(T1)->getDecl(),
7048 cast<RecordType>(T2)->getDecl());
7049 }
7050
7051 return false;
7052}
7053}
7054
7055//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7056
7057namespace {
7058/// \brief Given a type tag expression find the type tag itself.
7059///
7060/// \param TypeExpr Type tag expression, as it appears in user's code.
7061///
7062/// \param VD Declaration of an identifier that appears in a type tag.
7063///
7064/// \param MagicValue Type tag magic value.
7065bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7066 const ValueDecl **VD, uint64_t *MagicValue) {
7067 while(true) {
7068 if (!TypeExpr)
7069 return false;
7070
7071 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7072
7073 switch (TypeExpr->getStmtClass()) {
7074 case Stmt::UnaryOperatorClass: {
7075 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7076 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7077 TypeExpr = UO->getSubExpr();
7078 continue;
7079 }
7080 return false;
7081 }
7082
7083 case Stmt::DeclRefExprClass: {
7084 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7085 *VD = DRE->getDecl();
7086 return true;
7087 }
7088
7089 case Stmt::IntegerLiteralClass: {
7090 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7091 llvm::APInt MagicValueAPInt = IL->getValue();
7092 if (MagicValueAPInt.getActiveBits() <= 64) {
7093 *MagicValue = MagicValueAPInt.getZExtValue();
7094 return true;
7095 } else
7096 return false;
7097 }
7098
7099 case Stmt::BinaryConditionalOperatorClass:
7100 case Stmt::ConditionalOperatorClass: {
7101 const AbstractConditionalOperator *ACO =
7102 cast<AbstractConditionalOperator>(TypeExpr);
7103 bool Result;
7104 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7105 if (Result)
7106 TypeExpr = ACO->getTrueExpr();
7107 else
7108 TypeExpr = ACO->getFalseExpr();
7109 continue;
7110 }
7111 return false;
7112 }
7113
7114 case Stmt::BinaryOperatorClass: {
7115 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7116 if (BO->getOpcode() == BO_Comma) {
7117 TypeExpr = BO->getRHS();
7118 continue;
7119 }
7120 return false;
7121 }
7122
7123 default:
7124 return false;
7125 }
7126 }
7127}
7128
7129/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7130///
7131/// \param TypeExpr Expression that specifies a type tag.
7132///
7133/// \param MagicValues Registered magic values.
7134///
7135/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7136/// kind.
7137///
7138/// \param TypeInfo Information about the corresponding C type.
7139///
7140/// \returns true if the corresponding C type was found.
7141bool GetMatchingCType(
7142 const IdentifierInfo *ArgumentKind,
7143 const Expr *TypeExpr, const ASTContext &Ctx,
7144 const llvm::DenseMap<Sema::TypeTagMagicValue,
7145 Sema::TypeTagData> *MagicValues,
7146 bool &FoundWrongKind,
7147 Sema::TypeTagData &TypeInfo) {
7148 FoundWrongKind = false;
7149
7150 // Variable declaration that has type_tag_for_datatype attribute.
7151 const ValueDecl *VD = NULL;
7152
7153 uint64_t MagicValue;
7154
7155 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7156 return false;
7157
7158 if (VD) {
7159 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7160 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7161 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7162 I != E; ++I) {
7163 if (I->getArgumentKind() != ArgumentKind) {
7164 FoundWrongKind = true;
7165 return false;
7166 }
7167 TypeInfo.Type = I->getMatchingCType();
7168 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7169 TypeInfo.MustBeNull = I->getMustBeNull();
7170 return true;
7171 }
7172 return false;
7173 }
7174
7175 if (!MagicValues)
7176 return false;
7177
7178 llvm::DenseMap<Sema::TypeTagMagicValue,
7179 Sema::TypeTagData>::const_iterator I =
7180 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7181 if (I == MagicValues->end())
7182 return false;
7183
7184 TypeInfo = I->second;
7185 return true;
7186}
7187} // unnamed namespace
7188
7189void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7190 uint64_t MagicValue, QualType Type,
7191 bool LayoutCompatible,
7192 bool MustBeNull) {
7193 if (!TypeTagForDatatypeMagicValues)
7194 TypeTagForDatatypeMagicValues.reset(
7195 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7196
7197 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7198 (*TypeTagForDatatypeMagicValues)[Magic] =
7199 TypeTagData(Type, LayoutCompatible, MustBeNull);
7200}
7201
7202namespace {
7203bool IsSameCharType(QualType T1, QualType T2) {
7204 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7205 if (!BT1)
7206 return false;
7207
7208 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7209 if (!BT2)
7210 return false;
7211
7212 BuiltinType::Kind T1Kind = BT1->getKind();
7213 BuiltinType::Kind T2Kind = BT2->getKind();
7214
7215 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7216 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7217 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7218 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7219}
7220} // unnamed namespace
7221
7222void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7223 const Expr * const *ExprArgs) {
7224 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7225 bool IsPointerAttr = Attr->getIsPointer();
7226
7227 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7228 bool FoundWrongKind;
7229 TypeTagData TypeInfo;
7230 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7231 TypeTagForDatatypeMagicValues.get(),
7232 FoundWrongKind, TypeInfo)) {
7233 if (FoundWrongKind)
7234 Diag(TypeTagExpr->getExprLoc(),
7235 diag::warn_type_tag_for_datatype_wrong_kind)
7236 << TypeTagExpr->getSourceRange();
7237 return;
7238 }
7239
7240 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7241 if (IsPointerAttr) {
7242 // Skip implicit cast of pointer to `void *' (as a function argument).
7243 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007244 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007245 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007246 ArgumentExpr = ICE->getSubExpr();
7247 }
7248 QualType ArgumentType = ArgumentExpr->getType();
7249
7250 // Passing a `void*' pointer shouldn't trigger a warning.
7251 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7252 return;
7253
7254 if (TypeInfo.MustBeNull) {
7255 // Type tag with matching void type requires a null pointer.
7256 if (!ArgumentExpr->isNullPointerConstant(Context,
7257 Expr::NPC_ValueDependentIsNotNull)) {
7258 Diag(ArgumentExpr->getExprLoc(),
7259 diag::warn_type_safety_null_pointer_required)
7260 << ArgumentKind->getName()
7261 << ArgumentExpr->getSourceRange()
7262 << TypeTagExpr->getSourceRange();
7263 }
7264 return;
7265 }
7266
7267 QualType RequiredType = TypeInfo.Type;
7268 if (IsPointerAttr)
7269 RequiredType = Context.getPointerType(RequiredType);
7270
7271 bool mismatch = false;
7272 if (!TypeInfo.LayoutCompatible) {
7273 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7274
7275 // C++11 [basic.fundamental] p1:
7276 // Plain char, signed char, and unsigned char are three distinct types.
7277 //
7278 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7279 // char' depending on the current char signedness mode.
7280 if (mismatch)
7281 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7282 RequiredType->getPointeeType())) ||
7283 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7284 mismatch = false;
7285 } else
7286 if (IsPointerAttr)
7287 mismatch = !isLayoutCompatible(Context,
7288 ArgumentType->getPointeeType(),
7289 RequiredType->getPointeeType());
7290 else
7291 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7292
7293 if (mismatch)
7294 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7295 << ArgumentType << ArgumentKind->getName()
7296 << TypeInfo.LayoutCompatible << RequiredType
7297 << ArgumentExpr->getSourceRange()
7298 << TypeTagExpr->getSourceRange();
7299}