blob: ed4a034675234e97cb5c6abacffff5f4ad757693 [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) {
Benjamin Kramer47abb252013-08-08 11:08:26 +0000719 CheckedVarArgs.resize(Args.size());
Richard Trieu0538f0e2013-06-22 00:20:41 +0000720 for (specific_attr_iterator<FormatAttr>
Benjamin Kramer47abb252013-08-08 11:08:26 +0000721 I = FDecl->specific_attr_begin<FormatAttr>(),
722 E = FDecl->specific_attr_end<FormatAttr>();
723 I != E; ++I)
724 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
725 CheckedVarArgs);
Richard Smith0e218972013-08-05 18:49:43 +0000726 }
Richard Smith831421f2012-06-25 20:30:08 +0000727
728 // Refuse POD arguments that weren't caught by the format string
729 // checks above.
Richard Smith0e218972013-08-05 18:49:43 +0000730 if (CallType != VariadicDoesNotApply) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000731 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000732 // Args[ArgIdx] can be null in malformed code.
Richard Smith0e218972013-08-05 18:49:43 +0000733 if (const Expr *Arg = Args[ArgIdx]) {
734 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
735 checkVariadicArgument(Arg, CallType);
736 }
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000737 }
Richard Smith0e218972013-08-05 18:49:43 +0000738 }
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Richard Trieu0538f0e2013-06-22 00:20:41 +0000740 if (FDecl) {
741 for (specific_attr_iterator<NonNullAttr>
742 I = FDecl->specific_attr_begin<NonNullAttr>(),
743 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
744 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000745
Richard Trieu0538f0e2013-06-22 00:20:41 +0000746 // Type safety checking.
747 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
748 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
749 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
750 i != e; ++i) {
751 CheckArgumentWithTypeTag(*i, Args.data());
752 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000753 }
Richard Smith831421f2012-06-25 20:30:08 +0000754}
755
756/// CheckConstructorCall - Check a constructor call for correctness and safety
757/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000758void Sema::CheckConstructorCall(FunctionDecl *FDecl,
759 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000760 const FunctionProtoType *Proto,
761 SourceLocation Loc) {
762 VariadicCallType CallType =
763 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000764 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000765 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
766}
767
768/// CheckFunctionCall - Check a direct function call for various correctness
769/// and safety properties not strictly enforced by the C type system.
770bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
771 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000772 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
773 isa<CXXMethodDecl>(FDecl);
774 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
775 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000776 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
777 TheCall->getCallee());
778 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000779 Expr** Args = TheCall->getArgs();
780 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000781 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000782 // If this is a call to a member operator, hide the first argument
783 // from checkCall.
784 // FIXME: Our choice of AST representation here is less than ideal.
785 ++Args;
786 --NumArgs;
787 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000788 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
789 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000790 IsMemberFunction, TheCall->getRParenLoc(),
791 TheCall->getCallee()->getSourceRange(), CallType);
792
793 IdentifierInfo *FnInfo = FDecl->getIdentifier();
794 // None of the checks below are needed for functions that don't have
795 // simple names (e.g., C++ conversion functions).
796 if (!FnInfo)
797 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000798
Anna Zaks0a151a12012-01-17 00:37:07 +0000799 unsigned CMId = FDecl->getMemoryFunctionKind();
800 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000801 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000802
Anna Zaksd9b859a2012-01-13 21:52:01 +0000803 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000804 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000805 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000806 else if (CMId == Builtin::BIstrncat)
807 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000808 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000809 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000810
Anders Carlssond406bf02009-08-16 01:56:34 +0000811 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000812}
813
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000814bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000815 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000816 VariadicCallType CallType =
817 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000818
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000819 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000820 /*IsMemberFunction=*/false,
821 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000822
823 return false;
824}
825
Richard Trieuf462b012013-06-20 21:03:13 +0000826bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
827 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000828 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
829 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000830 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000832 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000833 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000834 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Richard Trieuf462b012013-06-20 21:03:13 +0000836 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000837 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000838 CallType = VariadicDoesNotApply;
839 } else if (Ty->isBlockPointerType()) {
840 CallType = VariadicBlock;
841 } else { // Ty->isFunctionPointerType()
842 CallType = VariadicFunction;
843 }
Richard Smith831421f2012-06-25 20:30:08 +0000844 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000845
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000846 checkCall(NDecl,
847 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
848 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000849 NumProtoArgs, /*IsMemberFunction=*/false,
850 TheCall->getRParenLoc(),
851 TheCall->getCallee()->getSourceRange(), CallType);
852
Anders Carlssond406bf02009-08-16 01:56:34 +0000853 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000854}
855
Richard Trieu0538f0e2013-06-22 00:20:41 +0000856/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
857/// such as function pointers returned from functions.
858bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
859 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
860 TheCall->getCallee());
861 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
862
863 checkCall(/*FDecl=*/0,
864 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
865 TheCall->getNumArgs()),
866 NumProtoArgs, /*IsMemberFunction=*/false,
867 TheCall->getRParenLoc(),
868 TheCall->getCallee()->getSourceRange(), CallType);
869
870 return false;
871}
872
Richard Smithff34d402012-04-12 05:08:17 +0000873ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
874 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000875 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
876 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000877
Richard Smithff34d402012-04-12 05:08:17 +0000878 // All these operations take one of the following forms:
879 enum {
880 // C __c11_atomic_init(A *, C)
881 Init,
882 // C __c11_atomic_load(A *, int)
883 Load,
884 // void __atomic_load(A *, CP, int)
885 Copy,
886 // C __c11_atomic_add(A *, M, int)
887 Arithmetic,
888 // C __atomic_exchange_n(A *, CP, int)
889 Xchg,
890 // void __atomic_exchange(A *, C *, CP, int)
891 GNUXchg,
892 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
893 C11CmpXchg,
894 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
895 GNUCmpXchg
896 } Form = Init;
897 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
898 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
899 // where:
900 // C is an appropriate type,
901 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
902 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
903 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
904 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000905
Richard Smithff34d402012-04-12 05:08:17 +0000906 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
907 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
908 && "need to update code for modified C11 atomics");
909 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
910 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
911 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
912 Op == AtomicExpr::AO__atomic_store_n ||
913 Op == AtomicExpr::AO__atomic_exchange_n ||
914 Op == AtomicExpr::AO__atomic_compare_exchange_n;
915 bool IsAddSub = false;
916
917 switch (Op) {
918 case AtomicExpr::AO__c11_atomic_init:
919 Form = Init;
920 break;
921
922 case AtomicExpr::AO__c11_atomic_load:
923 case AtomicExpr::AO__atomic_load_n:
924 Form = Load;
925 break;
926
927 case AtomicExpr::AO__c11_atomic_store:
928 case AtomicExpr::AO__atomic_load:
929 case AtomicExpr::AO__atomic_store:
930 case AtomicExpr::AO__atomic_store_n:
931 Form = Copy;
932 break;
933
934 case AtomicExpr::AO__c11_atomic_fetch_add:
935 case AtomicExpr::AO__c11_atomic_fetch_sub:
936 case AtomicExpr::AO__atomic_fetch_add:
937 case AtomicExpr::AO__atomic_fetch_sub:
938 case AtomicExpr::AO__atomic_add_fetch:
939 case AtomicExpr::AO__atomic_sub_fetch:
940 IsAddSub = true;
941 // Fall through.
942 case AtomicExpr::AO__c11_atomic_fetch_and:
943 case AtomicExpr::AO__c11_atomic_fetch_or:
944 case AtomicExpr::AO__c11_atomic_fetch_xor:
945 case AtomicExpr::AO__atomic_fetch_and:
946 case AtomicExpr::AO__atomic_fetch_or:
947 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000948 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000949 case AtomicExpr::AO__atomic_and_fetch:
950 case AtomicExpr::AO__atomic_or_fetch:
951 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000952 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000953 Form = Arithmetic;
954 break;
955
956 case AtomicExpr::AO__c11_atomic_exchange:
957 case AtomicExpr::AO__atomic_exchange_n:
958 Form = Xchg;
959 break;
960
961 case AtomicExpr::AO__atomic_exchange:
962 Form = GNUXchg;
963 break;
964
965 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
966 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
967 Form = C11CmpXchg;
968 break;
969
970 case AtomicExpr::AO__atomic_compare_exchange:
971 case AtomicExpr::AO__atomic_compare_exchange_n:
972 Form = GNUCmpXchg;
973 break;
974 }
975
976 // Check we have the right number of arguments.
977 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000978 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000979 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000980 << TheCall->getCallee()->getSourceRange();
981 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000982 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
983 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000984 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000985 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000986 << TheCall->getCallee()->getSourceRange();
987 return ExprError();
988 }
989
Richard Smithff34d402012-04-12 05:08:17 +0000990 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000991 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000992 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
993 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
994 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000995 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000996 << Ptr->getType() << Ptr->getSourceRange();
997 return ExprError();
998 }
999
Richard Smithff34d402012-04-12 05:08:17 +00001000 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1001 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1002 QualType ValType = AtomTy; // 'C'
1003 if (IsC11) {
1004 if (!AtomTy->isAtomicType()) {
1005 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1006 << Ptr->getType() << Ptr->getSourceRange();
1007 return ExprError();
1008 }
Richard Smithbc57b102012-09-15 06:09:58 +00001009 if (AtomTy.isConstQualified()) {
1010 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1011 << Ptr->getType() << Ptr->getSourceRange();
1012 return ExprError();
1013 }
Richard Smithff34d402012-04-12 05:08:17 +00001014 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +00001015 }
Eli Friedman276b0612011-10-11 02:20:01 +00001016
Richard Smithff34d402012-04-12 05:08:17 +00001017 // For an arithmetic operation, the implied arithmetic must be well-formed.
1018 if (Form == Arithmetic) {
1019 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1020 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1021 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1022 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1023 return ExprError();
1024 }
1025 if (!IsAddSub && !ValType->isIntegerType()) {
1026 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1027 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1028 return ExprError();
1029 }
1030 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1031 // For __atomic_*_n operations, the value type must be a scalar integral or
1032 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +00001033 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +00001034 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1035 return ExprError();
1036 }
1037
1038 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
1039 // For GNU atomics, require a trivially-copyable type. This is not part of
1040 // the GNU atomics specification, but we enforce it for sanity.
1041 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +00001042 << Ptr->getType() << Ptr->getSourceRange();
1043 return ExprError();
1044 }
1045
Richard Smithff34d402012-04-12 05:08:17 +00001046 // FIXME: For any builtin other than a load, the ValType must not be
1047 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +00001048
1049 switch (ValType.getObjCLifetime()) {
1050 case Qualifiers::OCL_None:
1051 case Qualifiers::OCL_ExplicitNone:
1052 // okay
1053 break;
1054
1055 case Qualifiers::OCL_Weak:
1056 case Qualifiers::OCL_Strong:
1057 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +00001058 // FIXME: Can this happen? By this point, ValType should be known
1059 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +00001060 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1061 << ValType << Ptr->getSourceRange();
1062 return ExprError();
1063 }
1064
1065 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +00001066 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +00001067 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +00001068 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +00001069 ResultType = Context.BoolTy;
1070
Richard Smithff34d402012-04-12 05:08:17 +00001071 // The type of a parameter passed 'by value'. In the GNU atomics, such
1072 // arguments are actually passed as pointers.
1073 QualType ByValType = ValType; // 'CP'
1074 if (!IsC11 && !IsN)
1075 ByValType = Ptr->getType();
1076
Eli Friedman276b0612011-10-11 02:20:01 +00001077 // The first argument --- the pointer --- has a fixed type; we
1078 // deduce the types of the rest of the arguments accordingly. Walk
1079 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +00001080 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +00001081 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +00001082 if (i < NumVals[Form] + 1) {
1083 switch (i) {
1084 case 1:
1085 // The second argument is the non-atomic operand. For arithmetic, this
1086 // is always passed by value, and for a compare_exchange it is always
1087 // passed by address. For the rest, GNU uses by-address and C11 uses
1088 // by-value.
1089 assert(Form != Load);
1090 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1091 Ty = ValType;
1092 else if (Form == Copy || Form == Xchg)
1093 Ty = ByValType;
1094 else if (Form == Arithmetic)
1095 Ty = Context.getPointerDiffType();
1096 else
1097 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1098 break;
1099 case 2:
1100 // The third argument to compare_exchange / GNU exchange is a
1101 // (pointer to a) desired value.
1102 Ty = ByValType;
1103 break;
1104 case 3:
1105 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1106 Ty = Context.BoolTy;
1107 break;
1108 }
Eli Friedman276b0612011-10-11 02:20:01 +00001109 } else {
1110 // The order(s) are always converted to int.
1111 Ty = Context.IntTy;
1112 }
Richard Smithff34d402012-04-12 05:08:17 +00001113
Eli Friedman276b0612011-10-11 02:20:01 +00001114 InitializedEntity Entity =
1115 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +00001116 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +00001117 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1118 if (Arg.isInvalid())
1119 return true;
1120 TheCall->setArg(i, Arg.get());
1121 }
1122
Richard Smithff34d402012-04-12 05:08:17 +00001123 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001124 SmallVector<Expr*, 5> SubExprs;
1125 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +00001126 switch (Form) {
1127 case Init:
1128 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +00001129 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001130 break;
1131 case Load:
1132 SubExprs.push_back(TheCall->getArg(1)); // Order
1133 break;
1134 case Copy:
1135 case Arithmetic:
1136 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001137 SubExprs.push_back(TheCall->getArg(2)); // Order
1138 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +00001139 break;
1140 case GNUXchg:
1141 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1142 SubExprs.push_back(TheCall->getArg(3)); // Order
1143 SubExprs.push_back(TheCall->getArg(1)); // Val1
1144 SubExprs.push_back(TheCall->getArg(2)); // Val2
1145 break;
1146 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001147 SubExprs.push_back(TheCall->getArg(3)); // Order
1148 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001149 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +00001150 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +00001151 break;
1152 case GNUCmpXchg:
1153 SubExprs.push_back(TheCall->getArg(4)); // Order
1154 SubExprs.push_back(TheCall->getArg(1)); // Val1
1155 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1156 SubExprs.push_back(TheCall->getArg(2)); // Val2
1157 SubExprs.push_back(TheCall->getArg(3)); // Weak
1158 break;
Eli Friedman276b0612011-10-11 02:20:01 +00001159 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001160
1161 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1162 SubExprs, ResultType, Op,
1163 TheCall->getRParenLoc());
1164
1165 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1166 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1167 Context.AtomicUsesUnsupportedLibcall(AE))
1168 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1169 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +00001170
Fariborz Jahanian538bbe52013-05-28 17:37:39 +00001171 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +00001172}
1173
1174
John McCall5f8d6042011-08-27 01:09:30 +00001175/// checkBuiltinArgument - Given a call to a builtin function, perform
1176/// normal type-checking on the given argument, updating the call in
1177/// place. This is useful when a builtin function requires custom
1178/// type-checking for some of its arguments but not necessarily all of
1179/// them.
1180///
1181/// Returns true on error.
1182static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1183 FunctionDecl *Fn = E->getDirectCallee();
1184 assert(Fn && "builtin call without direct callee!");
1185
1186 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1187 InitializedEntity Entity =
1188 InitializedEntity::InitializeParameter(S.Context, Param);
1189
1190 ExprResult Arg = E->getArg(0);
1191 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1192 if (Arg.isInvalid())
1193 return true;
1194
1195 E->setArg(ArgIndex, Arg.take());
1196 return false;
1197}
1198
Chris Lattner5caa3702009-05-08 06:58:22 +00001199/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1200/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1201/// type of its first argument. The main ActOnCallExpr routines have already
1202/// promoted the types of arguments because all of these calls are prototyped as
1203/// void(...).
1204///
1205/// This function goes through and does final semantic checking for these
1206/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001207ExprResult
1208Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001209 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001210 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1211 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1212
1213 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001214 if (TheCall->getNumArgs() < 1) {
1215 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1216 << 0 << 1 << TheCall->getNumArgs()
1217 << TheCall->getCallee()->getSourceRange();
1218 return ExprError();
1219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
Chris Lattner5caa3702009-05-08 06:58:22 +00001221 // Inspect the first argument of the atomic builtin. This should always be
1222 // a pointer type, whose element is an integral scalar or pointer type.
1223 // Because it is a pointer type, we don't have to worry about any implicit
1224 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001225 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001226 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001227 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1228 if (FirstArgResult.isInvalid())
1229 return ExprError();
1230 FirstArg = FirstArgResult.take();
1231 TheCall->setArg(0, FirstArg);
1232
John McCallf85e1932011-06-15 23:02:42 +00001233 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1234 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001235 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1236 << FirstArg->getType() << FirstArg->getSourceRange();
1237 return ExprError();
1238 }
Mike Stump1eb44332009-09-09 15:08:12 +00001239
John McCallf85e1932011-06-15 23:02:42 +00001240 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001241 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001242 !ValType->isBlockPointerType()) {
1243 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1244 << FirstArg->getType() << FirstArg->getSourceRange();
1245 return ExprError();
1246 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001247
John McCallf85e1932011-06-15 23:02:42 +00001248 switch (ValType.getObjCLifetime()) {
1249 case Qualifiers::OCL_None:
1250 case Qualifiers::OCL_ExplicitNone:
1251 // okay
1252 break;
1253
1254 case Qualifiers::OCL_Weak:
1255 case Qualifiers::OCL_Strong:
1256 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001257 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001258 << ValType << FirstArg->getSourceRange();
1259 return ExprError();
1260 }
1261
John McCallb45ae252011-10-05 07:41:44 +00001262 // Strip any qualifiers off ValType.
1263 ValType = ValType.getUnqualifiedType();
1264
Chandler Carruth8d13d222010-07-18 20:54:12 +00001265 // The majority of builtins return a value, but a few have special return
1266 // types, so allow them to override appropriately below.
1267 QualType ResultType = ValType;
1268
Chris Lattner5caa3702009-05-08 06:58:22 +00001269 // We need to figure out which concrete builtin this maps onto. For example,
1270 // __sync_fetch_and_add with a 2 byte object turns into
1271 // __sync_fetch_and_add_2.
1272#define BUILTIN_ROW(x) \
1273 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1274 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001275
Chris Lattner5caa3702009-05-08 06:58:22 +00001276 static const unsigned BuiltinIndices[][5] = {
1277 BUILTIN_ROW(__sync_fetch_and_add),
1278 BUILTIN_ROW(__sync_fetch_and_sub),
1279 BUILTIN_ROW(__sync_fetch_and_or),
1280 BUILTIN_ROW(__sync_fetch_and_and),
1281 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001282
Chris Lattner5caa3702009-05-08 06:58:22 +00001283 BUILTIN_ROW(__sync_add_and_fetch),
1284 BUILTIN_ROW(__sync_sub_and_fetch),
1285 BUILTIN_ROW(__sync_and_and_fetch),
1286 BUILTIN_ROW(__sync_or_and_fetch),
1287 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Chris Lattner5caa3702009-05-08 06:58:22 +00001289 BUILTIN_ROW(__sync_val_compare_and_swap),
1290 BUILTIN_ROW(__sync_bool_compare_and_swap),
1291 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001292 BUILTIN_ROW(__sync_lock_release),
1293 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001294 };
Mike Stump1eb44332009-09-09 15:08:12 +00001295#undef BUILTIN_ROW
1296
Chris Lattner5caa3702009-05-08 06:58:22 +00001297 // Determine the index of the size.
1298 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001299 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001300 case 1: SizeIndex = 0; break;
1301 case 2: SizeIndex = 1; break;
1302 case 4: SizeIndex = 2; break;
1303 case 8: SizeIndex = 3; break;
1304 case 16: SizeIndex = 4; break;
1305 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001306 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1307 << FirstArg->getType() << FirstArg->getSourceRange();
1308 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001309 }
Mike Stump1eb44332009-09-09 15:08:12 +00001310
Chris Lattner5caa3702009-05-08 06:58:22 +00001311 // Each of these builtins has one pointer argument, followed by some number of
1312 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1313 // that we ignore. Find out which row of BuiltinIndices to read from as well
1314 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001315 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001316 unsigned BuiltinIndex, NumFixed = 1;
1317 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001318 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001319 case Builtin::BI__sync_fetch_and_add:
1320 case Builtin::BI__sync_fetch_and_add_1:
1321 case Builtin::BI__sync_fetch_and_add_2:
1322 case Builtin::BI__sync_fetch_and_add_4:
1323 case Builtin::BI__sync_fetch_and_add_8:
1324 case Builtin::BI__sync_fetch_and_add_16:
1325 BuiltinIndex = 0;
1326 break;
1327
1328 case Builtin::BI__sync_fetch_and_sub:
1329 case Builtin::BI__sync_fetch_and_sub_1:
1330 case Builtin::BI__sync_fetch_and_sub_2:
1331 case Builtin::BI__sync_fetch_and_sub_4:
1332 case Builtin::BI__sync_fetch_and_sub_8:
1333 case Builtin::BI__sync_fetch_and_sub_16:
1334 BuiltinIndex = 1;
1335 break;
1336
1337 case Builtin::BI__sync_fetch_and_or:
1338 case Builtin::BI__sync_fetch_and_or_1:
1339 case Builtin::BI__sync_fetch_and_or_2:
1340 case Builtin::BI__sync_fetch_and_or_4:
1341 case Builtin::BI__sync_fetch_and_or_8:
1342 case Builtin::BI__sync_fetch_and_or_16:
1343 BuiltinIndex = 2;
1344 break;
1345
1346 case Builtin::BI__sync_fetch_and_and:
1347 case Builtin::BI__sync_fetch_and_and_1:
1348 case Builtin::BI__sync_fetch_and_and_2:
1349 case Builtin::BI__sync_fetch_and_and_4:
1350 case Builtin::BI__sync_fetch_and_and_8:
1351 case Builtin::BI__sync_fetch_and_and_16:
1352 BuiltinIndex = 3;
1353 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Douglas Gregora9766412011-11-28 16:30:08 +00001355 case Builtin::BI__sync_fetch_and_xor:
1356 case Builtin::BI__sync_fetch_and_xor_1:
1357 case Builtin::BI__sync_fetch_and_xor_2:
1358 case Builtin::BI__sync_fetch_and_xor_4:
1359 case Builtin::BI__sync_fetch_and_xor_8:
1360 case Builtin::BI__sync_fetch_and_xor_16:
1361 BuiltinIndex = 4;
1362 break;
1363
1364 case Builtin::BI__sync_add_and_fetch:
1365 case Builtin::BI__sync_add_and_fetch_1:
1366 case Builtin::BI__sync_add_and_fetch_2:
1367 case Builtin::BI__sync_add_and_fetch_4:
1368 case Builtin::BI__sync_add_and_fetch_8:
1369 case Builtin::BI__sync_add_and_fetch_16:
1370 BuiltinIndex = 5;
1371 break;
1372
1373 case Builtin::BI__sync_sub_and_fetch:
1374 case Builtin::BI__sync_sub_and_fetch_1:
1375 case Builtin::BI__sync_sub_and_fetch_2:
1376 case Builtin::BI__sync_sub_and_fetch_4:
1377 case Builtin::BI__sync_sub_and_fetch_8:
1378 case Builtin::BI__sync_sub_and_fetch_16:
1379 BuiltinIndex = 6;
1380 break;
1381
1382 case Builtin::BI__sync_and_and_fetch:
1383 case Builtin::BI__sync_and_and_fetch_1:
1384 case Builtin::BI__sync_and_and_fetch_2:
1385 case Builtin::BI__sync_and_and_fetch_4:
1386 case Builtin::BI__sync_and_and_fetch_8:
1387 case Builtin::BI__sync_and_and_fetch_16:
1388 BuiltinIndex = 7;
1389 break;
1390
1391 case Builtin::BI__sync_or_and_fetch:
1392 case Builtin::BI__sync_or_and_fetch_1:
1393 case Builtin::BI__sync_or_and_fetch_2:
1394 case Builtin::BI__sync_or_and_fetch_4:
1395 case Builtin::BI__sync_or_and_fetch_8:
1396 case Builtin::BI__sync_or_and_fetch_16:
1397 BuiltinIndex = 8;
1398 break;
1399
1400 case Builtin::BI__sync_xor_and_fetch:
1401 case Builtin::BI__sync_xor_and_fetch_1:
1402 case Builtin::BI__sync_xor_and_fetch_2:
1403 case Builtin::BI__sync_xor_and_fetch_4:
1404 case Builtin::BI__sync_xor_and_fetch_8:
1405 case Builtin::BI__sync_xor_and_fetch_16:
1406 BuiltinIndex = 9;
1407 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Chris Lattner5caa3702009-05-08 06:58:22 +00001409 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001410 case Builtin::BI__sync_val_compare_and_swap_1:
1411 case Builtin::BI__sync_val_compare_and_swap_2:
1412 case Builtin::BI__sync_val_compare_and_swap_4:
1413 case Builtin::BI__sync_val_compare_and_swap_8:
1414 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001415 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001416 NumFixed = 2;
1417 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001418
Chris Lattner5caa3702009-05-08 06:58:22 +00001419 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001420 case Builtin::BI__sync_bool_compare_and_swap_1:
1421 case Builtin::BI__sync_bool_compare_and_swap_2:
1422 case Builtin::BI__sync_bool_compare_and_swap_4:
1423 case Builtin::BI__sync_bool_compare_and_swap_8:
1424 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001425 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001426 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001427 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001428 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001429
1430 case Builtin::BI__sync_lock_test_and_set:
1431 case Builtin::BI__sync_lock_test_and_set_1:
1432 case Builtin::BI__sync_lock_test_and_set_2:
1433 case Builtin::BI__sync_lock_test_and_set_4:
1434 case Builtin::BI__sync_lock_test_and_set_8:
1435 case Builtin::BI__sync_lock_test_and_set_16:
1436 BuiltinIndex = 12;
1437 break;
1438
Chris Lattner5caa3702009-05-08 06:58:22 +00001439 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001440 case Builtin::BI__sync_lock_release_1:
1441 case Builtin::BI__sync_lock_release_2:
1442 case Builtin::BI__sync_lock_release_4:
1443 case Builtin::BI__sync_lock_release_8:
1444 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001445 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001446 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001447 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001448 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001449
1450 case Builtin::BI__sync_swap:
1451 case Builtin::BI__sync_swap_1:
1452 case Builtin::BI__sync_swap_2:
1453 case Builtin::BI__sync_swap_4:
1454 case Builtin::BI__sync_swap_8:
1455 case Builtin::BI__sync_swap_16:
1456 BuiltinIndex = 14;
1457 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001458 }
Mike Stump1eb44332009-09-09 15:08:12 +00001459
Chris Lattner5caa3702009-05-08 06:58:22 +00001460 // Now that we know how many fixed arguments we expect, first check that we
1461 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001462 if (TheCall->getNumArgs() < 1+NumFixed) {
1463 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1464 << 0 << 1+NumFixed << TheCall->getNumArgs()
1465 << TheCall->getCallee()->getSourceRange();
1466 return ExprError();
1467 }
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001469 // Get the decl for the concrete builtin from this, we can tell what the
1470 // concrete integer type we should convert to is.
1471 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1472 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001473 FunctionDecl *NewBuiltinDecl;
1474 if (NewBuiltinID == BuiltinID)
1475 NewBuiltinDecl = FDecl;
1476 else {
1477 // Perform builtin lookup to avoid redeclaring it.
1478 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1479 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1480 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1481 assert(Res.getFoundDecl());
1482 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1483 if (NewBuiltinDecl == 0)
1484 return ExprError();
1485 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001486
John McCallf871d0c2010-08-07 06:22:56 +00001487 // The first argument --- the pointer --- has a fixed type; we
1488 // deduce the types of the rest of the arguments accordingly. Walk
1489 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001490 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001491 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001492
Chris Lattner5caa3702009-05-08 06:58:22 +00001493 // GCC does an implicit conversion to the pointer or integer ValType. This
1494 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001495 // Initialize the argument.
1496 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1497 ValType, /*consume*/ false);
1498 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001499 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001500 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Chris Lattner5caa3702009-05-08 06:58:22 +00001502 // Okay, we have something that *can* be converted to the right type. Check
1503 // to see if there is a potentially weird extension going on here. This can
1504 // happen when you do an atomic operation on something like an char* and
1505 // pass in 42. The 42 gets converted to char. This is even more strange
1506 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001507 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001508 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001509 }
Mike Stump1eb44332009-09-09 15:08:12 +00001510
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001511 ASTContext& Context = this->getASTContext();
1512
1513 // Create a new DeclRefExpr to refer to the new decl.
1514 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1515 Context,
1516 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001517 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001518 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001519 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001520 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001521 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001522 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Chris Lattner5caa3702009-05-08 06:58:22 +00001524 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001525 // FIXME: This loses syntactic information.
1526 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1527 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1528 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001529 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001531 // Change the result type of the call to match the original value type. This
1532 // is arbitrary, but the codegen for these builtins ins design to handle it
1533 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001534 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001535
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001536 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001537}
1538
Chris Lattner69039812009-02-18 06:01:06 +00001539/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001540/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001541/// Note: It might also make sense to do the UTF-16 conversion here (would
1542/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001543bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001544 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001545 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1546
Douglas Gregor5cee1192011-07-27 05:40:30 +00001547 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001548 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1549 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001550 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001551 }
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001553 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001554 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001555 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001556 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001557 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001558 UTF16 *ToPtr = &ToBuf[0];
1559
1560 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1561 &ToPtr, ToPtr + NumBytes,
1562 strictConversion);
1563 // Check for conversion failure.
1564 if (Result != conversionOK)
1565 Diag(Arg->getLocStart(),
1566 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1567 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001568 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001569}
1570
Chris Lattnerc27c6652007-12-20 00:05:45 +00001571/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1572/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001573bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1574 Expr *Fn = TheCall->getCallee();
1575 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001576 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001577 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001578 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1579 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001580 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001581 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001582 return true;
1583 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001584
1585 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001586 return Diag(TheCall->getLocEnd(),
1587 diag::err_typecheck_call_too_few_args_at_least)
1588 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001589 }
1590
John McCall5f8d6042011-08-27 01:09:30 +00001591 // Type-check the first argument normally.
1592 if (checkBuiltinArgument(*this, TheCall, 0))
1593 return true;
1594
Chris Lattnerc27c6652007-12-20 00:05:45 +00001595 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001596 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001597 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001598 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001599 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001600 else if (FunctionDecl *FD = getCurFunctionDecl())
1601 isVariadic = FD->isVariadic();
1602 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001603 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001604
Chris Lattnerc27c6652007-12-20 00:05:45 +00001605 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001606 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1607 return true;
1608 }
Mike Stump1eb44332009-09-09 15:08:12 +00001609
Chris Lattner30ce3442007-12-19 23:59:04 +00001610 // Verify that the second argument to the builtin is the last argument of the
1611 // current function or method.
1612 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001613 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001614
Nico Weberb07d4482013-05-24 23:31:57 +00001615 // These are valid if SecondArgIsLastNamedArgument is false after the next
1616 // block.
1617 QualType Type;
1618 SourceLocation ParamLoc;
1619
Anders Carlsson88cf2262008-02-11 04:20:54 +00001620 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1621 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001622 // FIXME: This isn't correct for methods (results in bogus warning).
1623 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001624 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001625 if (CurBlock)
1626 LastArg = *(CurBlock->TheDecl->param_end()-1);
1627 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001628 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001629 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001630 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001631 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001632
1633 Type = PV->getType();
1634 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001635 }
1636 }
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Chris Lattner30ce3442007-12-19 23:59:04 +00001638 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001639 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001640 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001641 else if (Type->isReferenceType()) {
1642 Diag(Arg->getLocStart(),
1643 diag::warn_va_start_of_reference_type_is_undefined);
1644 Diag(ParamLoc, diag::note_parameter_type) << Type;
1645 }
1646
Chris Lattner30ce3442007-12-19 23:59:04 +00001647 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001648}
Chris Lattner30ce3442007-12-19 23:59:04 +00001649
Chris Lattner1b9a0792007-12-20 00:26:33 +00001650/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1651/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001652bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1653 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001654 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001655 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001656 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001657 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001658 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001659 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001660 << SourceRange(TheCall->getArg(2)->getLocStart(),
1661 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001662
John Wiegley429bb272011-04-08 18:41:53 +00001663 ExprResult OrigArg0 = TheCall->getArg(0);
1664 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001665
Chris Lattner1b9a0792007-12-20 00:26:33 +00001666 // Do standard promotions between the two arguments, returning their common
1667 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001668 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001669 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1670 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001671
1672 // Make sure any conversions are pushed back into the call; this is
1673 // type safe since unordered compare builtins are declared as "_Bool
1674 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001675 TheCall->setArg(0, OrigArg0.get());
1676 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001677
John Wiegley429bb272011-04-08 18:41:53 +00001678 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001679 return false;
1680
Chris Lattner1b9a0792007-12-20 00:26:33 +00001681 // If the common type isn't a real floating type, then the arguments were
1682 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001683 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001684 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001685 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001686 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1687 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001688
Chris Lattner1b9a0792007-12-20 00:26:33 +00001689 return false;
1690}
1691
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001692/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1693/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001694/// to check everything. We expect the last argument to be a floating point
1695/// value.
1696bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1697 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001698 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001699 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001700 if (TheCall->getNumArgs() > NumArgs)
1701 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001702 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001703 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001704 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001705 (*(TheCall->arg_end()-1))->getLocEnd());
1706
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001707 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Eli Friedman9ac6f622009-08-31 20:06:00 +00001709 if (OrigArg->isTypeDependent())
1710 return false;
1711
Chris Lattner81368fb2010-05-06 05:50:07 +00001712 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001713 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001714 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001715 diag::err_typecheck_call_invalid_unary_fp)
1716 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Chris Lattner81368fb2010-05-06 05:50:07 +00001718 // If this is an implicit conversion from float -> double, remove it.
1719 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1720 Expr *CastArg = Cast->getSubExpr();
1721 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1722 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1723 "promotion from float to double is the only expected cast here");
1724 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001725 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001726 }
1727 }
1728
Eli Friedman9ac6f622009-08-31 20:06:00 +00001729 return false;
1730}
1731
Eli Friedmand38617c2008-05-14 19:38:39 +00001732/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1733// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001734ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001735 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001736 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001737 diag::err_typecheck_call_too_few_args_at_least)
Craig Topperb44545a2013-07-28 21:50:10 +00001738 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1739 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001740
Nate Begeman37b6a572010-06-08 00:16:34 +00001741 // Determine which of the following types of shufflevector we're checking:
1742 // 1) unary, vector mask: (lhs, mask)
1743 // 2) binary, vector mask: (lhs, rhs, mask)
1744 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1745 QualType resType = TheCall->getArg(0)->getType();
1746 unsigned numElements = 0;
Craig Toppere3fbbe92013-07-19 04:46:31 +00001747
Douglas Gregorcde01732009-05-19 22:10:17 +00001748 if (!TheCall->getArg(0)->isTypeDependent() &&
1749 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001750 QualType LHSType = TheCall->getArg(0)->getType();
1751 QualType RHSType = TheCall->getArg(1)->getType();
Craig Toppere3fbbe92013-07-19 04:46:31 +00001752
Craig Topperbbe759c2013-07-29 06:47:04 +00001753 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1754 return ExprError(Diag(TheCall->getLocStart(),
1755 diag::err_shufflevector_non_vector)
1756 << SourceRange(TheCall->getArg(0)->getLocStart(),
1757 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001758
Nate Begeman37b6a572010-06-08 00:16:34 +00001759 numElements = LHSType->getAs<VectorType>()->getNumElements();
1760 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Nate Begeman37b6a572010-06-08 00:16:34 +00001762 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1763 // with mask. If so, verify that RHS is an integer vector type with the
1764 // same number of elts as lhs.
1765 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001766 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001767 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbbe759c2013-07-29 06:47:04 +00001768 return ExprError(Diag(TheCall->getLocStart(),
1769 diag::err_shufflevector_incompatible_vector)
1770 << SourceRange(TheCall->getArg(1)->getLocStart(),
1771 TheCall->getArg(1)->getLocEnd()));
Craig Toppere3fbbe92013-07-19 04:46:31 +00001772 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbbe759c2013-07-29 06:47:04 +00001773 return ExprError(Diag(TheCall->getLocStart(),
1774 diag::err_shufflevector_incompatible_vector)
1775 << SourceRange(TheCall->getArg(0)->getLocStart(),
1776 TheCall->getArg(1)->getLocEnd()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001777 } else if (numElements != numResElements) {
1778 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001779 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001780 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001781 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001782 }
1783
1784 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001785 if (TheCall->getArg(i)->isTypeDependent() ||
1786 TheCall->getArg(i)->isValueDependent())
1787 continue;
1788
Nate Begeman37b6a572010-06-08 00:16:34 +00001789 llvm::APSInt Result(32);
1790 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1791 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001792 diag::err_shufflevector_nonconstant_argument)
1793 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001794
Craig Topper6f4f8082013-08-03 17:40:38 +00001795 // Allow -1 which will be translated to undef in the IR.
1796 if (Result.isSigned() && Result.isAllOnesValue())
1797 continue;
1798
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001799 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001800 return ExprError(Diag(TheCall->getLocStart(),
Craig Topperb44545a2013-07-28 21:50:10 +00001801 diag::err_shufflevector_argument_too_large)
1802 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001803 }
1804
Chris Lattner5f9e2722011-07-23 10:55:15 +00001805 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001806
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001807 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001808 exprs.push_back(TheCall->getArg(i));
1809 TheCall->setArg(i, 0);
1810 }
1811
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001812 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001813 TheCall->getCallee()->getLocStart(),
1814 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001815}
Chris Lattner30ce3442007-12-19 23:59:04 +00001816
Daniel Dunbar4493f792008-07-21 22:59:13 +00001817/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1818// This is declared to take (const void*, ...) and can take two
1819// optional constant int args.
1820bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001821 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001822
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001823 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001824 return Diag(TheCall->getLocEnd(),
1825 diag::err_typecheck_call_too_many_args_at_most)
1826 << 0 /*function call*/ << 3 << NumArgs
1827 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001828
1829 // Argument 0 is checked for us and the remaining arguments must be
1830 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001831 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001832 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001833
1834 // We can't check the value of a dependent argument.
1835 if (Arg->isTypeDependent() || Arg->isValueDependent())
1836 continue;
1837
Eli Friedman9aef7262009-12-04 00:30:06 +00001838 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001839 if (SemaBuiltinConstantArg(TheCall, i, Result))
1840 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Daniel Dunbar4493f792008-07-21 22:59:13 +00001842 // FIXME: gcc issues a warning and rewrites these to 0. These
1843 // seems especially odd for the third argument since the default
1844 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001845 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001846 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001847 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001848 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001849 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001850 if (Result.getLimitedValue() > 3)
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" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001853 }
1854 }
1855
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001856 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001857}
1858
Eric Christopher691ebc32010-04-17 02:26:23 +00001859/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1860/// TheCall is a constant expression.
1861bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1862 llvm::APSInt &Result) {
1863 Expr *Arg = TheCall->getArg(ArgNum);
1864 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1865 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1866
1867 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1868
1869 if (!Arg->isIntegerConstantExpr(Result, Context))
1870 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001871 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001872
Chris Lattner21fb98e2009-09-23 06:06:36 +00001873 return false;
1874}
1875
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001876/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1877/// int type). This simply type checks that type is one of the defined
1878/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001879// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001880bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001881 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001882
1883 // We can't check the value of a dependent argument.
1884 if (TheCall->getArg(1)->isTypeDependent() ||
1885 TheCall->getArg(1)->isValueDependent())
1886 return false;
1887
Eric Christopher691ebc32010-04-17 02:26:23 +00001888 // Check constant-ness first.
1889 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1890 return true;
1891
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001892 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001893 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001894 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1895 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001896 }
1897
1898 return false;
1899}
1900
Eli Friedman586d6a82009-05-03 06:04:26 +00001901/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001902/// This checks that val is a constant 1.
1903bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1904 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001905 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001906
Eric Christopher691ebc32010-04-17 02:26:23 +00001907 // TODO: This is less than ideal. Overload this to take a value.
1908 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1909 return true;
1910
1911 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001912 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1913 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1914
1915 return false;
1916}
1917
Richard Smith0e218972013-08-05 18:49:43 +00001918namespace {
1919enum StringLiteralCheckType {
1920 SLCT_NotALiteral,
1921 SLCT_UncheckedLiteral,
1922 SLCT_CheckedLiteral
1923};
1924}
1925
Richard Smith831421f2012-06-25 20:30:08 +00001926// Determine if an expression is a string literal or constant string.
1927// If this function returns false on the arguments to a function expecting a
1928// format string, we will usually need to emit a warning.
1929// True string literals are then checked by CheckFormatString.
Richard Smith0e218972013-08-05 18:49:43 +00001930static StringLiteralCheckType
1931checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1932 bool HasVAListArg, unsigned format_idx,
1933 unsigned firstDataArg, Sema::FormatStringType Type,
1934 Sema::VariadicCallType CallType, bool InFunctionCall,
1935 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001936 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001937 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001938 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001939
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001940 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001941
Richard Smith0e218972013-08-05 18:49:43 +00001942 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikiea73cdcb2012-02-10 21:07:25 +00001943 // Technically -Wformat-nonliteral does not warn about this case.
1944 // The behavior of printf and friends in this case is implementation
1945 // dependent. Ideally if the format string cannot be null then
1946 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith0e218972013-08-05 18:49:43 +00001947 return SLCT_UncheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001948
Ted Kremenekd30ef872009-01-12 23:09:09 +00001949 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001950 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001951 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001952 // The expression is a literal if both sub-expressions were, and it was
1953 // completely checked only if both sub-expressions were checked.
1954 const AbstractConditionalOperator *C =
1955 cast<AbstractConditionalOperator>(E);
1956 StringLiteralCheckType Left =
Richard Smith0e218972013-08-05 18:49:43 +00001957 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001958 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001959 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001960 if (Left == SLCT_NotALiteral)
1961 return SLCT_NotALiteral;
1962 StringLiteralCheckType Right =
Richard Smith0e218972013-08-05 18:49:43 +00001963 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001964 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00001965 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00001966 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001967 }
1968
1969 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001970 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1971 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001972 }
1973
John McCall56ca35d2011-02-17 10:25:35 +00001974 case Stmt::OpaqueValueExprClass:
1975 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1976 E = src;
1977 goto tryAgain;
1978 }
Richard Smith831421f2012-06-25 20:30:08 +00001979 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001980
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001981 case Stmt::PredefinedExprClass:
1982 // While __func__, etc., are technically not string literals, they
1983 // cannot contain format specifiers and thus are not a security
1984 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001985 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001986
Ted Kremenek082d9362009-03-20 21:35:28 +00001987 case Stmt::DeclRefExprClass: {
1988 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Ted Kremenek082d9362009-03-20 21:35:28 +00001990 // As an exception, do not flag errors for variables binding to
1991 // const string literals.
1992 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1993 bool isConstant = false;
1994 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001995
Richard Smith0e218972013-08-05 18:49:43 +00001996 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
1997 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001998 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smith0e218972013-08-05 18:49:43 +00001999 isConstant = T.isConstant(S.Context) &&
2000 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00002001 } else if (T->isObjCObjectPointerType()) {
2002 // In ObjC, there is usually no "const ObjectPointer" type,
2003 // so don't check if the pointee type is constant.
Richard Smith0e218972013-08-05 18:49:43 +00002004 isConstant = T.isConstant(S.Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00002005 }
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Ted Kremenek082d9362009-03-20 21:35:28 +00002007 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002008 if (const Expr *Init = VD->getAnyInitializer()) {
2009 // Look through initializers like const char c[] = { "foo" }
2010 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2011 if (InitList->isStringLiteralInit())
2012 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2013 }
Richard Smith0e218972013-08-05 18:49:43 +00002014 return checkFormatStringExpr(S, Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002015 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002016 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002017 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00002018 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002019 }
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Anders Carlssond966a552009-06-28 19:55:58 +00002021 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2022 // special check to see if the format string is a function parameter
2023 // of the function calling the printf function. If the function
2024 // has an attribute indicating it is a printf-like function, then we
2025 // should suppress warnings concerning non-literals being used in a call
2026 // to a vprintf function. For example:
2027 //
2028 // void
2029 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2030 // va_list ap;
2031 // va_start(ap, fmt);
2032 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2033 // ...
Richard Smith0e218972013-08-05 18:49:43 +00002034 // }
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002035 if (HasVAListArg) {
2036 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2037 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2038 int PVIndex = PV->getFunctionScopeIndex() + 1;
2039 for (specific_attr_iterator<FormatAttr>
2040 i = ND->specific_attr_begin<FormatAttr>(),
2041 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2042 FormatAttr *PVFormat = *i;
2043 // adjust for implicit parameter
2044 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2045 if (MD->isInstance())
2046 ++PVIndex;
2047 // We also check if the formats are compatible.
2048 // We can't pass a 'scanf' string to a 'printf' function.
2049 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smith0e218972013-08-05 18:49:43 +00002050 Type == S.GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00002051 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00002052 }
2053 }
2054 }
2055 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
Richard Smith831421f2012-06-25 20:30:08 +00002058 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00002059 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00002060
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002061 case Stmt::CallExprClass:
2062 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00002063 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00002064 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2065 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2066 unsigned ArgIndex = FA->getFormatIdx();
2067 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2068 if (MD->isInstance())
2069 --ArgIndex;
2070 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Richard Smith0e218972013-08-05 18:49:43 +00002072 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002073 HasVAListArg, format_idx, firstDataArg,
Richard Smith0e218972013-08-05 18:49:43 +00002074 Type, CallType, InFunctionCall,
2075 CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002076 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2077 unsigned BuiltinID = FD->getBuiltinID();
2078 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2079 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2080 const Expr *Arg = CE->getArg(0);
Richard Smith0e218972013-08-05 18:49:43 +00002081 return checkFormatStringExpr(S, Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00002082 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002083 firstDataArg, Type, CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002084 InFunctionCall, CheckedVarArgs);
Jordan Rose50687312012-06-04 23:52:23 +00002085 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00002086 }
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Richard Smith831421f2012-06-25 20:30:08 +00002089 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00002090 }
Ted Kremenek082d9362009-03-20 21:35:28 +00002091 case Stmt::ObjCStringLiteralClass:
2092 case Stmt::StringLiteralClass: {
2093 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Ted Kremenek082d9362009-03-20 21:35:28 +00002095 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00002096 StrE = ObjCFExpr->getString();
2097 else
Ted Kremenek082d9362009-03-20 21:35:28 +00002098 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Ted Kremenekd30ef872009-01-12 23:09:09 +00002100 if (StrE) {
Richard Smith0e218972013-08-05 18:49:43 +00002101 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2102 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002103 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002104 }
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Richard Smith831421f2012-06-25 20:30:08 +00002106 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002107 }
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Ted Kremenek082d9362009-03-20 21:35:28 +00002109 default:
Richard Smith831421f2012-06-25 20:30:08 +00002110 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002111 }
2112}
2113
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002114void
Mike Stump1eb44332009-09-09 15:08:12 +00002115Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00002116 const Expr * const *ExprArgs,
2117 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00002118 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2119 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002120 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00002121 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00002122
2123 // As a special case, transparent unions initialized with zero are
2124 // considered null for the purposes of the nonnull attribute.
2125 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2126 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2127 if (const CompoundLiteralExpr *CLE =
2128 dyn_cast<CompoundLiteralExpr>(ArgExpr))
2129 if (const InitListExpr *ILE =
2130 dyn_cast<InitListExpr>(CLE->getInitializer()))
2131 ArgExpr = ILE->getInit(0);
2132 }
2133
2134 bool Result;
2135 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00002136 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00002137 }
2138}
Ted Kremenekd30ef872009-01-12 23:09:09 +00002139
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002140Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2141 return llvm::StringSwitch<FormatStringType>(Format->getType())
2142 .Case("scanf", FST_Scanf)
2143 .Cases("printf", "printf0", FST_Printf)
2144 .Cases("NSString", "CFString", FST_NSString)
2145 .Case("strftime", FST_Strftime)
2146 .Case("strfmon", FST_Strfmon)
2147 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2148 .Default(FST_Unknown);
2149}
2150
Jordan Roseddcfbc92012-07-19 18:10:23 +00002151/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00002152/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00002153/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002154bool Sema::CheckFormatArguments(const FormatAttr *Format,
2155 ArrayRef<const Expr *> Args,
2156 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002157 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002158 SourceLocation Loc, SourceRange Range,
2159 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith831421f2012-06-25 20:30:08 +00002160 FormatStringInfo FSI;
2161 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002162 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00002163 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smith0e218972013-08-05 18:49:43 +00002164 CallType, Loc, Range, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002165 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002166}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00002167
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002168bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00002169 bool HasVAListArg, unsigned format_idx,
2170 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002171 VariadicCallType CallType,
Richard Smith0e218972013-08-05 18:49:43 +00002172 SourceLocation Loc, SourceRange Range,
2173 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002174 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002175 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002176 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00002177 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00002178 }
Mike Stump1eb44332009-09-09 15:08:12 +00002179
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002180 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Chris Lattner59907c42007-08-10 20:18:51 +00002182 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00002183 //
Ted Kremenek71895b92007-08-14 17:39:48 +00002184 // Dynamically generated format strings are difficult to
2185 // automatically vet at compile time. Requiring that format strings
2186 // are string literals: (1) permits the checking of format strings by
2187 // the compiler and thereby (2) can practically remove the source of
2188 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002189
Mike Stump1eb44332009-09-09 15:08:12 +00002190 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002191 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00002192 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002193 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00002194 StringLiteralCheckType CT =
Richard Smith0e218972013-08-05 18:49:43 +00002195 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2196 format_idx, firstDataArg, Type, CallType,
2197 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith831421f2012-06-25 20:30:08 +00002198 if (CT != SLCT_NotALiteral)
2199 // Literal format string found, check done!
2200 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00002201
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002202 // Strftime is particular as it always uses a single 'time' argument,
2203 // so it is safe to pass a non-literal string.
2204 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00002205 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00002206
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002207 // Do not emit diag when the string param is a macro expansion and the
2208 // format is either NSString or CFString. This is a hack to prevent
2209 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2210 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00002211 if (Type == FST_NSString &&
2212 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00002213 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00002214
Chris Lattner655f1412009-04-29 04:59:47 +00002215 // If there are no arguments specified, warn with -Wformat-security, otherwise
2216 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002217 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002218 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002219 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002220 << OrigFormatExpr->getSourceRange();
2221 else
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)
Chris Lattner655f1412009-04-29 04:59:47 +00002224 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002225 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002226}
Ted Kremenek71895b92007-08-14 17:39:48 +00002227
Ted Kremeneke0e53132010-01-28 23:39:18 +00002228namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002229class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2230protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002231 Sema &S;
2232 const StringLiteral *FExpr;
2233 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002234 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002235 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002236 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002237 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002238 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002239 unsigned FormatIdx;
Richard Smith0e218972013-08-05 18:49:43 +00002240 llvm::SmallBitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002241 bool usesPositionalArgs;
2242 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002243 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002244 Sema::VariadicCallType CallType;
Richard Smith0e218972013-08-05 18:49:43 +00002245 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002246public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002247 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002248 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002249 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002250 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002251 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002252 Sema::VariadicCallType callType,
2253 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002254 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002255 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2256 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002257 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002258 usesPositionalArgs(false), atFirstArg(true),
Richard Smith0e218972013-08-05 18:49:43 +00002259 inFunctionCall(inFunctionCall), CallType(callType),
2260 CheckedVarArgs(CheckedVarArgs) {
2261 CoveredArgs.resize(numDataArgs);
2262 CoveredArgs.reset();
2263 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002264
Ted Kremenek07d161f2010-01-29 01:50:07 +00002265 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002266
Ted Kremenek826a3452010-07-16 02:11:22 +00002267 void HandleIncompleteSpecifier(const char *startSpecifier,
2268 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002269
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002270 void HandleInvalidLengthModifier(
2271 const analyze_format_string::FormatSpecifier &FS,
2272 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002273 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002274
Hans Wennborg76517422012-02-22 10:17:01 +00002275 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002276 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002277 const char *startSpecifier, unsigned specifierLen);
2278
2279 void HandleNonStandardConversionSpecifier(
2280 const analyze_format_string::ConversionSpecifier &CS,
2281 const char *startSpecifier, unsigned specifierLen);
2282
Hans Wennborgf8562642012-03-09 10:10:54 +00002283 virtual void HandlePosition(const char *startPos, unsigned posLen);
2284
Ted Kremenekefaff192010-02-27 01:41:03 +00002285 virtual void HandleInvalidPosition(const char *startSpecifier,
2286 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002287 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002288
2289 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2290
Ted Kremeneke0e53132010-01-28 23:39:18 +00002291 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002292
Richard Trieu55733de2011-10-28 00:41:25 +00002293 template <typename Range>
2294 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2295 const Expr *ArgumentExpr,
2296 PartialDiagnostic PDiag,
2297 SourceLocation StringLoc,
2298 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002299 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002300
Ted Kremenek826a3452010-07-16 02:11:22 +00002301protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002302 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2303 const char *startSpec,
2304 unsigned specifierLen,
2305 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002306
2307 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2308 const char *startSpec,
2309 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002310
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002311 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002312 CharSourceRange getSpecifierRange(const char *startSpecifier,
2313 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002314 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002315
Ted Kremenek0d277352010-01-29 01:06:55 +00002316 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002317
2318 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2319 const analyze_format_string::ConversionSpecifier &CS,
2320 const char *startSpecifier, unsigned specifierLen,
2321 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002322
2323 template <typename Range>
2324 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2325 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002326 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002327
2328 void CheckPositionalAndNonpositionalArgs(
2329 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002330};
2331}
2332
Ted Kremenek826a3452010-07-16 02:11:22 +00002333SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002334 return OrigFormatExpr->getSourceRange();
2335}
2336
Ted Kremenek826a3452010-07-16 02:11:22 +00002337CharSourceRange CheckFormatHandler::
2338getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002339 SourceLocation Start = getLocationOfByte(startSpecifier);
2340 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2341
2342 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002343 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002344
2345 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002346}
2347
Ted Kremenek826a3452010-07-16 02:11:22 +00002348SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002349 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002350}
2351
Ted Kremenek826a3452010-07-16 02:11:22 +00002352void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2353 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002354 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2355 getLocationOfByte(startSpecifier),
2356 /*IsStringLocation*/true,
2357 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002358}
2359
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002360void CheckFormatHandler::HandleInvalidLengthModifier(
2361 const analyze_format_string::FormatSpecifier &FS,
2362 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002363 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002364 using namespace analyze_format_string;
2365
2366 const LengthModifier &LM = FS.getLengthModifier();
2367 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2368
2369 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002370 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002371 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002372 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002373 getLocationOfByte(LM.getStart()),
2374 /*IsStringLocation*/true,
2375 getSpecifierRange(startSpecifier, specifierLen));
2376
2377 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2378 << FixedLM->toString()
2379 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2380
2381 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002382 FixItHint Hint;
2383 if (DiagID == diag::warn_format_nonsensical_length)
2384 Hint = FixItHint::CreateRemoval(LMRange);
2385
2386 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002387 getLocationOfByte(LM.getStart()),
2388 /*IsStringLocation*/true,
2389 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002390 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002391 }
2392}
2393
Hans Wennborg76517422012-02-22 10:17:01 +00002394void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002395 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002396 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002397 using namespace analyze_format_string;
2398
2399 const LengthModifier &LM = FS.getLengthModifier();
2400 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2401
2402 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002403 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002404 if (FixedLM) {
2405 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2406 << LM.toString() << 0,
2407 getLocationOfByte(LM.getStart()),
2408 /*IsStringLocation*/true,
2409 getSpecifierRange(startSpecifier, specifierLen));
2410
2411 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2412 << FixedLM->toString()
2413 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2414
2415 } else {
2416 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2417 << LM.toString() << 0,
2418 getLocationOfByte(LM.getStart()),
2419 /*IsStringLocation*/true,
2420 getSpecifierRange(startSpecifier, specifierLen));
2421 }
Hans Wennborg76517422012-02-22 10:17:01 +00002422}
2423
2424void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2425 const analyze_format_string::ConversionSpecifier &CS,
2426 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002427 using namespace analyze_format_string;
2428
2429 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002430 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002431 if (FixedCS) {
2432 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2433 << CS.toString() << /*conversion specifier*/1,
2434 getLocationOfByte(CS.getStart()),
2435 /*IsStringLocation*/true,
2436 getSpecifierRange(startSpecifier, specifierLen));
2437
2438 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2439 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2440 << FixedCS->toString()
2441 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2442 } else {
2443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2444 << CS.toString() << /*conversion specifier*/1,
2445 getLocationOfByte(CS.getStart()),
2446 /*IsStringLocation*/true,
2447 getSpecifierRange(startSpecifier, specifierLen));
2448 }
Hans Wennborg76517422012-02-22 10:17:01 +00002449}
2450
Hans Wennborgf8562642012-03-09 10:10:54 +00002451void CheckFormatHandler::HandlePosition(const char *startPos,
2452 unsigned posLen) {
2453 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2454 getLocationOfByte(startPos),
2455 /*IsStringLocation*/true,
2456 getSpecifierRange(startPos, posLen));
2457}
2458
Ted Kremenekefaff192010-02-27 01:41:03 +00002459void
Ted Kremenek826a3452010-07-16 02:11:22 +00002460CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2461 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002462 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2463 << (unsigned) p,
2464 getLocationOfByte(startPos), /*IsStringLocation*/true,
2465 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002466}
2467
Ted Kremenek826a3452010-07-16 02:11:22 +00002468void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002469 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2471 getLocationOfByte(startPos),
2472 /*IsStringLocation*/true,
2473 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002474}
2475
Ted Kremenek826a3452010-07-16 02:11:22 +00002476void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002477 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002478 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002479 EmitFormatDiagnostic(
2480 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2481 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2482 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002483 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002484}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002485
Jordan Rose48716662012-07-19 18:10:08 +00002486// Note that this may return NULL if there was an error parsing or building
2487// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002488const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002489 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002490}
2491
2492void CheckFormatHandler::DoneProcessing() {
2493 // Does the number of data arguments exceed the number of
2494 // format conversions in the format string?
2495 if (!HasVAListArg) {
2496 // Find any arguments that weren't covered.
2497 CoveredArgs.flip();
2498 signed notCoveredArg = CoveredArgs.find_first();
2499 if (notCoveredArg >= 0) {
2500 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002501 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2502 SourceLocation Loc = E->getLocStart();
2503 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2504 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2505 Loc, /*IsStringLocation*/false,
2506 getFormatStringRange());
2507 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002508 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002509 }
2510 }
2511}
2512
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002513bool
2514CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2515 SourceLocation Loc,
2516 const char *startSpec,
2517 unsigned specifierLen,
2518 const char *csStart,
2519 unsigned csLen) {
2520
2521 bool keepGoing = true;
2522 if (argIndex < NumDataArgs) {
2523 // Consider the argument coverered, even though the specifier doesn't
2524 // make sense.
2525 CoveredArgs.set(argIndex);
2526 }
2527 else {
2528 // If argIndex exceeds the number of data arguments we
2529 // don't issue a warning because that is just a cascade of warnings (and
2530 // they may have intended '%%' anyway). We don't want to continue processing
2531 // the format string after this point, however, as we will like just get
2532 // gibberish when trying to match arguments.
2533 keepGoing = false;
2534 }
2535
Richard Trieu55733de2011-10-28 00:41:25 +00002536 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2537 << StringRef(csStart, csLen),
2538 Loc, /*IsStringLocation*/true,
2539 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002540
2541 return keepGoing;
2542}
2543
Richard Trieu55733de2011-10-28 00:41:25 +00002544void
2545CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2546 const char *startSpec,
2547 unsigned specifierLen) {
2548 EmitFormatDiagnostic(
2549 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2550 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2551}
2552
Ted Kremenek666a1972010-07-26 19:45:42 +00002553bool
2554CheckFormatHandler::CheckNumArgs(
2555 const analyze_format_string::FormatSpecifier &FS,
2556 const analyze_format_string::ConversionSpecifier &CS,
2557 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2558
2559 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002560 PartialDiagnostic PDiag = FS.usesPositionalArg()
2561 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2562 << (argIndex+1) << NumDataArgs)
2563 : S.PDiag(diag::warn_printf_insufficient_data_args);
2564 EmitFormatDiagnostic(
2565 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2566 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002567 return false;
2568 }
2569 return true;
2570}
2571
Richard Trieu55733de2011-10-28 00:41:25 +00002572template<typename Range>
2573void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2574 SourceLocation Loc,
2575 bool IsStringLocation,
2576 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002577 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002578 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002579 Loc, IsStringLocation, StringRange, FixIt);
2580}
2581
2582/// \brief If the format string is not within the funcion call, emit a note
2583/// so that the function call and string are in diagnostic messages.
2584///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002585/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002586/// call and only one diagnostic message will be produced. Otherwise, an
2587/// extra note will be emitted pointing to location of the format string.
2588///
2589/// \param ArgumentExpr the expression that is passed as the format string
2590/// argument in the function call. Used for getting locations when two
2591/// diagnostics are emitted.
2592///
2593/// \param PDiag the callee should already have provided any strings for the
2594/// diagnostic message. This function only adds locations and fixits
2595/// to diagnostics.
2596///
2597/// \param Loc primary location for diagnostic. If two diagnostics are
2598/// required, one will be at Loc and a new SourceLocation will be created for
2599/// the other one.
2600///
2601/// \param IsStringLocation if true, Loc points to the format string should be
2602/// used for the note. Otherwise, Loc points to the argument list and will
2603/// be used with PDiag.
2604///
2605/// \param StringRange some or all of the string to highlight. This is
2606/// templated so it can accept either a CharSourceRange or a SourceRange.
2607///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002608/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002609template<typename Range>
2610void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2611 const Expr *ArgumentExpr,
2612 PartialDiagnostic PDiag,
2613 SourceLocation Loc,
2614 bool IsStringLocation,
2615 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002616 ArrayRef<FixItHint> FixIt) {
2617 if (InFunctionCall) {
2618 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2619 D << StringRange;
2620 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2621 I != E; ++I) {
2622 D << *I;
2623 }
2624 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002625 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2626 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002627
2628 const Sema::SemaDiagnosticBuilder &Note =
2629 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2630 diag::note_format_string_defined);
2631
2632 Note << StringRange;
2633 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2634 I != E; ++I) {
2635 Note << *I;
2636 }
Richard Trieu55733de2011-10-28 00:41:25 +00002637 }
2638}
2639
Ted Kremenek826a3452010-07-16 02:11:22 +00002640//===--- CHECK: Printf format string checking ------------------------------===//
2641
2642namespace {
2643class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002644 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002645public:
2646 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2647 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002648 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002649 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002650 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002651 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00002652 Sema::VariadicCallType CallType,
2653 llvm::SmallBitVector &CheckedVarArgs)
2654 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2655 numDataArgs, beg, hasVAListArg, Args,
2656 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2657 ObjCContext(isObjC)
Jordan Roseddcfbc92012-07-19 18:10:23 +00002658 {}
2659
Ted Kremenek826a3452010-07-16 02:11:22 +00002660
2661 bool HandleInvalidPrintfConversionSpecifier(
2662 const analyze_printf::PrintfSpecifier &FS,
2663 const char *startSpecifier,
2664 unsigned specifierLen);
2665
2666 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2667 const char *startSpecifier,
2668 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002669 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2670 const char *StartSpecifier,
2671 unsigned SpecifierLen,
2672 const Expr *E);
2673
Ted Kremenek826a3452010-07-16 02:11:22 +00002674 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2675 const char *startSpecifier, unsigned specifierLen);
2676 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2677 const analyze_printf::OptionalAmount &Amt,
2678 unsigned type,
2679 const char *startSpecifier, unsigned specifierLen);
2680 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2681 const analyze_printf::OptionalFlag &flag,
2682 const char *startSpecifier, unsigned specifierLen);
2683 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2684 const analyze_printf::OptionalFlag &ignoredFlag,
2685 const analyze_printf::OptionalFlag &flag,
2686 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002687 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002688 const Expr *E, const CharSourceRange &CSR);
2689
Ted Kremenek826a3452010-07-16 02:11:22 +00002690};
2691}
2692
2693bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2694 const analyze_printf::PrintfSpecifier &FS,
2695 const char *startSpecifier,
2696 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002697 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002698 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002699
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002700 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2701 getLocationOfByte(CS.getStart()),
2702 startSpecifier, specifierLen,
2703 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002704}
2705
Ted Kremenek826a3452010-07-16 02:11:22 +00002706bool CheckPrintfHandler::HandleAmount(
2707 const analyze_format_string::OptionalAmount &Amt,
2708 unsigned k, const char *startSpecifier,
2709 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002710
2711 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002712 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002713 unsigned argIndex = Amt.getArgIndex();
2714 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002715 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2716 << k,
2717 getLocationOfByte(Amt.getStart()),
2718 /*IsStringLocation*/true,
2719 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002720 // Don't do any more checking. We will just emit
2721 // spurious errors.
2722 return false;
2723 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002724
Ted Kremenek0d277352010-01-29 01:06:55 +00002725 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002726 // Although not in conformance with C99, we also allow the argument to be
2727 // an 'unsigned int' as that is a reasonably safe case. GCC also
2728 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002729 CoveredArgs.set(argIndex);
2730 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002731 if (!Arg)
2732 return false;
2733
Ted Kremenek0d277352010-01-29 01:06:55 +00002734 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002735
Hans Wennborgf3749f42012-08-07 08:11:26 +00002736 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2737 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002738
Hans Wennborgf3749f42012-08-07 08:11:26 +00002739 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002740 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002741 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002742 << T << Arg->getSourceRange(),
2743 getLocationOfByte(Amt.getStart()),
2744 /*IsStringLocation*/true,
2745 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002746 // Don't do any more checking. We will just emit
2747 // spurious errors.
2748 return false;
2749 }
2750 }
2751 }
2752 return true;
2753}
Ted Kremenek0d277352010-01-29 01:06:55 +00002754
Tom Caree4ee9662010-06-17 19:00:27 +00002755void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002756 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002757 const analyze_printf::OptionalAmount &Amt,
2758 unsigned type,
2759 const char *startSpecifier,
2760 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002761 const analyze_printf::PrintfConversionSpecifier &CS =
2762 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002763
Richard Trieu55733de2011-10-28 00:41:25 +00002764 FixItHint fixit =
2765 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2766 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2767 Amt.getConstantLength()))
2768 : FixItHint();
2769
2770 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2771 << type << CS.toString(),
2772 getLocationOfByte(Amt.getStart()),
2773 /*IsStringLocation*/true,
2774 getSpecifierRange(startSpecifier, specifierLen),
2775 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002776}
2777
Ted Kremenek826a3452010-07-16 02:11:22 +00002778void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002779 const analyze_printf::OptionalFlag &flag,
2780 const char *startSpecifier,
2781 unsigned specifierLen) {
2782 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002783 const analyze_printf::PrintfConversionSpecifier &CS =
2784 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2786 << flag.toString() << CS.toString(),
2787 getLocationOfByte(flag.getPosition()),
2788 /*IsStringLocation*/true,
2789 getSpecifierRange(startSpecifier, specifierLen),
2790 FixItHint::CreateRemoval(
2791 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002792}
2793
2794void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002795 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002796 const analyze_printf::OptionalFlag &ignoredFlag,
2797 const analyze_printf::OptionalFlag &flag,
2798 const char *startSpecifier,
2799 unsigned specifierLen) {
2800 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002801 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2802 << ignoredFlag.toString() << flag.toString(),
2803 getLocationOfByte(ignoredFlag.getPosition()),
2804 /*IsStringLocation*/true,
2805 getSpecifierRange(startSpecifier, specifierLen),
2806 FixItHint::CreateRemoval(
2807 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002808}
2809
Richard Smith831421f2012-06-25 20:30:08 +00002810// Determines if the specified is a C++ class or struct containing
2811// a member with the specified name and kind (e.g. a CXXMethodDecl named
2812// "c_str()").
2813template<typename MemberKind>
2814static llvm::SmallPtrSet<MemberKind*, 1>
2815CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2816 const RecordType *RT = Ty->getAs<RecordType>();
2817 llvm::SmallPtrSet<MemberKind*, 1> Results;
2818
2819 if (!RT)
2820 return Results;
2821 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2822 if (!RD)
2823 return Results;
2824
2825 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2826 Sema::LookupMemberName);
2827
2828 // We just need to include all members of the right kind turned up by the
2829 // filter, at this point.
2830 if (S.LookupQualifiedName(R, RT->getDecl()))
2831 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2832 NamedDecl *decl = (*I)->getUnderlyingDecl();
2833 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2834 Results.insert(FK);
2835 }
2836 return Results;
2837}
2838
2839// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002840// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002841// Returns true when a c_str() conversion method is found.
2842bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002843 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002844 const CharSourceRange &CSR) {
2845 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2846
2847 MethodSet Results =
2848 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2849
2850 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2851 MI != ME; ++MI) {
2852 const CXXMethodDecl *Method = *MI;
2853 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002854 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002855 // FIXME: Suggest parens if the expression needs them.
2856 SourceLocation EndLoc =
2857 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2858 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2859 << "c_str()"
2860 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2861 return true;
2862 }
2863 }
2864
2865 return false;
2866}
2867
Ted Kremeneke0e53132010-01-28 23:39:18 +00002868bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002869CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002870 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002871 const char *startSpecifier,
2872 unsigned specifierLen) {
2873
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002874 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002875 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002876 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002877
Ted Kremenekbaa40062010-07-19 22:01:06 +00002878 if (FS.consumesDataArgument()) {
2879 if (atFirstArg) {
2880 atFirstArg = false;
2881 usesPositionalArgs = FS.usesPositionalArg();
2882 }
2883 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002884 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2885 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002886 return false;
2887 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002888 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002889
Ted Kremenekefaff192010-02-27 01:41:03 +00002890 // First check if the field width, precision, and conversion specifier
2891 // have matching data arguments.
2892 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2893 startSpecifier, specifierLen)) {
2894 return false;
2895 }
2896
2897 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2898 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002899 return false;
2900 }
2901
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002902 if (!CS.consumesDataArgument()) {
2903 // FIXME: Technically specifying a precision or field width here
2904 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002905 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002906 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002907
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002908 // Consume the argument.
2909 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002910 if (argIndex < NumDataArgs) {
2911 // The check to see if the argIndex is valid will come later.
2912 // We set the bit here because we may exit early from this
2913 // function if we encounter some other error.
2914 CoveredArgs.set(argIndex);
2915 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002916
2917 // Check for using an Objective-C specific conversion specifier
2918 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002919 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002920 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2921 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002922 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002923
Tom Caree4ee9662010-06-17 19:00:27 +00002924 // Check for invalid use of field width
2925 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002926 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002927 startSpecifier, specifierLen);
2928 }
2929
2930 // Check for invalid use of precision
2931 if (!FS.hasValidPrecision()) {
2932 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2933 startSpecifier, specifierLen);
2934 }
2935
2936 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002937 if (!FS.hasValidThousandsGroupingPrefix())
2938 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002939 if (!FS.hasValidLeadingZeros())
2940 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2941 if (!FS.hasValidPlusPrefix())
2942 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002943 if (!FS.hasValidSpacePrefix())
2944 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002945 if (!FS.hasValidAlternativeForm())
2946 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2947 if (!FS.hasValidLeftJustified())
2948 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2949
2950 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002951 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2952 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2953 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002954 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2955 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2956 startSpecifier, specifierLen);
2957
2958 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002959 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002960 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2961 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002962 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002963 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002964 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002965 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2966 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002967
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002968 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2969 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2970
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002971 // The remaining checks depend on the data arguments.
2972 if (HasVAListArg)
2973 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002974
Ted Kremenek666a1972010-07-26 19:45:42 +00002975 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002976 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002977
Jordan Rose48716662012-07-19 18:10:08 +00002978 const Expr *Arg = getDataArg(argIndex);
2979 if (!Arg)
2980 return true;
2981
2982 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002983}
2984
Jordan Roseec087352012-09-05 22:56:26 +00002985static bool requiresParensToAddCast(const Expr *E) {
2986 // FIXME: We should have a general way to reason about operator
2987 // precedence and whether parens are actually needed here.
2988 // Take care of a few common cases where they aren't.
2989 const Expr *Inside = E->IgnoreImpCasts();
2990 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2991 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2992
2993 switch (Inside->getStmtClass()) {
2994 case Stmt::ArraySubscriptExprClass:
2995 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002996 case Stmt::CharacterLiteralClass:
2997 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002998 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002999 case Stmt::FloatingLiteralClass:
3000 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003001 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003002 case Stmt::ObjCArrayLiteralClass:
3003 case Stmt::ObjCBoolLiteralExprClass:
3004 case Stmt::ObjCBoxedExprClass:
3005 case Stmt::ObjCDictionaryLiteralClass:
3006 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003007 case Stmt::ObjCIvarRefExprClass:
3008 case Stmt::ObjCMessageExprClass:
3009 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003010 case Stmt::ObjCStringLiteralClass:
3011 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00003012 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00003013 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00003014 case Stmt::UnaryOperatorClass:
3015 return false;
3016 default:
3017 return true;
3018 }
3019}
3020
Richard Smith831421f2012-06-25 20:30:08 +00003021bool
3022CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3023 const char *StartSpecifier,
3024 unsigned SpecifierLen,
3025 const Expr *E) {
3026 using namespace analyze_format_string;
3027 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003028 // Now type check the data expression that matches the
3029 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00003030 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3031 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00003032 if (!AT.isValid())
3033 return true;
Jordan Roseec087352012-09-05 22:56:26 +00003034
Jordan Rose448ac3e2012-12-05 18:44:40 +00003035 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00003036 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3037 ExprTy = TET->getUnderlyingExpr()->getType();
3038 }
3039
Jordan Rose448ac3e2012-12-05 18:44:40 +00003040 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003041 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00003042
Jordan Rose614a8652012-09-05 22:56:19 +00003043 // Look through argument promotions for our error message's reported type.
3044 // This includes the integral and floating promotions, but excludes array
3045 // and function pointer decay; seeing that an argument intended to be a
3046 // string has type 'char [6]' is probably more confusing than 'char *'.
3047 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3048 if (ICE->getCastKind() == CK_IntegralCast ||
3049 ICE->getCastKind() == CK_FloatingCast) {
3050 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00003051 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00003052
3053 // Check if we didn't match because of an implicit cast from a 'char'
3054 // or 'short' to an 'int'. This is done because printf is a varargs
3055 // function.
3056 if (ICE->getType() == S.Context.IntTy ||
3057 ICE->getType() == S.Context.UnsignedIntTy) {
3058 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003059 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00003060 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00003061 }
Jordan Roseee0259d2012-06-04 22:48:57 +00003062 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00003063 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3064 // Special case for 'a', which has type 'int' in C.
3065 // Note, however, that we do /not/ want to treat multibyte constants like
3066 // 'MooV' as characters! This form is deprecated but still exists.
3067 if (ExprTy == S.Context.IntTy)
3068 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3069 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00003070 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003071
Jordan Rose2cd34402012-12-05 18:44:49 +00003072 // %C in an Objective-C context prints a unichar, not a wchar_t.
3073 // If the argument is an integer of some kind, believe the %C and suggest
3074 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00003075 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00003076 if (ObjCContext &&
3077 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3078 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3079 !ExprTy->isCharType()) {
3080 // 'unichar' is defined as a typedef of unsigned short, but we should
3081 // prefer using the typedef if it is visible.
3082 IntendedTy = S.Context.UnsignedShortTy;
3083
3084 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3085 Sema::LookupOrdinaryName);
3086 if (S.LookupName(Result, S.getCurScope())) {
3087 NamedDecl *ND = Result.getFoundDecl();
3088 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3089 if (TD->getUnderlyingType() == IntendedTy)
3090 IntendedTy = S.Context.getTypedefType(TD);
3091 }
3092 }
3093 }
3094
3095 // Special-case some of Darwin's platform-independence types by suggesting
3096 // casts to primitive types that are known to be large enough.
3097 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00003098 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00003099 // Use a 'while' to peel off layers of typedefs.
3100 QualType TyTy = IntendedTy;
3101 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00003102 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00003103 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00003104 .Case("NSInteger", S.Context.LongTy)
3105 .Case("NSUInteger", S.Context.UnsignedLongTy)
3106 .Case("SInt32", S.Context.IntTy)
3107 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00003108 .Default(QualType());
3109
3110 if (!CastTy.isNull()) {
3111 ShouldNotPrintDirectly = true;
3112 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00003113 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00003114 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00003115 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00003116 }
3117 }
3118
Jordan Rose614a8652012-09-05 22:56:19 +00003119 // We may be able to offer a FixItHint if it is a supported type.
3120 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00003121 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00003122 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003123
Jordan Rose614a8652012-09-05 22:56:19 +00003124 if (success) {
3125 // Get the fix string from the fixed format specifier
3126 SmallString<16> buf;
3127 llvm::raw_svector_ostream os(buf);
3128 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003129
Jordan Roseec087352012-09-05 22:56:26 +00003130 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3131
Jordan Rose2cd34402012-12-05 18:44:49 +00003132 if (IntendedTy == ExprTy) {
3133 // In this case, the specifier is wrong and should be changed to match
3134 // the argument.
3135 EmitFormatDiagnostic(
3136 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3137 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3138 << E->getSourceRange(),
3139 E->getLocStart(),
3140 /*IsStringLocation*/false,
3141 SpecRange,
3142 FixItHint::CreateReplacement(SpecRange, os.str()));
3143
3144 } else {
Jordan Roseec087352012-09-05 22:56:26 +00003145 // The canonical type for formatting this value is different from the
3146 // actual type of the expression. (This occurs, for example, with Darwin's
3147 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3148 // should be printed as 'long' for 64-bit compatibility.)
3149 // Rather than emitting a normal format/argument mismatch, we want to
3150 // add a cast to the recommended type (and correct the format string
3151 // if necessary).
3152 SmallString<16> CastBuf;
3153 llvm::raw_svector_ostream CastFix(CastBuf);
3154 CastFix << "(";
3155 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3156 CastFix << ")";
3157
3158 SmallVector<FixItHint,4> Hints;
3159 if (!AT.matchesType(S.Context, IntendedTy))
3160 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3161
3162 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3163 // If there's already a cast present, just replace it.
3164 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3165 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3166
3167 } else if (!requiresParensToAddCast(E)) {
3168 // If the expression has high enough precedence,
3169 // just write the C-style cast.
3170 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3171 CastFix.str()));
3172 } else {
3173 // Otherwise, add parens around the expression as well as the cast.
3174 CastFix << "(";
3175 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3176 CastFix.str()));
3177
3178 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3179 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3180 }
3181
Jordan Rose2cd34402012-12-05 18:44:49 +00003182 if (ShouldNotPrintDirectly) {
3183 // The expression has a type that should not be printed directly.
3184 // We extract the name from the typedef because we don't want to show
3185 // the underlying type in the diagnostic.
3186 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00003187
Jordan Rose2cd34402012-12-05 18:44:49 +00003188 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3189 << Name << IntendedTy
3190 << E->getSourceRange(),
3191 E->getLocStart(), /*IsStringLocation=*/false,
3192 SpecRange, Hints);
3193 } else {
3194 // In this case, the expression could be printed using a different
3195 // specifier, but we've decided that the specifier is probably correct
3196 // and we should cast instead. Just use the normal warning message.
3197 EmitFormatDiagnostic(
3198 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3199 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3200 << E->getSourceRange(),
3201 E->getLocStart(), /*IsStringLocation*/false,
3202 SpecRange, Hints);
3203 }
Jordan Roseec087352012-09-05 22:56:26 +00003204 }
Jordan Rose614a8652012-09-05 22:56:19 +00003205 } else {
3206 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3207 SpecifierLen);
3208 // Since the warning for passing non-POD types to variadic functions
3209 // was deferred until now, we emit a warning for non-POD
3210 // arguments here.
Richard Smith0e218972013-08-05 18:49:43 +00003211 switch (S.isValidVarArgType(ExprTy)) {
3212 case Sema::VAK_Valid:
3213 case Sema::VAK_ValidInCXX11:
Jordan Rose614a8652012-09-05 22:56:19 +00003214 EmitFormatDiagnostic(
Richard Smith0e218972013-08-05 18:49:43 +00003215 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3216 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3217 << CSR
3218 << E->getSourceRange(),
3219 E->getLocStart(), /*IsStringLocation*/false, CSR);
3220 break;
3221
3222 case Sema::VAK_Undefined:
3223 EmitFormatDiagnostic(
3224 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith80ad52f2013-01-02 11:42:31 +00003225 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003226 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003227 << CallType
3228 << AT.getRepresentativeTypeName(S.Context)
3229 << CSR
3230 << E->getSourceRange(),
3231 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose614a8652012-09-05 22:56:19 +00003232 checkForCStrMembers(AT, E, CSR);
Richard Smith0e218972013-08-05 18:49:43 +00003233 break;
3234
3235 case Sema::VAK_Invalid:
3236 if (ExprTy->isObjCObjectType())
3237 EmitFormatDiagnostic(
3238 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3239 << S.getLangOpts().CPlusPlus11
3240 << ExprTy
3241 << CallType
3242 << AT.getRepresentativeTypeName(S.Context)
3243 << CSR
3244 << E->getSourceRange(),
3245 E->getLocStart(), /*IsStringLocation*/false, CSR);
3246 else
3247 // FIXME: If this is an initializer list, suggest removing the braces
3248 // or inserting a cast to the target type.
3249 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3250 << isa<InitListExpr>(E) << ExprTy << CallType
3251 << AT.getRepresentativeTypeName(S.Context)
3252 << E->getSourceRange();
3253 break;
3254 }
3255
3256 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3257 "format string specifier index out of range");
3258 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003259 }
3260
Ted Kremeneke0e53132010-01-28 23:39:18 +00003261 return true;
3262}
3263
Ted Kremenek826a3452010-07-16 02:11:22 +00003264//===--- CHECK: Scanf format string checking ------------------------------===//
3265
3266namespace {
3267class CheckScanfHandler : public CheckFormatHandler {
3268public:
3269 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3270 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003271 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003272 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003273 unsigned formatIdx, bool inFunctionCall,
Richard Smith0e218972013-08-05 18:49:43 +00003274 Sema::VariadicCallType CallType,
3275 llvm::SmallBitVector &CheckedVarArgs)
3276 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3277 numDataArgs, beg, hasVAListArg,
3278 Args, formatIdx, inFunctionCall, CallType,
3279 CheckedVarArgs)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003280 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003281
3282 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3283 const char *startSpecifier,
3284 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003285
3286 bool HandleInvalidScanfConversionSpecifier(
3287 const analyze_scanf::ScanfSpecifier &FS,
3288 const char *startSpecifier,
3289 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003290
3291 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003292};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003293}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003294
Ted Kremenekb7c21012010-07-16 18:28:03 +00003295void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3296 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003297 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3298 getLocationOfByte(end), /*IsStringLocation*/true,
3299 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003300}
3301
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003302bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3303 const analyze_scanf::ScanfSpecifier &FS,
3304 const char *startSpecifier,
3305 unsigned specifierLen) {
3306
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003307 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003308 FS.getConversionSpecifier();
3309
3310 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3311 getLocationOfByte(CS.getStart()),
3312 startSpecifier, specifierLen,
3313 CS.getStart(), CS.getLength());
3314}
3315
Ted Kremenek826a3452010-07-16 02:11:22 +00003316bool CheckScanfHandler::HandleScanfSpecifier(
3317 const analyze_scanf::ScanfSpecifier &FS,
3318 const char *startSpecifier,
3319 unsigned specifierLen) {
3320
3321 using namespace analyze_scanf;
3322 using namespace analyze_format_string;
3323
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003324 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003325
Ted Kremenekbaa40062010-07-19 22:01:06 +00003326 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3327 // be used to decide if we are using positional arguments consistently.
3328 if (FS.consumesDataArgument()) {
3329 if (atFirstArg) {
3330 atFirstArg = false;
3331 usesPositionalArgs = FS.usesPositionalArg();
3332 }
3333 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003334 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3335 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003336 return false;
3337 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003338 }
3339
3340 // Check if the field with is non-zero.
3341 const OptionalAmount &Amt = FS.getFieldWidth();
3342 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3343 if (Amt.getConstantAmount() == 0) {
3344 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3345 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003346 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3347 getLocationOfByte(Amt.getStart()),
3348 /*IsStringLocation*/true, R,
3349 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003350 }
3351 }
3352
3353 if (!FS.consumesDataArgument()) {
3354 // FIXME: Technically specifying a precision or field width here
3355 // makes no sense. Worth issuing a warning at some point.
3356 return true;
3357 }
3358
3359 // Consume the argument.
3360 unsigned argIndex = FS.getArgIndex();
3361 if (argIndex < NumDataArgs) {
3362 // The check to see if the argIndex is valid will come later.
3363 // We set the bit here because we may exit early from this
3364 // function if we encounter some other error.
3365 CoveredArgs.set(argIndex);
3366 }
3367
Ted Kremenek1e51c202010-07-20 20:04:47 +00003368 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003369 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003370 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3371 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003372 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003373 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003374 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003375 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3376 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003377
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003378 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3379 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3380
Ted Kremenek826a3452010-07-16 02:11:22 +00003381 // The remaining checks depend on the data arguments.
3382 if (HasVAListArg)
3383 return true;
3384
Ted Kremenek666a1972010-07-26 19:45:42 +00003385 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003386 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003387
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003388 // Check that the argument type matches the format specifier.
3389 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003390 if (!Ex)
3391 return true;
3392
Hans Wennborg58e1e542012-08-07 08:59:46 +00003393 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3394 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003395 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003396 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003397 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003398
3399 if (success) {
3400 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003401 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003402 llvm::raw_svector_ostream os(buf);
3403 fixedFS.toString(os);
3404
3405 EmitFormatDiagnostic(
3406 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003407 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003408 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003409 Ex->getLocStart(),
3410 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003411 getSpecifierRange(startSpecifier, specifierLen),
3412 FixItHint::CreateReplacement(
3413 getSpecifierRange(startSpecifier, specifierLen),
3414 os.str()));
3415 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003416 EmitFormatDiagnostic(
3417 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003418 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003419 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003420 Ex->getLocStart(),
3421 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003422 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003423 }
3424 }
3425
Ted Kremenek826a3452010-07-16 02:11:22 +00003426 return true;
3427}
3428
3429void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003430 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003431 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003432 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003433 unsigned firstDataArg, FormatStringType Type,
Richard Smith0e218972013-08-05 18:49:43 +00003434 bool inFunctionCall, VariadicCallType CallType,
3435 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003436
Ted Kremeneke0e53132010-01-28 23:39:18 +00003437 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003438 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003439 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003440 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003441 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3442 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003443 return;
3444 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003445
Ted Kremeneke0e53132010-01-28 23:39:18 +00003446 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003447 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003448 const char *Str = StrRef.data();
3449 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003450 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003451
Ted Kremeneke0e53132010-01-28 23:39:18 +00003452 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003453 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003454 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003455 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003456 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3457 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003458 return;
3459 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003460
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003461 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003462 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003463 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003464 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003465 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003466
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003467 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003468 getLangOpts(),
3469 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003470 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003471 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003472 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003473 Str, HasVAListArg, Args, format_idx,
Richard Smith0e218972013-08-05 18:49:43 +00003474 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek826a3452010-07-16 02:11:22 +00003475
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003476 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003477 getLangOpts(),
3478 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003479 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003480 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003481}
3482
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003483//===--- CHECK: Standard memory functions ---------------------------------===//
3484
Douglas Gregor2a053a32011-05-03 20:05:22 +00003485/// \brief Determine whether the given type is a dynamic class type (e.g.,
3486/// whether it has a vtable).
3487static bool isDynamicClassType(QualType T) {
3488 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3489 if (CXXRecordDecl *Definition = Record->getDefinition())
3490 if (Definition->isDynamicClass())
3491 return true;
3492
3493 return false;
3494}
3495
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003496/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003497/// otherwise returns NULL.
3498static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003499 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003500 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3501 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3502 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003503
Chandler Carruth000d4282011-06-16 09:09:40 +00003504 return 0;
3505}
3506
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003507/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003508static QualType getSizeOfArgType(const Expr* E) {
3509 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3510 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3511 if (SizeOf->getKind() == clang::UETT_SizeOf)
3512 return SizeOf->getTypeOfArgument();
3513
3514 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003515}
3516
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003517/// \brief Check for dangerous or invalid arguments to memset().
3518///
Chandler Carruth929f0132011-06-03 06:23:57 +00003519/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003520/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3521/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003522///
3523/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003524void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003525 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003526 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003527 assert(BId != 0);
3528
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003529 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003530 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003531 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003532 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003533 return;
3534
Anna Zaks0a151a12012-01-17 00:37:07 +00003535 unsigned LastArg = (BId == Builtin::BImemset ||
3536 BId == Builtin::BIstrndup ? 1 : 2);
3537 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003538 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003539
3540 // We have special checking when the length is a sizeof expression.
3541 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3542 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3543 llvm::FoldingSetNodeID SizeOfArgID;
3544
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003545 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3546 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003547 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003548
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003549 QualType DestTy = Dest->getType();
3550 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3551 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003552
Chandler Carruth000d4282011-06-16 09:09:40 +00003553 // Never warn about void type pointers. This can be used to suppress
3554 // false positives.
3555 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003556 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003557
Chandler Carruth000d4282011-06-16 09:09:40 +00003558 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3559 // actually comparing the expressions for equality. Because computing the
3560 // expression IDs can be expensive, we only do this if the diagnostic is
3561 // enabled.
3562 if (SizeOfArg &&
3563 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3564 SizeOfArg->getExprLoc())) {
3565 // We only compute IDs for expressions if the warning is enabled, and
3566 // cache the sizeof arg's ID.
3567 if (SizeOfArgID == llvm::FoldingSetNodeID())
3568 SizeOfArg->Profile(SizeOfArgID, Context, true);
3569 llvm::FoldingSetNodeID DestID;
3570 Dest->Profile(DestID, Context, true);
3571 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003572 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3573 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003574 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003575 StringRef ReadableName = FnName->getName();
3576
Chandler Carruth000d4282011-06-16 09:09:40 +00003577 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003578 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003579 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003580 if (!PointeeTy->isIncompleteType() &&
3581 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003582 ActionIdx = 2; // If the pointee's size is sizeof(char),
3583 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003584
3585 // If the function is defined as a builtin macro, do not show macro
3586 // expansion.
3587 SourceLocation SL = SizeOfArg->getExprLoc();
3588 SourceRange DSR = Dest->getSourceRange();
3589 SourceRange SSR = SizeOfArg->getSourceRange();
3590 SourceManager &SM = PP.getSourceManager();
3591
3592 if (SM.isMacroArgExpansion(SL)) {
3593 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3594 SL = SM.getSpellingLoc(SL);
3595 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3596 SM.getSpellingLoc(DSR.getEnd()));
3597 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3598 SM.getSpellingLoc(SSR.getEnd()));
3599 }
3600
Anna Zaks90c78322012-05-30 23:14:52 +00003601 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003602 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003603 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003604 << PointeeTy
3605 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003606 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003607 << SSR);
3608 DiagRuntimeBehavior(SL, SizeOfArg,
3609 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3610 << ActionIdx
3611 << SSR);
3612
Chandler Carruth000d4282011-06-16 09:09:40 +00003613 break;
3614 }
3615 }
3616
3617 // Also check for cases where the sizeof argument is the exact same
3618 // type as the memory argument, and where it points to a user-defined
3619 // record type.
3620 if (SizeOfArgTy != QualType()) {
3621 if (PointeeTy->isRecordType() &&
3622 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3623 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3624 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3625 << FnName << SizeOfArgTy << ArgIdx
3626 << PointeeTy << Dest->getSourceRange()
3627 << LenExpr->getSourceRange());
3628 break;
3629 }
Nico Webere4a1c642011-06-14 16:14:58 +00003630 }
3631
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003632 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003633 if (isDynamicClassType(PointeeTy)) {
3634
3635 unsigned OperationType = 0;
3636 // "overwritten" if we're warning about the destination for any call
3637 // but memcmp; otherwise a verb appropriate to the call.
3638 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3639 if (BId == Builtin::BImemcpy)
3640 OperationType = 1;
3641 else if(BId == Builtin::BImemmove)
3642 OperationType = 2;
3643 else if (BId == Builtin::BImemcmp)
3644 OperationType = 3;
3645 }
3646
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003647 DiagRuntimeBehavior(
3648 Dest->getExprLoc(), Dest,
3649 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003650 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003651 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003652 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003653 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003654 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3655 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003656 DiagRuntimeBehavior(
3657 Dest->getExprLoc(), Dest,
3658 PDiag(diag::warn_arc_object_memaccess)
3659 << ArgIdx << FnName << PointeeTy
3660 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003661 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003662 continue;
John McCallf85e1932011-06-15 23:02:42 +00003663
3664 DiagRuntimeBehavior(
3665 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003666 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003667 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3668 break;
3669 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003670 }
3671}
3672
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003673// A little helper routine: ignore addition and subtraction of integer literals.
3674// This intentionally does not ignore all integer constant expressions because
3675// we don't want to remove sizeof().
3676static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3677 Ex = Ex->IgnoreParenCasts();
3678
3679 for (;;) {
3680 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3681 if (!BO || !BO->isAdditiveOp())
3682 break;
3683
3684 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3685 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3686
3687 if (isa<IntegerLiteral>(RHS))
3688 Ex = LHS;
3689 else if (isa<IntegerLiteral>(LHS))
3690 Ex = RHS;
3691 else
3692 break;
3693 }
3694
3695 return Ex;
3696}
3697
Anna Zaks0f38ace2012-08-08 21:42:23 +00003698static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3699 ASTContext &Context) {
3700 // Only handle constant-sized or VLAs, but not flexible members.
3701 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3702 // Only issue the FIXIT for arrays of size > 1.
3703 if (CAT->getSize().getSExtValue() <= 1)
3704 return false;
3705 } else if (!Ty->isVariableArrayType()) {
3706 return false;
3707 }
3708 return true;
3709}
3710
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003711// Warn if the user has made the 'size' argument to strlcpy or strlcat
3712// be the size of the source, instead of the destination.
3713void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3714 IdentifierInfo *FnName) {
3715
3716 // Don't crash if the user has the wrong number of arguments
3717 if (Call->getNumArgs() != 3)
3718 return;
3719
3720 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3721 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3722 const Expr *CompareWithSrc = NULL;
3723
3724 // Look for 'strlcpy(dst, x, sizeof(x))'
3725 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3726 CompareWithSrc = Ex;
3727 else {
3728 // Look for 'strlcpy(dst, x, strlen(x))'
3729 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003730 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003731 && SizeCall->getNumArgs() == 1)
3732 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3733 }
3734 }
3735
3736 if (!CompareWithSrc)
3737 return;
3738
3739 // Determine if the argument to sizeof/strlen is equal to the source
3740 // argument. In principle there's all kinds of things you could do
3741 // here, for instance creating an == expression and evaluating it with
3742 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3743 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3744 if (!SrcArgDRE)
3745 return;
3746
3747 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3748 if (!CompareWithSrcDRE ||
3749 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3750 return;
3751
3752 const Expr *OriginalSizeArg = Call->getArg(2);
3753 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3754 << OriginalSizeArg->getSourceRange() << FnName;
3755
3756 // Output a FIXIT hint if the destination is an array (rather than a
3757 // pointer to an array). This could be enhanced to handle some
3758 // pointers if we know the actual size, like if DstArg is 'array+2'
3759 // we could say 'sizeof(array)-2'.
3760 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003761 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003762 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003763
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003764 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003765 llvm::raw_svector_ostream OS(sizeString);
3766 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003767 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003768 OS << ")";
3769
3770 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3771 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3772 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003773}
3774
Anna Zaksc36bedc2012-02-01 19:08:57 +00003775/// Check if two expressions refer to the same declaration.
3776static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3777 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3778 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3779 return D1->getDecl() == D2->getDecl();
3780 return false;
3781}
3782
3783static const Expr *getStrlenExprArg(const Expr *E) {
3784 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3785 const FunctionDecl *FD = CE->getDirectCallee();
3786 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3787 return 0;
3788 return CE->getArg(0)->IgnoreParenCasts();
3789 }
3790 return 0;
3791}
3792
3793// Warn on anti-patterns as the 'size' argument to strncat.
3794// The correct size argument should look like following:
3795// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3796void Sema::CheckStrncatArguments(const CallExpr *CE,
3797 IdentifierInfo *FnName) {
3798 // Don't crash if the user has the wrong number of arguments.
3799 if (CE->getNumArgs() < 3)
3800 return;
3801 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3802 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3803 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3804
3805 // Identify common expressions, which are wrongly used as the size argument
3806 // to strncat and may lead to buffer overflows.
3807 unsigned PatternType = 0;
3808 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3809 // - sizeof(dst)
3810 if (referToTheSameDecl(SizeOfArg, DstArg))
3811 PatternType = 1;
3812 // - sizeof(src)
3813 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3814 PatternType = 2;
3815 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3816 if (BE->getOpcode() == BO_Sub) {
3817 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3818 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3819 // - sizeof(dst) - strlen(dst)
3820 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3821 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3822 PatternType = 1;
3823 // - sizeof(src) - (anything)
3824 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3825 PatternType = 2;
3826 }
3827 }
3828
3829 if (PatternType == 0)
3830 return;
3831
Anna Zaksafdb0412012-02-03 01:27:37 +00003832 // Generate the diagnostic.
3833 SourceLocation SL = LenArg->getLocStart();
3834 SourceRange SR = LenArg->getSourceRange();
3835 SourceManager &SM = PP.getSourceManager();
3836
3837 // If the function is defined as a builtin macro, do not show macro expansion.
3838 if (SM.isMacroArgExpansion(SL)) {
3839 SL = SM.getSpellingLoc(SL);
3840 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3841 SM.getSpellingLoc(SR.getEnd()));
3842 }
3843
Anna Zaks0f38ace2012-08-08 21:42:23 +00003844 // Check if the destination is an array (rather than a pointer to an array).
3845 QualType DstTy = DstArg->getType();
3846 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3847 Context);
3848 if (!isKnownSizeArray) {
3849 if (PatternType == 1)
3850 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3851 else
3852 Diag(SL, diag::warn_strncat_src_size) << SR;
3853 return;
3854 }
3855
Anna Zaksc36bedc2012-02-01 19:08:57 +00003856 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003857 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003858 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003859 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003860
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003861 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003862 llvm::raw_svector_ostream OS(sizeString);
3863 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003864 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003865 OS << ") - ";
3866 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003867 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003868 OS << ") - 1";
3869
Anna Zaksafdb0412012-02-03 01:27:37 +00003870 Diag(SL, diag::note_strncat_wrong_size)
3871 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003872}
3873
Ted Kremenek06de2762007-08-17 16:46:58 +00003874//===--- CHECK: Return Address of Stack Variable --------------------------===//
3875
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003876static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3877 Decl *ParentDecl);
3878static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3879 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003880
3881/// CheckReturnStackAddr - Check if a return statement returns the address
3882/// of a stack variable.
3883void
3884Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3885 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003887 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003888 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003889
3890 // Perform checking for returned stack addresses, local blocks,
3891 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003892 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003893 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003894 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003895 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003896 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003897 }
3898
3899 if (stackE == 0)
3900 return; // Nothing suspicious was found.
3901
3902 SourceLocation diagLoc;
3903 SourceRange diagRange;
3904 if (refVars.empty()) {
3905 diagLoc = stackE->getLocStart();
3906 diagRange = stackE->getSourceRange();
3907 } else {
3908 // We followed through a reference variable. 'stackE' contains the
3909 // problematic expression but we will warn at the return statement pointing
3910 // at the reference variable. We will later display the "trail" of
3911 // reference variables using notes.
3912 diagLoc = refVars[0]->getLocStart();
3913 diagRange = refVars[0]->getSourceRange();
3914 }
3915
3916 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3917 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3918 : diag::warn_ret_stack_addr)
3919 << DR->getDecl()->getDeclName() << diagRange;
3920 } else if (isa<BlockExpr>(stackE)) { // local block.
3921 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3922 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3923 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3924 } else { // local temporary.
3925 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3926 : diag::warn_ret_local_temp_addr)
3927 << diagRange;
3928 }
3929
3930 // Display the "trail" of reference variables that we followed until we
3931 // found the problematic expression using notes.
3932 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3933 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3934 // If this var binds to another reference var, show the range of the next
3935 // var, otherwise the var binds to the problematic expression, in which case
3936 // show the range of the expression.
3937 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3938 : stackE->getSourceRange();
3939 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3940 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003941 }
3942}
3943
3944/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3945/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003946/// to a location on the stack, a local block, an address of a label, or a
3947/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003948/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003949/// encounter a subexpression that (1) clearly does not lead to one of the
3950/// above problematic expressions (2) is something we cannot determine leads to
3951/// a problematic expression based on such local checking.
3952///
3953/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3954/// the expression that they point to. Such variables are added to the
3955/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003956///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003957/// EvalAddr processes expressions that are pointers that are used as
3958/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003959/// At the base case of the recursion is a check for the above problematic
3960/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003961///
3962/// This implementation handles:
3963///
3964/// * pointer-to-pointer casts
3965/// * implicit conversions from array references to pointers
3966/// * taking the address of fields
3967/// * arbitrary interplay between "&" and "*" operators
3968/// * pointer arithmetic from an address of a stack variable
3969/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003970static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3971 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003972 if (E->isTypeDependent())
Craig Topperb61c2942013-08-02 05:10:31 +00003973 return NULL;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003974
Ted Kremenek06de2762007-08-17 16:46:58 +00003975 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003976 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003977 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003978 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003979 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003980
Peter Collingbournef111d932011-04-15 00:35:48 +00003981 E = E->IgnoreParens();
3982
Ted Kremenek06de2762007-08-17 16:46:58 +00003983 // Our "symbolic interpreter" is just a dispatch off the currently
3984 // viewed AST node. We then recursively traverse the AST by calling
3985 // EvalAddr and EvalVal appropriately.
3986 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003987 case Stmt::DeclRefExprClass: {
3988 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3989
3990 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3991 // If this is a reference variable, follow through to the expression that
3992 // it points to.
3993 if (V->hasLocalStorage() &&
3994 V->getType()->isReferenceType() && V->hasInit()) {
3995 // Add the reference variable to the "trail".
3996 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003997 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003998 }
3999
4000 return NULL;
4001 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004002
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004003 case Stmt::UnaryOperatorClass: {
4004 // The only unary operator that make sense to handle here
4005 // is AddrOf. All others don't make sense as pointers.
4006 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004007
John McCall2de56d12010-08-25 11:45:40 +00004008 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004009 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004010 else
Ted Kremenek06de2762007-08-17 16:46:58 +00004011 return NULL;
4012 }
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004014 case Stmt::BinaryOperatorClass: {
4015 // Handle pointer arithmetic. All other binary operators are not valid
4016 // in this context.
4017 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00004018 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00004019
John McCall2de56d12010-08-25 11:45:40 +00004020 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004021 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00004022
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004023 Expr *Base = B->getLHS();
4024
4025 // Determine which argument is the real pointer base. It could be
4026 // the RHS argument instead of the LHS.
4027 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00004028
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004029 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004030 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004031 }
Steve Naroff61f40a22008-09-10 19:17:48 +00004032
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004033 // For conditional operators we need to see if either the LHS or RHS are
4034 // valid DeclRefExpr*s. If one of them is valid, we return it.
4035 case Stmt::ConditionalOperatorClass: {
4036 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004037
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004038 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004039 if (Expr *lhsExpr = C->getLHS()) {
4040 // In C++, we can have a throw-expression, which has 'void' type.
4041 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004042 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004043 return LHS;
4044 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004045
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00004046 // In C++, we can have a throw-expression, which has 'void' type.
4047 if (C->getRHS()->getType()->isVoidType())
4048 return NULL;
4049
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004050 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004051 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004052
4053 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00004054 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004055 return E; // local block.
4056 return NULL;
4057
4058 case Stmt::AddrLabelExprClass:
4059 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00004060
John McCall80ee6e82011-11-10 05:35:25 +00004061 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004062 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4063 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004064
Ted Kremenek54b52742008-08-07 00:49:01 +00004065 // For casts, we need to handle conversions from arrays to
4066 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00004067 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00004068 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00004069 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00004070 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00004071 case Stmt::CXXStaticCastExprClass:
4072 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00004073 case Stmt::CXXConstCastExprClass:
4074 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00004075 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4076 switch (cast<CastExpr>(E)->getCastKind()) {
4077 case CK_BitCast:
4078 case CK_LValueToRValue:
4079 case CK_NoOp:
4080 case CK_BaseToDerived:
4081 case CK_DerivedToBase:
4082 case CK_UncheckedDerivedToBase:
4083 case CK_Dynamic:
4084 case CK_CPointerToObjCPointerCast:
4085 case CK_BlockPointerToObjCPointerCast:
4086 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004087 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004088
4089 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004090 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00004091
4092 default:
4093 return 0;
4094 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004095 }
Mike Stump1eb44332009-09-09 15:08:12 +00004096
Douglas Gregor03e80032011-06-21 17:03:29 +00004097 case Stmt::MaterializeTemporaryExprClass:
4098 if (Expr *Result = EvalAddr(
4099 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004100 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004101 return Result;
4102
4103 return E;
4104
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00004105 // Everything else: we simply don't reason about them.
4106 default:
4107 return NULL;
4108 }
Ted Kremenek06de2762007-08-17 16:46:58 +00004109}
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Ted Kremenek06de2762007-08-17 16:46:58 +00004111
4112/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4113/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004114static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4115 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004116do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00004117 // We should only be called for evaluating non-pointer expressions, or
4118 // expressions with a pointer type that are not used as references but instead
4119 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Ted Kremenek06de2762007-08-17 16:46:58 +00004121 // Our "symbolic interpreter" is just a dispatch off the currently
4122 // viewed AST node. We then recursively traverse the AST by calling
4123 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00004124
4125 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00004126 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004127 case Stmt::ImplicitCastExprClass: {
4128 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00004129 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00004130 E = IE->getSubExpr();
4131 continue;
4132 }
4133 return NULL;
4134 }
4135
John McCall80ee6e82011-11-10 05:35:25 +00004136 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004137 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00004138
Douglas Gregora2813ce2009-10-23 18:54:35 +00004139 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004140 // When we hit a DeclRefExpr we are looking at code that refers to a
4141 // variable's name. If it's not a reference variable we check if it has
4142 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00004143 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004144
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004145 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4146 // Check if it refers to itself, e.g. "int& i = i;".
4147 if (V == ParentDecl)
4148 return DR;
4149
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004150 if (V->hasLocalStorage()) {
4151 if (!V->getType()->isReferenceType())
4152 return DR;
4153
4154 // Reference variable, follow through to the expression that
4155 // it points to.
4156 if (V->hasInit()) {
4157 // Add the reference variable to the "trail".
4158 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004159 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004160 }
4161 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004162 }
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Ted Kremenek06de2762007-08-17 16:46:58 +00004164 return NULL;
4165 }
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Ted Kremenek06de2762007-08-17 16:46:58 +00004167 case Stmt::UnaryOperatorClass: {
4168 // The only unary operator that make sense to handle here
4169 // is Deref. All others don't resolve to a "name." This includes
4170 // handling all sorts of rvalues passed to a unary operator.
4171 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004172
John McCall2de56d12010-08-25 11:45:40 +00004173 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004174 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004175
4176 return NULL;
4177 }
Mike Stump1eb44332009-09-09 15:08:12 +00004178
Ted Kremenek06de2762007-08-17 16:46:58 +00004179 case Stmt::ArraySubscriptExprClass: {
4180 // Array subscripts are potential references to data on the stack. We
4181 // retrieve the DeclRefExpr* for the array variable if it indeed
4182 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004183 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004184 }
Mike Stump1eb44332009-09-09 15:08:12 +00004185
Ted Kremenek06de2762007-08-17 16:46:58 +00004186 case Stmt::ConditionalOperatorClass: {
4187 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004188 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00004189 ConditionalOperator *C = cast<ConditionalOperator>(E);
4190
Anders Carlsson39073232007-11-30 19:04:31 +00004191 // Handle the GNU extension for missing LHS.
4192 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004193 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00004194 return LHS;
4195
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004196 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004197 }
Mike Stump1eb44332009-09-09 15:08:12 +00004198
Ted Kremenek06de2762007-08-17 16:46:58 +00004199 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00004200 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00004201 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00004202
Ted Kremenek06de2762007-08-17 16:46:58 +00004203 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00004204 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00004205 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00004206
4207 // Check whether the member type is itself a reference, in which case
4208 // we're not going to refer to the member, but to what the member refers to.
4209 if (M->getMemberDecl()->getType()->isReferenceType())
4210 return NULL;
4211
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004212 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00004213 }
Mike Stump1eb44332009-09-09 15:08:12 +00004214
Douglas Gregor03e80032011-06-21 17:03:29 +00004215 case Stmt::MaterializeTemporaryExprClass:
4216 if (Expr *Result = EvalVal(
4217 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00004218 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00004219 return Result;
4220
4221 return E;
4222
Ted Kremenek06de2762007-08-17 16:46:58 +00004223 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00004224 // Check that we don't return or take the address of a reference to a
4225 // temporary. This is only useful in C++.
4226 if (!E->isTypeDependent() && E->isRValue())
4227 return E;
4228
4229 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00004230 return NULL;
4231 }
Ted Kremenek68957a92010-08-04 20:01:07 +00004232} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00004233}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004234
4235//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4236
4237/// Check for comparisons of floating point operands using != and ==.
4238/// Issue a warning if these are no self-comparisons, as they are not likely
4239/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00004240void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00004241 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4242 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004243
4244 // Special case: check for x == x (which is OK).
4245 // Do not emit warnings for such cases.
4246 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4247 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4248 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004249 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004250
4251
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004252 // Special case: check for comparisons against literals that can be exactly
4253 // represented by APFloat. In such cases, do not emit a warning. This
4254 // is a heuristic: often comparison against such literals are used to
4255 // detect if a value in a variable has not changed. This clearly can
4256 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004257 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4258 if (FLL->isExact())
4259 return;
4260 } else
4261 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4262 if (FLR->isExact())
4263 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004264
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004265 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004266 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4267 if (CL->isBuiltinCall())
4268 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004269
David Blaikie980343b2012-07-16 20:47:22 +00004270 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4271 if (CR->isBuiltinCall())
4272 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004274 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004275 Diag(Loc, diag::warn_floatingpoint_eq)
4276 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004277}
John McCallba26e582010-01-04 23:21:16 +00004278
John McCallf2370c92010-01-06 05:24:50 +00004279//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4280//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004281
John McCallf2370c92010-01-06 05:24:50 +00004282namespace {
John McCallba26e582010-01-04 23:21:16 +00004283
John McCallf2370c92010-01-06 05:24:50 +00004284/// Structure recording the 'active' range of an integer-valued
4285/// expression.
4286struct IntRange {
4287 /// The number of bits active in the int.
4288 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004289
John McCallf2370c92010-01-06 05:24:50 +00004290 /// True if the int is known not to have negative values.
4291 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004292
John McCallf2370c92010-01-06 05:24:50 +00004293 IntRange(unsigned Width, bool NonNegative)
4294 : Width(Width), NonNegative(NonNegative)
4295 {}
John McCallba26e582010-01-04 23:21:16 +00004296
John McCall1844a6e2010-11-10 23:38:19 +00004297 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004298 static IntRange forBoolType() {
4299 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004300 }
4301
John McCall1844a6e2010-11-10 23:38:19 +00004302 /// Returns the range of an opaque value of the given integral type.
4303 static IntRange forValueOfType(ASTContext &C, QualType T) {
4304 return forValueOfCanonicalType(C,
4305 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004306 }
4307
John McCall1844a6e2010-11-10 23:38:19 +00004308 /// Returns the range of an opaque value of a canonical integral type.
4309 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004310 assert(T->isCanonicalUnqualified());
4311
4312 if (const VectorType *VT = dyn_cast<VectorType>(T))
4313 T = VT->getElementType().getTypePtr();
4314 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4315 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004316
David Majnemerf9eaf982013-06-07 22:07:20 +00004317 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004318 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004319 EnumDecl *Enum = ET->getDecl();
4320 if (!Enum->isCompleteDefinition())
4321 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004322
David Majnemerf9eaf982013-06-07 22:07:20 +00004323 unsigned NumPositive = Enum->getNumPositiveBits();
4324 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004325
David Majnemerf9eaf982013-06-07 22:07:20 +00004326 if (NumNegative == 0)
4327 return IntRange(NumPositive, true/*NonNegative*/);
4328 else
4329 return IntRange(std::max(NumPositive + 1, NumNegative),
4330 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004331 }
John McCallf2370c92010-01-06 05:24:50 +00004332
4333 const BuiltinType *BT = cast<BuiltinType>(T);
4334 assert(BT->isInteger());
4335
4336 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4337 }
4338
John McCall1844a6e2010-11-10 23:38:19 +00004339 /// Returns the "target" range of a canonical integral type, i.e.
4340 /// the range of values expressible in the type.
4341 ///
4342 /// This matches forValueOfCanonicalType except that enums have the
4343 /// full range of their type, not the range of their enumerators.
4344 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4345 assert(T->isCanonicalUnqualified());
4346
4347 if (const VectorType *VT = dyn_cast<VectorType>(T))
4348 T = VT->getElementType().getTypePtr();
4349 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4350 T = CT->getElementType().getTypePtr();
4351 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004352 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004353
4354 const BuiltinType *BT = cast<BuiltinType>(T);
4355 assert(BT->isInteger());
4356
4357 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4358 }
4359
4360 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004361 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004362 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004363 L.NonNegative && R.NonNegative);
4364 }
4365
John McCall1844a6e2010-11-10 23:38:19 +00004366 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004367 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004368 return IntRange(std::min(L.Width, R.Width),
4369 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004370 }
4371};
4372
Ted Kremenek0692a192012-01-31 05:37:37 +00004373static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4374 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004375 if (value.isSigned() && value.isNegative())
4376 return IntRange(value.getMinSignedBits(), false);
4377
4378 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004379 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004380
4381 // isNonNegative() just checks the sign bit without considering
4382 // signedness.
4383 return IntRange(value.getActiveBits(), true);
4384}
4385
Ted Kremenek0692a192012-01-31 05:37:37 +00004386static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4387 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004388 if (result.isInt())
4389 return GetValueRange(C, result.getInt(), MaxWidth);
4390
4391 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004392 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4393 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4394 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4395 R = IntRange::join(R, El);
4396 }
John McCallf2370c92010-01-06 05:24:50 +00004397 return R;
4398 }
4399
4400 if (result.isComplexInt()) {
4401 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4402 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4403 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004404 }
4405
4406 // This can happen with lossless casts to intptr_t of "based" lvalues.
4407 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004408 // FIXME: The only reason we need to pass the type in here is to get
4409 // the sign right on this one case. It would be nice if APValue
4410 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004411 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004412 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004413}
John McCallf2370c92010-01-06 05:24:50 +00004414
Eli Friedman09bddcf2013-07-08 20:20:06 +00004415static QualType GetExprType(Expr *E) {
4416 QualType Ty = E->getType();
4417 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4418 Ty = AtomicRHS->getValueType();
4419 return Ty;
4420}
4421
John McCallf2370c92010-01-06 05:24:50 +00004422/// Pseudo-evaluate the given integer expression, estimating the
4423/// range of values it might take.
4424///
4425/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004426static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004427 E = E->IgnoreParens();
4428
4429 // Try a full evaluation first.
4430 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004431 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004432 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004433
4434 // I think we only want to look through implicit casts here; if the
4435 // user has an explicit widening cast, we should treat the value as
4436 // being of the new, wider type.
4437 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004438 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004439 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4440
Eli Friedman09bddcf2013-07-08 20:20:06 +00004441 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004442
John McCall2de56d12010-08-25 11:45:40 +00004443 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004444
John McCallf2370c92010-01-06 05:24:50 +00004445 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004446 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004447 return OutputTypeRange;
4448
4449 IntRange SubRange
4450 = GetExprRange(C, CE->getSubExpr(),
4451 std::min(MaxWidth, OutputTypeRange.Width));
4452
4453 // Bail out if the subexpr's range is as wide as the cast type.
4454 if (SubRange.Width >= OutputTypeRange.Width)
4455 return OutputTypeRange;
4456
4457 // Otherwise, we take the smaller width, and we're non-negative if
4458 // either the output type or the subexpr is.
4459 return IntRange(SubRange.Width,
4460 SubRange.NonNegative || OutputTypeRange.NonNegative);
4461 }
4462
4463 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4464 // If we can fold the condition, just take that operand.
4465 bool CondResult;
4466 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4467 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4468 : CO->getFalseExpr(),
4469 MaxWidth);
4470
4471 // Otherwise, conservatively merge.
4472 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4473 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4474 return IntRange::join(L, R);
4475 }
4476
4477 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4478 switch (BO->getOpcode()) {
4479
4480 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004481 case BO_LAnd:
4482 case BO_LOr:
4483 case BO_LT:
4484 case BO_GT:
4485 case BO_LE:
4486 case BO_GE:
4487 case BO_EQ:
4488 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004489 return IntRange::forBoolType();
4490
John McCall862ff872011-07-13 06:35:24 +00004491 // The type of the assignments is the type of the LHS, so the RHS
4492 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004493 case BO_MulAssign:
4494 case BO_DivAssign:
4495 case BO_RemAssign:
4496 case BO_AddAssign:
4497 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004498 case BO_XorAssign:
4499 case BO_OrAssign:
4500 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004501 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004502
John McCall862ff872011-07-13 06:35:24 +00004503 // Simple assignments just pass through the RHS, which will have
4504 // been coerced to the LHS type.
4505 case BO_Assign:
4506 // TODO: bitfields?
4507 return GetExprRange(C, BO->getRHS(), MaxWidth);
4508
John McCallf2370c92010-01-06 05:24:50 +00004509 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004510 case BO_PtrMemD:
4511 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004512 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004513
John McCall60fad452010-01-06 22:07:33 +00004514 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004515 case BO_And:
4516 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004517 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4518 GetExprRange(C, BO->getRHS(), MaxWidth));
4519
John McCallf2370c92010-01-06 05:24:50 +00004520 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004521 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004522 // ...except that we want to treat '1 << (blah)' as logically
4523 // positive. It's an important idiom.
4524 if (IntegerLiteral *I
4525 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4526 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004527 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004528 return IntRange(R.Width, /*NonNegative*/ true);
4529 }
4530 }
4531 // fallthrough
4532
John McCall2de56d12010-08-25 11:45:40 +00004533 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004534 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004535
John McCall60fad452010-01-06 22:07:33 +00004536 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004537 case BO_Shr:
4538 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004539 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4540
4541 // If the shift amount is a positive constant, drop the width by
4542 // that much.
4543 llvm::APSInt shift;
4544 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4545 shift.isNonNegative()) {
4546 unsigned zext = shift.getZExtValue();
4547 if (zext >= L.Width)
4548 L.Width = (L.NonNegative ? 0 : 1);
4549 else
4550 L.Width -= zext;
4551 }
4552
4553 return L;
4554 }
4555
4556 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004557 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004558 return GetExprRange(C, BO->getRHS(), MaxWidth);
4559
John McCall60fad452010-01-06 22:07:33 +00004560 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004561 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004562 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004563 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004564 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004565
John McCall00fe7612011-07-14 22:39:48 +00004566 // The width of a division result is mostly determined by the size
4567 // of the LHS.
4568 case BO_Div: {
4569 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004570 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004571 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4572
4573 // If the divisor is constant, use that.
4574 llvm::APSInt divisor;
4575 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4576 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4577 if (log2 >= L.Width)
4578 L.Width = (L.NonNegative ? 0 : 1);
4579 else
4580 L.Width = std::min(L.Width - log2, MaxWidth);
4581 return L;
4582 }
4583
4584 // Otherwise, just use the LHS's width.
4585 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4586 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4587 }
4588
4589 // The result of a remainder can't be larger than the result of
4590 // either side.
4591 case BO_Rem: {
4592 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004593 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004594 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4595 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4596
4597 IntRange meet = IntRange::meet(L, R);
4598 meet.Width = std::min(meet.Width, MaxWidth);
4599 return meet;
4600 }
4601
4602 // The default behavior is okay for these.
4603 case BO_Mul:
4604 case BO_Add:
4605 case BO_Xor:
4606 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004607 break;
4608 }
4609
John McCall00fe7612011-07-14 22:39:48 +00004610 // The default case is to treat the operation as if it were closed
4611 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004612 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4613 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4614 return IntRange::join(L, R);
4615 }
4616
4617 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4618 switch (UO->getOpcode()) {
4619 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004620 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004621 return IntRange::forBoolType();
4622
4623 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004624 case UO_Deref:
4625 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004626 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004627
4628 default:
4629 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4630 }
4631 }
4632
John McCall993f43f2013-05-06 21:39:12 +00004633 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004634 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004635 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004636
Eli Friedman09bddcf2013-07-08 20:20:06 +00004637 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004638}
John McCall51313c32010-01-04 23:31:57 +00004639
Ted Kremenek0692a192012-01-31 05:37:37 +00004640static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004641 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004642}
4643
John McCall51313c32010-01-04 23:31:57 +00004644/// Checks whether the given value, which currently has the given
4645/// source semantics, has the same value when coerced through the
4646/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004647static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4648 const llvm::fltSemantics &Src,
4649 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004650 llvm::APFloat truncated = value;
4651
4652 bool ignored;
4653 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4654 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4655
4656 return truncated.bitwiseIsEqual(value);
4657}
4658
4659/// Checks whether the given value, which currently has the given
4660/// source semantics, has the same value when coerced through the
4661/// target semantics.
4662///
4663/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004664static bool IsSameFloatAfterCast(const APValue &value,
4665 const llvm::fltSemantics &Src,
4666 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004667 if (value.isFloat())
4668 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4669
4670 if (value.isVector()) {
4671 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4672 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4673 return false;
4674 return true;
4675 }
4676
4677 assert(value.isComplexFloat());
4678 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4679 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4680}
4681
Ted Kremenek0692a192012-01-31 05:37:37 +00004682static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004683
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004684static bool IsZero(Sema &S, Expr *E) {
4685 // Suppress cases where we are comparing against an enum constant.
4686 if (const DeclRefExpr *DR =
4687 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4688 if (isa<EnumConstantDecl>(DR->getDecl()))
4689 return false;
4690
4691 // Suppress cases where the '0' value is expanded from a macro.
4692 if (E->getLocStart().isMacroID())
4693 return false;
4694
John McCall323ed742010-05-06 08:58:33 +00004695 llvm::APSInt Value;
4696 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4697}
4698
John McCall372e1032010-10-06 00:25:24 +00004699static bool HasEnumType(Expr *E) {
4700 // Strip off implicit integral promotions.
4701 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004702 if (ICE->getCastKind() != CK_IntegralCast &&
4703 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004704 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004705 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004706 }
4707
4708 return E->getType()->isEnumeralType();
4709}
4710
Ted Kremenek0692a192012-01-31 05:37:37 +00004711static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004712 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004713 if (E->isValueDependent())
4714 return;
4715
John McCall2de56d12010-08-25 11:45:40 +00004716 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004717 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004718 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004719 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004720 } else if (op == BO_GE && 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" << "true" << 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_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004725 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004726 << "0 >" << "false" << HasEnumType(E->getRHS())
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_LE && 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 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004731 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4732 }
4733}
4734
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004735static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004736 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004737 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004738 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004739 // 0 values are handled later by CheckTrivialUnsignedComparison().
4740 if (Value == 0)
4741 return;
4742
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004743 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004744 QualType OtherT = Other->getType();
4745 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004746 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004747 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004748 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004749 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004750 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004751
4752 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004753 bool CommonSigned = CommonT->isSignedIntegerType();
4754
4755 bool EqualityOnly = false;
4756
4757 // TODO: Investigate using GetExprRange() to get tighter bounds on
4758 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004759 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004760 unsigned OtherWidth = OtherRange.Width;
4761
4762 if (CommonSigned) {
4763 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004764 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004765 // Check that the constant is representable in type OtherT.
4766 if (ConstantSigned) {
4767 if (OtherWidth >= Value.getMinSignedBits())
4768 return;
4769 } else { // !ConstantSigned
4770 if (OtherWidth >= Value.getActiveBits() + 1)
4771 return;
4772 }
4773 } else { // !OtherSigned
4774 // Check that the constant is representable in type OtherT.
4775 // Negative values are out of range.
4776 if (ConstantSigned) {
4777 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4778 return;
4779 } else { // !ConstantSigned
4780 if (OtherWidth >= Value.getActiveBits())
4781 return;
4782 }
4783 }
4784 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004785 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004786 if (OtherWidth >= Value.getActiveBits())
4787 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004788 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004789 // Check to see if the constant is representable in OtherT.
4790 if (OtherWidth > Value.getActiveBits())
4791 return;
4792 // Check to see if the constant is equivalent to a negative value
4793 // cast to CommonT.
4794 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004795 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004796 return;
4797 // The constant value rests between values that OtherT can represent after
4798 // conversion. Relational comparison still works, but equality
4799 // comparisons will be tautological.
4800 EqualityOnly = true;
4801 } else { // OtherSigned && ConstantSigned
4802 assert(0 && "Two signed types converted to unsigned types.");
4803 }
4804 }
4805
4806 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4807
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004808 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004809 if (op == BO_EQ || op == BO_NE) {
4810 IsTrue = op == BO_NE;
4811 } else if (EqualityOnly) {
4812 return;
4813 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004814 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004815 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004816 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004817 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004818 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004819 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004820 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004821 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004822 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004823 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004824
4825 // If this is a comparison to an enum constant, include that
4826 // constant in the diagnostic.
4827 const EnumConstantDecl *ED = 0;
4828 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4829 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4830
4831 SmallString<64> PrettySourceValue;
4832 llvm::raw_svector_ostream OS(PrettySourceValue);
4833 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004834 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004835 else
4836 OS << Value;
4837
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004838 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004839 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004840 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004841}
4842
John McCall323ed742010-05-06 08:58:33 +00004843/// Analyze the operands of the given comparison. Implements the
4844/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004845static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004846 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4847 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004848}
John McCall51313c32010-01-04 23:31:57 +00004849
John McCallba26e582010-01-04 23:21:16 +00004850/// \brief Implements -Wsign-compare.
4851///
Richard Trieudd225092011-09-15 21:56:47 +00004852/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004853static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004854 // The type the comparison is being performed in.
4855 QualType T = E->getLHS()->getType();
4856 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4857 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004858 if (E->isValueDependent())
4859 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004860
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004861 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4862 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004863
4864 bool IsComparisonConstant = false;
4865
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004866 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004867 // of 'true' or 'false'.
4868 if (T->isIntegralType(S.Context)) {
4869 llvm::APSInt RHSValue;
4870 bool IsRHSIntegralLiteral =
4871 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4872 llvm::APSInt LHSValue;
4873 bool IsLHSIntegralLiteral =
4874 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4875 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4876 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4877 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4878 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4879 else
4880 IsComparisonConstant =
4881 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004882 } else if (!T->hasUnsignedIntegerRepresentation())
4883 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004884
John McCall323ed742010-05-06 08:58:33 +00004885 // We don't do anything special if this isn't an unsigned integral
4886 // comparison: we're only interested in integral comparisons, and
4887 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004888 //
4889 // We also don't care about value-dependent expressions or expressions
4890 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004891 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004892 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004893
John McCall323ed742010-05-06 08:58:33 +00004894 // Check to see if one of the (unmodified) operands is of different
4895 // signedness.
4896 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004897 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4898 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004899 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004900 signedOperand = LHS;
4901 unsignedOperand = RHS;
4902 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4903 signedOperand = RHS;
4904 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004905 } else {
John McCall323ed742010-05-06 08:58:33 +00004906 CheckTrivialUnsignedComparison(S, E);
4907 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004908 }
4909
John McCall323ed742010-05-06 08:58:33 +00004910 // Otherwise, calculate the effective range of the signed operand.
4911 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004912
John McCall323ed742010-05-06 08:58:33 +00004913 // Go ahead and analyze implicit conversions in the operands. Note
4914 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004915 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4916 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004917
John McCall323ed742010-05-06 08:58:33 +00004918 // If the signed range is non-negative, -Wsign-compare won't fire,
4919 // but we should still check for comparisons which are always true
4920 // or false.
4921 if (signedRange.NonNegative)
4922 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004923
4924 // For (in)equality comparisons, if the unsigned operand is a
4925 // constant which cannot collide with a overflowed signed operand,
4926 // then reinterpreting the signed operand as unsigned will not
4927 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004928 if (E->isEqualityOp()) {
4929 unsigned comparisonWidth = S.Context.getIntWidth(T);
4930 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004931
John McCall323ed742010-05-06 08:58:33 +00004932 // We should never be unable to prove that the unsigned operand is
4933 // non-negative.
4934 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4935
4936 if (unsignedRange.Width < comparisonWidth)
4937 return;
4938 }
4939
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004940 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4941 S.PDiag(diag::warn_mixed_sign_comparison)
4942 << LHS->getType() << RHS->getType()
4943 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004944}
4945
John McCall15d7d122010-11-11 03:21:53 +00004946/// Analyzes an attempt to assign the given value to a bitfield.
4947///
4948/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004949static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4950 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004951 assert(Bitfield->isBitField());
4952 if (Bitfield->isInvalidDecl())
4953 return false;
4954
John McCall91b60142010-11-11 05:33:51 +00004955 // White-list bool bitfields.
4956 if (Bitfield->getType()->isBooleanType())
4957 return false;
4958
Douglas Gregor46ff3032011-02-04 13:09:01 +00004959 // Ignore value- or type-dependent expressions.
4960 if (Bitfield->getBitWidth()->isValueDependent() ||
4961 Bitfield->getBitWidth()->isTypeDependent() ||
4962 Init->isValueDependent() ||
4963 Init->isTypeDependent())
4964 return false;
4965
John McCall15d7d122010-11-11 03:21:53 +00004966 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4967
Richard Smith80d4b552011-12-28 19:48:30 +00004968 llvm::APSInt Value;
4969 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004970 return false;
4971
John McCall15d7d122010-11-11 03:21:53 +00004972 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004973 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004974
4975 if (OriginalWidth <= FieldWidth)
4976 return false;
4977
Eli Friedman3a643af2012-01-26 23:11:39 +00004978 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004979 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004980 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004981
Eli Friedman3a643af2012-01-26 23:11:39 +00004982 // Check whether the stored value is equal to the original value.
4983 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004984 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004985 return false;
4986
Eli Friedman3a643af2012-01-26 23:11:39 +00004987 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004988 // therefore don't strictly fit into a signed bitfield of width 1.
4989 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004990 return false;
4991
John McCall15d7d122010-11-11 03:21:53 +00004992 std::string PrettyValue = Value.toString(10);
4993 std::string PrettyTrunc = TruncatedValue.toString(10);
4994
4995 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4996 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4997 << Init->getSourceRange();
4998
4999 return true;
5000}
5001
John McCallbeb22aa2010-11-09 23:24:47 +00005002/// Analyze the given simple or compound assignment for warning-worthy
5003/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00005004static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00005005 // Just recurse on the LHS.
5006 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5007
5008 // We want to recurse on the RHS as normal unless we're assigning to
5009 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00005010 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005011 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00005012 E->getOperatorLoc())) {
5013 // Recurse, ignoring any implicit conversions on the RHS.
5014 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5015 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00005016 }
5017 }
5018
5019 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5020}
5021
John McCall51313c32010-01-04 23:31:57 +00005022/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005023static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005024 SourceLocation CContext, unsigned diag,
5025 bool pruneControlFlow = false) {
5026 if (pruneControlFlow) {
5027 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5028 S.PDiag(diag)
5029 << SourceType << T << E->getSourceRange()
5030 << SourceRange(CContext));
5031 return;
5032 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005033 S.Diag(E->getExprLoc(), diag)
5034 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5035}
5036
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005037/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00005038static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00005039 SourceLocation CContext, unsigned diag,
5040 bool pruneControlFlow = false) {
5041 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00005042}
5043
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005044/// Diagnose an implicit cast from a literal expression. Does not warn when the
5045/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005046void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5047 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005048 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00005049 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005050 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00005051 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5052 T->hasUnsignedIntegerRepresentation());
5053 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00005054 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005055 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00005056 return;
5057
David Blaikiebe0ee872012-05-15 16:56:36 +00005058 SmallString<16> PrettySourceValue;
5059 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00005060 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00005061 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5062 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5063 else
David Blaikiede7e7b82012-05-15 17:18:27 +00005064 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00005065
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00005066 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00005067 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5068 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00005069}
5070
John McCall091f23f2010-11-09 22:22:12 +00005071std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5072 if (!Range.Width) return "0";
5073
5074 llvm::APSInt ValueInRange = Value;
5075 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00005076 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00005077 return ValueInRange.toString(10);
5078}
5079
Hans Wennborg88617a22012-08-28 15:44:30 +00005080static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5081 if (!isa<ImplicitCastExpr>(Ex))
5082 return false;
5083
5084 Expr *InnerE = Ex->IgnoreParenImpCasts();
5085 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5086 const Type *Source =
5087 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5088 if (Target->isDependentType())
5089 return false;
5090
5091 const BuiltinType *FloatCandidateBT =
5092 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5093 const Type *BoolCandidateType = ToBool ? Target : Source;
5094
5095 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5096 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5097}
5098
5099void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5100 SourceLocation CC) {
5101 unsigned NumArgs = TheCall->getNumArgs();
5102 for (unsigned i = 0; i < NumArgs; ++i) {
5103 Expr *CurrA = TheCall->getArg(i);
5104 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5105 continue;
5106
5107 bool IsSwapped = ((i > 0) &&
5108 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5109 IsSwapped |= ((i < (NumArgs - 1)) &&
5110 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5111 if (IsSwapped) {
5112 // Warn on this floating-point to bool conversion.
5113 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5114 CurrA->getType(), CC,
5115 diag::warn_impcast_floating_point_to_bool);
5116 }
5117 }
5118}
5119
John McCall323ed742010-05-06 08:58:33 +00005120void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005121 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00005122 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00005123
John McCall323ed742010-05-06 08:58:33 +00005124 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5125 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5126 if (Source == Target) return;
5127 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00005128
Chandler Carruth108f7562011-07-26 05:40:03 +00005129 // If the conversion context location is invalid don't complain. We also
5130 // don't want to emit a warning if the issue occurs from the expansion of
5131 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5132 // delay this check as long as possible. Once we detect we are in that
5133 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00005134 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00005135 return;
5136
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005137 // Diagnose implicit casts to bool.
5138 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5139 if (isa<StringLiteral>(E))
5140 // Warn on string literal to bool. Checks for string literals in logical
5141 // expressions, for instances, assert(0 && "error here"), is prevented
5142 // by a check in AnalyzeImplicitConversions().
5143 return DiagnoseImpCast(S, E, T, CC,
5144 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00005145 if (Source->isFunctionType()) {
5146 // Warn on function to bool. Checks free functions and static member
5147 // functions. Weakly imported functions are excluded from the check,
5148 // since it's common to test their value to check whether the linker
5149 // found a definition for them.
5150 ValueDecl *D = 0;
5151 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5152 D = R->getDecl();
5153 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5154 D = M->getMemberDecl();
5155 }
5156
5157 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00005158 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5159 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5160 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00005161 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5162 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5163 QualType ReturnType;
5164 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00005165 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00005166 if (!ReturnType.isNull()
5167 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5168 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5169 << FixItHint::CreateInsertion(
5170 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00005171 return;
5172 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00005173 }
5174 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005175 }
John McCall51313c32010-01-04 23:31:57 +00005176
5177 // Strip vector types.
5178 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005179 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005180 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005181 return;
John McCallb4eb64d2010-10-08 02:01:28 +00005182 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005183 }
Chris Lattnerb792b302011-06-14 04:51:15 +00005184
5185 // If the vector cast is cast between two vectors of the same size, it is
5186 // a bitcast, not a conversion.
5187 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5188 return;
John McCall51313c32010-01-04 23:31:57 +00005189
5190 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5191 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5192 }
5193
5194 // Strip complex types.
5195 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005196 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005197 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005198 return;
5199
John McCallb4eb64d2010-10-08 02:01:28 +00005200 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005201 }
John McCall51313c32010-01-04 23:31:57 +00005202
5203 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5204 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5205 }
5206
5207 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5208 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5209
5210 // If the source is floating point...
5211 if (SourceBT && SourceBT->isFloatingPoint()) {
5212 // ...and the target is floating point...
5213 if (TargetBT && TargetBT->isFloatingPoint()) {
5214 // ...then warn if we're dropping FP rank.
5215
5216 // Builtin FP kinds are ordered by increasing FP rank.
5217 if (SourceBT->getKind() > TargetBT->getKind()) {
5218 // Don't warn about float constants that are precisely
5219 // representable in the target type.
5220 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00005221 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00005222 // Value might be a float, a float vector, or a float complex.
5223 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00005224 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5225 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00005226 return;
5227 }
5228
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005229 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005230 return;
5231
John McCallb4eb64d2010-10-08 02:01:28 +00005232 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00005233 }
5234 return;
5235 }
5236
Ted Kremenekef9ff882011-03-10 20:03:42 +00005237 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00005238 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005239 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005240 return;
5241
Chandler Carrutha5b93322011-02-17 11:05:49 +00005242 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00005243 // We also want to warn on, e.g., "int i = -1.234"
5244 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5245 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5246 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5247
Chandler Carruthf65076e2011-04-10 08:36:24 +00005248 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5249 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005250 } else {
5251 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5252 }
5253 }
John McCall51313c32010-01-04 23:31:57 +00005254
Hans Wennborg88617a22012-08-28 15:44:30 +00005255 // If the target is bool, warn if expr is a function or method call.
5256 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5257 isa<CallExpr>(E)) {
5258 // Check last argument of function call to see if it is an
5259 // implicit cast from a type matching the type the result
5260 // is being cast to.
5261 CallExpr *CEx = cast<CallExpr>(E);
5262 unsigned NumArgs = CEx->getNumArgs();
5263 if (NumArgs > 0) {
5264 Expr *LastA = CEx->getArg(NumArgs - 1);
5265 Expr *InnerE = LastA->IgnoreParenImpCasts();
5266 const Type *InnerType =
5267 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5268 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5269 // Warn on this floating-point to bool conversion
5270 DiagnoseImpCast(S, E, T, CC,
5271 diag::warn_impcast_floating_point_to_bool);
5272 }
5273 }
5274 }
John McCall51313c32010-01-04 23:31:57 +00005275 return;
5276 }
5277
Richard Trieu1838ca52011-05-29 19:59:02 +00005278 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005279 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005280 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005281 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005282 SourceLocation Loc = E->getSourceRange().getBegin();
5283 if (Loc.isMacroID())
5284 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005285 if (!Loc.isMacroID() || CC.isMacroID())
5286 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5287 << T << clang::SourceRange(CC)
5288 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005289 }
5290
David Blaikieb26331b2012-06-19 21:19:06 +00005291 if (!Source->isIntegerType() || !Target->isIntegerType())
5292 return;
5293
David Blaikiebe0ee872012-05-15 16:56:36 +00005294 // TODO: remove this early return once the false positives for constant->bool
5295 // in templates, macros, etc, are reduced or removed.
5296 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5297 return;
5298
John McCall323ed742010-05-06 08:58:33 +00005299 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005300 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005301
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005302 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005303 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005304 // TODO: this should happen for bitfield stores, too.
5305 llvm::APSInt Value(32);
5306 if (E->isIntegerConstantExpr(Value, S.Context)) {
5307 if (S.SourceMgr.isInSystemMacro(CC))
5308 return;
5309
John McCall091f23f2010-11-09 22:22:12 +00005310 std::string PrettySourceValue = Value.toString(10);
5311 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005312
Ted Kremenek5e745da2011-10-22 02:37:33 +00005313 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5314 S.PDiag(diag::warn_impcast_integer_precision_constant)
5315 << PrettySourceValue << PrettyTargetValue
5316 << E->getType() << T << E->getSourceRange()
5317 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005318 return;
5319 }
5320
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005321 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5322 if (S.SourceMgr.isInSystemMacro(CC))
5323 return;
5324
David Blaikie37050842012-04-12 22:40:54 +00005325 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005326 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5327 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005328 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005329 }
5330
5331 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5332 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5333 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005334
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005335 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005336 return;
5337
John McCall323ed742010-05-06 08:58:33 +00005338 unsigned DiagID = diag::warn_impcast_integer_sign;
5339
5340 // Traditionally, gcc has warned about this under -Wsign-compare.
5341 // We also want to warn about it in -Wconversion.
5342 // So if -Wconversion is off, use a completely identical diagnostic
5343 // in the sign-compare group.
5344 // The conditional-checking code will
5345 if (ICContext) {
5346 DiagID = diag::warn_impcast_integer_sign_conditional;
5347 *ICContext = true;
5348 }
5349
John McCallb4eb64d2010-10-08 02:01:28 +00005350 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005351 }
5352
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005353 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005354 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5355 // type, to give us better diagnostics.
5356 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005357 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005358 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5359 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5360 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5361 SourceType = S.Context.getTypeDeclType(Enum);
5362 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5363 }
5364 }
5365
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005366 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5367 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005368 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5369 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005370 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005371 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005372 return;
5373
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005374 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005375 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005376 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005377
John McCall51313c32010-01-04 23:31:57 +00005378 return;
5379}
5380
David Blaikie9fb1ac52012-05-15 21:57:38 +00005381void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5382 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005383
5384void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005385 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005386 E = E->IgnoreParenImpCasts();
5387
5388 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005389 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005390
John McCallb4eb64d2010-10-08 02:01:28 +00005391 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005392 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005393 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005394 return;
5395}
5396
David Blaikie9fb1ac52012-05-15 21:57:38 +00005397void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5398 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005399 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005400
5401 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005402 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5403 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005404
5405 // If -Wconversion would have warned about either of the candidates
5406 // for a signedness conversion to the context type...
5407 if (!Suspicious) return;
5408
5409 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005410 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5411 CC))
John McCall323ed742010-05-06 08:58:33 +00005412 return;
5413
John McCall323ed742010-05-06 08:58:33 +00005414 // ...then check whether it would have warned about either of the
5415 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005416 if (E->getType() == T) return;
5417
5418 Suspicious = false;
5419 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5420 E->getType(), CC, &Suspicious);
5421 if (!Suspicious)
5422 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005423 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005424}
5425
5426/// AnalyzeImplicitConversions - Find and report any interesting
5427/// implicit conversions in the given expression. There are a couple
5428/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005429void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005430 QualType T = OrigE->getType();
5431 Expr *E = OrigE->IgnoreParenImpCasts();
5432
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005433 if (E->isTypeDependent() || E->isValueDependent())
5434 return;
5435
John McCall323ed742010-05-06 08:58:33 +00005436 // For conditional operators, we analyze the arguments as if they
5437 // were being fed directly into the output.
5438 if (isa<ConditionalOperator>(E)) {
5439 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005440 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005441 return;
5442 }
5443
Hans Wennborg88617a22012-08-28 15:44:30 +00005444 // Check implicit argument conversions for function calls.
5445 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5446 CheckImplicitArgumentConversions(S, Call, CC);
5447
John McCall323ed742010-05-06 08:58:33 +00005448 // Go ahead and check any implicit conversions we might have skipped.
5449 // The non-canonical typecheck is just an optimization;
5450 // CheckImplicitConversion will filter out dead implicit conversions.
5451 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005452 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005453
5454 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005455
5456 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005457 if (POE->getResultExpr())
5458 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005459 }
5460
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005461 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5462 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5463
John McCall323ed742010-05-06 08:58:33 +00005464 // Skip past explicit casts.
5465 if (isa<ExplicitCastExpr>(E)) {
5466 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005467 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005468 }
5469
John McCallbeb22aa2010-11-09 23:24:47 +00005470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5471 // Do a somewhat different check with comparison operators.
5472 if (BO->isComparisonOp())
5473 return AnalyzeComparison(S, BO);
5474
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005475 // And with simple assignments.
5476 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005477 return AnalyzeAssignment(S, BO);
5478 }
John McCall323ed742010-05-06 08:58:33 +00005479
5480 // These break the otherwise-useful invariant below. Fortunately,
5481 // we don't really need to recurse into them, because any internal
5482 // expressions should have been analyzed already when they were
5483 // built into statements.
5484 if (isa<StmtExpr>(E)) return;
5485
5486 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005487 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005488
5489 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005490 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005491 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5492 bool IsLogicalOperator = BO && BO->isLogicalOp();
5493 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005494 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005495 if (!ChildExpr)
5496 continue;
5497
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005498 if (IsLogicalOperator &&
5499 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5500 // Ignore checking string literals that are in logical operators.
5501 continue;
5502 AnalyzeImplicitConversions(S, ChildExpr, CC);
5503 }
John McCall323ed742010-05-06 08:58:33 +00005504}
5505
5506} // end anonymous namespace
5507
5508/// Diagnoses "dangerous" implicit conversions within the given
5509/// expression (which is a full expression). Implements -Wconversion
5510/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005511///
5512/// \param CC the "context" location of the implicit conversion, i.e.
5513/// the most location of the syntactic entity requiring the implicit
5514/// conversion
5515void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005516 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005517 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005518 return;
5519
5520 // Don't diagnose for value- or type-dependent expressions.
5521 if (E->isTypeDependent() || E->isValueDependent())
5522 return;
5523
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005524 // Check for array bounds violations in cases where the check isn't triggered
5525 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5526 // ArraySubscriptExpr is on the RHS of a variable initialization.
5527 CheckArrayAccess(E);
5528
John McCallb4eb64d2010-10-08 02:01:28 +00005529 // This is not the right CC for (e.g.) a variable initialization.
5530 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005531}
5532
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005533/// Diagnose when expression is an integer constant expression and its evaluation
5534/// results in integer overflow
5535void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005536 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005537 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5538 E->EvaluateForOverflow(Context, &Diags);
5539 }
5540}
5541
Richard Smith6c3af3d2013-01-17 01:17:56 +00005542namespace {
5543/// \brief Visitor for expressions which looks for unsequenced operations on the
5544/// same object.
5545class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005546 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5547
Richard Smith6c3af3d2013-01-17 01:17:56 +00005548 /// \brief A tree of sequenced regions within an expression. Two regions are
5549 /// unsequenced if one is an ancestor or a descendent of the other. When we
5550 /// finish processing an expression with sequencing, such as a comma
5551 /// expression, we fold its tree nodes into its parent, since they are
5552 /// unsequenced with respect to nodes we will visit later.
5553 class SequenceTree {
5554 struct Value {
5555 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5556 unsigned Parent : 31;
5557 bool Merged : 1;
5558 };
5559 llvm::SmallVector<Value, 8> Values;
5560
5561 public:
5562 /// \brief A region within an expression which may be sequenced with respect
5563 /// to some other region.
5564 class Seq {
5565 explicit Seq(unsigned N) : Index(N) {}
5566 unsigned Index;
5567 friend class SequenceTree;
5568 public:
5569 Seq() : Index(0) {}
5570 };
5571
5572 SequenceTree() { Values.push_back(Value(0)); }
5573 Seq root() const { return Seq(0); }
5574
5575 /// \brief Create a new sequence of operations, which is an unsequenced
5576 /// subset of \p Parent. This sequence of operations is sequenced with
5577 /// respect to other children of \p Parent.
5578 Seq allocate(Seq Parent) {
5579 Values.push_back(Value(Parent.Index));
5580 return Seq(Values.size() - 1);
5581 }
5582
5583 /// \brief Merge a sequence of operations into its parent.
5584 void merge(Seq S) {
5585 Values[S.Index].Merged = true;
5586 }
5587
5588 /// \brief Determine whether two operations are unsequenced. This operation
5589 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5590 /// should have been merged into its parent as appropriate.
5591 bool isUnsequenced(Seq Cur, Seq Old) {
5592 unsigned C = representative(Cur.Index);
5593 unsigned Target = representative(Old.Index);
5594 while (C >= Target) {
5595 if (C == Target)
5596 return true;
5597 C = Values[C].Parent;
5598 }
5599 return false;
5600 }
5601
5602 private:
5603 /// \brief Pick a representative for a sequence.
5604 unsigned representative(unsigned K) {
5605 if (Values[K].Merged)
5606 // Perform path compression as we go.
5607 return Values[K].Parent = representative(Values[K].Parent);
5608 return K;
5609 }
5610 };
5611
5612 /// An object for which we can track unsequenced uses.
5613 typedef NamedDecl *Object;
5614
5615 /// Different flavors of object usage which we track. We only track the
5616 /// least-sequenced usage of each kind.
5617 enum UsageKind {
5618 /// A read of an object. Multiple unsequenced reads are OK.
5619 UK_Use,
5620 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005621 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005622 UK_ModAsValue,
5623 /// A modification of an object which is not sequenced before the value
5624 /// computation of the expression, such as n++.
5625 UK_ModAsSideEffect,
5626
5627 UK_Count = UK_ModAsSideEffect + 1
5628 };
5629
5630 struct Usage {
5631 Usage() : Use(0), Seq() {}
5632 Expr *Use;
5633 SequenceTree::Seq Seq;
5634 };
5635
5636 struct UsageInfo {
5637 UsageInfo() : Diagnosed(false) {}
5638 Usage Uses[UK_Count];
5639 /// Have we issued a diagnostic for this variable already?
5640 bool Diagnosed;
5641 };
5642 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5643
5644 Sema &SemaRef;
5645 /// Sequenced regions within the expression.
5646 SequenceTree Tree;
5647 /// Declaration modifications and references which we have seen.
5648 UsageInfoMap UsageMap;
5649 /// The region we are currently within.
5650 SequenceTree::Seq Region;
5651 /// Filled in with declarations which were modified as a side-effect
5652 /// (that is, post-increment operations).
5653 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005654 /// Expressions to check later. We defer checking these to reduce
5655 /// stack usage.
5656 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005657
5658 /// RAII object wrapping the visitation of a sequenced subexpression of an
5659 /// expression. At the end of this process, the side-effects of the evaluation
5660 /// become sequenced with respect to the value computation of the result, so
5661 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5662 /// UK_ModAsValue.
5663 struct SequencedSubexpression {
5664 SequencedSubexpression(SequenceChecker &Self)
5665 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5666 Self.ModAsSideEffect = &ModAsSideEffect;
5667 }
5668 ~SequencedSubexpression() {
5669 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5670 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5671 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5672 Self.addUsage(U, ModAsSideEffect[I].first,
5673 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5674 }
5675 Self.ModAsSideEffect = OldModAsSideEffect;
5676 }
5677
5678 SequenceChecker &Self;
5679 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5680 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5681 };
5682
Richard Smith67470052013-06-20 22:21:56 +00005683 /// RAII object wrapping the visitation of a subexpression which we might
5684 /// choose to evaluate as a constant. If any subexpression is evaluated and
5685 /// found to be non-constant, this allows us to suppress the evaluation of
5686 /// the outer expression.
5687 class EvaluationTracker {
5688 public:
5689 EvaluationTracker(SequenceChecker &Self)
5690 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5691 Self.EvalTracker = this;
5692 }
5693 ~EvaluationTracker() {
5694 Self.EvalTracker = Prev;
5695 if (Prev)
5696 Prev->EvalOK &= EvalOK;
5697 }
5698
5699 bool evaluate(const Expr *E, bool &Result) {
5700 if (!EvalOK || E->isValueDependent())
5701 return false;
5702 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5703 return EvalOK;
5704 }
5705
5706 private:
5707 SequenceChecker &Self;
5708 EvaluationTracker *Prev;
5709 bool EvalOK;
5710 } *EvalTracker;
5711
Richard Smith6c3af3d2013-01-17 01:17:56 +00005712 /// \brief Find the object which is produced by the specified expression,
5713 /// if any.
5714 Object getObject(Expr *E, bool Mod) const {
5715 E = E->IgnoreParenCasts();
5716 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5717 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5718 return getObject(UO->getSubExpr(), Mod);
5719 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5720 if (BO->getOpcode() == BO_Comma)
5721 return getObject(BO->getRHS(), Mod);
5722 if (Mod && BO->isAssignmentOp())
5723 return getObject(BO->getLHS(), Mod);
5724 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5725 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5726 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5727 return ME->getMemberDecl();
5728 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5729 // FIXME: If this is a reference, map through to its value.
5730 return DRE->getDecl();
5731 return 0;
5732 }
5733
5734 /// \brief Note that an object was modified or used by an expression.
5735 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5736 Usage &U = UI.Uses[UK];
5737 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5738 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5739 ModAsSideEffect->push_back(std::make_pair(O, U));
5740 U.Use = Ref;
5741 U.Seq = Region;
5742 }
5743 }
5744 /// \brief Check whether a modification or use conflicts with a prior usage.
5745 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5746 bool IsModMod) {
5747 if (UI.Diagnosed)
5748 return;
5749
5750 const Usage &U = UI.Uses[OtherKind];
5751 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5752 return;
5753
5754 Expr *Mod = U.Use;
5755 Expr *ModOrUse = Ref;
5756 if (OtherKind == UK_Use)
5757 std::swap(Mod, ModOrUse);
5758
5759 SemaRef.Diag(Mod->getExprLoc(),
5760 IsModMod ? diag::warn_unsequenced_mod_mod
5761 : diag::warn_unsequenced_mod_use)
5762 << O << SourceRange(ModOrUse->getExprLoc());
5763 UI.Diagnosed = true;
5764 }
5765
5766 void notePreUse(Object O, Expr *Use) {
5767 UsageInfo &U = UsageMap[O];
5768 // Uses conflict with other modifications.
5769 checkUsage(O, U, Use, UK_ModAsValue, false);
5770 }
5771 void notePostUse(Object O, Expr *Use) {
5772 UsageInfo &U = UsageMap[O];
5773 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5774 addUsage(U, O, Use, UK_Use);
5775 }
5776
5777 void notePreMod(Object O, Expr *Mod) {
5778 UsageInfo &U = UsageMap[O];
5779 // Modifications conflict with other modifications and with uses.
5780 checkUsage(O, U, Mod, UK_ModAsValue, true);
5781 checkUsage(O, U, Mod, UK_Use, false);
5782 }
5783 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5784 UsageInfo &U = UsageMap[O];
5785 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5786 addUsage(U, O, Use, UK);
5787 }
5788
5789public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005790 SequenceChecker(Sema &S, Expr *E,
5791 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005792 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5793 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005794 Visit(E);
5795 }
5796
5797 void VisitStmt(Stmt *S) {
5798 // Skip all statements which aren't expressions for now.
5799 }
5800
5801 void VisitExpr(Expr *E) {
5802 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005803 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005804 }
5805
5806 void VisitCastExpr(CastExpr *E) {
5807 Object O = Object();
5808 if (E->getCastKind() == CK_LValueToRValue)
5809 O = getObject(E->getSubExpr(), false);
5810
5811 if (O)
5812 notePreUse(O, E);
5813 VisitExpr(E);
5814 if (O)
5815 notePostUse(O, E);
5816 }
5817
5818 void VisitBinComma(BinaryOperator *BO) {
5819 // C++11 [expr.comma]p1:
5820 // Every value computation and side effect associated with the left
5821 // expression is sequenced before every value computation and side
5822 // effect associated with the right expression.
5823 SequenceTree::Seq LHS = Tree.allocate(Region);
5824 SequenceTree::Seq RHS = Tree.allocate(Region);
5825 SequenceTree::Seq OldRegion = Region;
5826
5827 {
5828 SequencedSubexpression SeqLHS(*this);
5829 Region = LHS;
5830 Visit(BO->getLHS());
5831 }
5832
5833 Region = RHS;
5834 Visit(BO->getRHS());
5835
5836 Region = OldRegion;
5837
5838 // Forget that LHS and RHS are sequenced. They are both unsequenced
5839 // with respect to other stuff.
5840 Tree.merge(LHS);
5841 Tree.merge(RHS);
5842 }
5843
5844 void VisitBinAssign(BinaryOperator *BO) {
5845 // The modification is sequenced after the value computation of the LHS
5846 // and RHS, so check it before inspecting the operands and update the
5847 // map afterwards.
5848 Object O = getObject(BO->getLHS(), true);
5849 if (!O)
5850 return VisitExpr(BO);
5851
5852 notePreMod(O, BO);
5853
5854 // C++11 [expr.ass]p7:
5855 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5856 // only once.
5857 //
5858 // Therefore, for a compound assignment operator, O is considered used
5859 // everywhere except within the evaluation of E1 itself.
5860 if (isa<CompoundAssignOperator>(BO))
5861 notePreUse(O, BO);
5862
5863 Visit(BO->getLHS());
5864
5865 if (isa<CompoundAssignOperator>(BO))
5866 notePostUse(O, BO);
5867
5868 Visit(BO->getRHS());
5869
Richard Smith418dd3e2013-06-26 23:16:51 +00005870 // C++11 [expr.ass]p1:
5871 // the assignment is sequenced [...] before the value computation of the
5872 // assignment expression.
5873 // C11 6.5.16/3 has no such rule.
5874 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5875 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005876 }
5877 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5878 VisitBinAssign(CAO);
5879 }
5880
5881 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5882 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5883 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5884 Object O = getObject(UO->getSubExpr(), true);
5885 if (!O)
5886 return VisitExpr(UO);
5887
5888 notePreMod(O, UO);
5889 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005890 // C++11 [expr.pre.incr]p1:
5891 // the expression ++x is equivalent to x+=1
5892 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5893 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005894 }
5895
5896 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5897 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5898 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5899 Object O = getObject(UO->getSubExpr(), true);
5900 if (!O)
5901 return VisitExpr(UO);
5902
5903 notePreMod(O, UO);
5904 Visit(UO->getSubExpr());
5905 notePostMod(O, UO, UK_ModAsSideEffect);
5906 }
5907
5908 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5909 void VisitBinLOr(BinaryOperator *BO) {
5910 // The side-effects of the LHS of an '&&' are sequenced before the
5911 // value computation of the RHS, and hence before the value computation
5912 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5913 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005914 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005915 {
5916 SequencedSubexpression Sequenced(*this);
5917 Visit(BO->getLHS());
5918 }
5919
5920 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005921 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005922 if (!Result)
5923 Visit(BO->getRHS());
5924 } else {
5925 // Check for unsequenced operations in the RHS, treating it as an
5926 // entirely separate evaluation.
5927 //
5928 // FIXME: If there are operations in the RHS which are unsequenced
5929 // with respect to operations outside the RHS, and those operations
5930 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005931 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005932 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005933 }
5934 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005935 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005936 {
5937 SequencedSubexpression Sequenced(*this);
5938 Visit(BO->getLHS());
5939 }
5940
5941 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005942 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005943 if (Result)
5944 Visit(BO->getRHS());
5945 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005946 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005947 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005948 }
5949
5950 // Only visit the condition, unless we can be sure which subexpression will
5951 // be chosen.
5952 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005953 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005954 {
5955 SequencedSubexpression Sequenced(*this);
5956 Visit(CO->getCond());
5957 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005958
5959 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005960 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005961 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005962 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005963 WorkList.push_back(CO->getTrueExpr());
5964 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005965 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005966 }
5967
Richard Smith0c0b3902013-06-30 10:40:20 +00005968 void VisitCallExpr(CallExpr *CE) {
5969 // C++11 [intro.execution]p15:
5970 // When calling a function [...], every value computation and side effect
5971 // associated with any argument expression, or with the postfix expression
5972 // designating the called function, is sequenced before execution of every
5973 // expression or statement in the body of the function [and thus before
5974 // the value computation of its result].
5975 SequencedSubexpression Sequenced(*this);
5976 Base::VisitCallExpr(CE);
5977
5978 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5979 }
5980
Richard Smith6c3af3d2013-01-17 01:17:56 +00005981 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005982 // This is a call, so all subexpressions are sequenced before the result.
5983 SequencedSubexpression Sequenced(*this);
5984
Richard Smith6c3af3d2013-01-17 01:17:56 +00005985 if (!CCE->isListInitialization())
5986 return VisitExpr(CCE);
5987
5988 // In C++11, list initializations are sequenced.
5989 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5990 SequenceTree::Seq Parent = Region;
5991 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5992 E = CCE->arg_end();
5993 I != E; ++I) {
5994 Region = Tree.allocate(Parent);
5995 Elts.push_back(Region);
5996 Visit(*I);
5997 }
5998
5999 // Forget that the initializers are sequenced.
6000 Region = Parent;
6001 for (unsigned I = 0; I < Elts.size(); ++I)
6002 Tree.merge(Elts[I]);
6003 }
6004
6005 void VisitInitListExpr(InitListExpr *ILE) {
6006 if (!SemaRef.getLangOpts().CPlusPlus11)
6007 return VisitExpr(ILE);
6008
6009 // In C++11, list initializations are sequenced.
6010 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
6011 SequenceTree::Seq Parent = Region;
6012 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6013 Expr *E = ILE->getInit(I);
6014 if (!E) continue;
6015 Region = Tree.allocate(Parent);
6016 Elts.push_back(Region);
6017 Visit(E);
6018 }
6019
6020 // Forget that the initializers are sequenced.
6021 Region = Parent;
6022 for (unsigned I = 0; I < Elts.size(); ++I)
6023 Tree.merge(Elts[I]);
6024 }
6025};
6026}
6027
6028void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00006029 llvm::SmallVector<Expr*, 8> WorkList;
6030 WorkList.push_back(E);
6031 while (!WorkList.empty()) {
6032 Expr *Item = WorkList.back();
6033 WorkList.pop_back();
6034 SequenceChecker(*this, Item, WorkList);
6035 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00006036}
6037
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006038void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6039 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00006040 CheckImplicitConversions(E, CheckLoc);
6041 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006042 if (!IsConstexpr && !E->isValueDependent())
6043 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00006044}
6045
John McCall15d7d122010-11-11 03:21:53 +00006046void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6047 FieldDecl *BitField,
6048 Expr *Init) {
6049 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6050}
6051
Mike Stumpf8c49212010-01-21 03:59:47 +00006052/// CheckParmsForFunctionDef - Check that the parameters of the given
6053/// function are appropriate for the definition of a function. This
6054/// takes care of any checks that cannot be performed on the
6055/// declaration itself, e.g., that the types of each of the function
6056/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00006057bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6058 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00006059 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006060 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00006061 for (; P != PEnd; ++P) {
6062 ParmVarDecl *Param = *P;
6063
Mike Stumpf8c49212010-01-21 03:59:47 +00006064 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6065 // function declarator that is part of a function definition of
6066 // that function shall not have incomplete type.
6067 //
6068 // This is also C++ [dcl.fct]p6.
6069 if (!Param->isInvalidDecl() &&
6070 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00006071 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00006072 Param->setInvalidDecl();
6073 HasInvalidParm = true;
6074 }
6075
6076 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6077 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00006078 if (CheckParameterNames &&
6079 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00006080 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006081 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00006082 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00006083
6084 // C99 6.7.5.3p12:
6085 // If the function declarator is not part of a definition of that
6086 // function, parameters may have incomplete type and may use the [*]
6087 // notation in their sequences of declarator specifiers to specify
6088 // variable length array types.
6089 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006090 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00006091 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00006092 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00006093 // information is added for it.
6094 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006095 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00006096 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00006097 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00006098 }
Reid Kleckner9b601952013-06-21 12:45:15 +00006099
6100 // MSVC destroys objects passed by value in the callee. Therefore a
6101 // function definition which takes such a parameter must be able to call the
6102 // object's destructor.
6103 if (getLangOpts().CPlusPlus &&
6104 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6105 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6106 FinalizeVarWithDestructor(Param, RT);
6107 }
Mike Stumpf8c49212010-01-21 03:59:47 +00006108 }
6109
6110 return HasInvalidParm;
6111}
John McCallb7f4ffe2010-08-12 21:44:57 +00006112
6113/// CheckCastAlign - Implements -Wcast-align, which warns when a
6114/// pointer cast increases the alignment requirements.
6115void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6116 // This is actually a lot of work to potentially be doing on every
6117 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00006118 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6119 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00006120 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00006121 return;
6122
6123 // Ignore dependent types.
6124 if (T->isDependentType() || Op->getType()->isDependentType())
6125 return;
6126
6127 // Require that the destination be a pointer type.
6128 const PointerType *DestPtr = T->getAs<PointerType>();
6129 if (!DestPtr) return;
6130
6131 // If the destination has alignment 1, we're done.
6132 QualType DestPointee = DestPtr->getPointeeType();
6133 if (DestPointee->isIncompleteType()) return;
6134 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6135 if (DestAlign.isOne()) return;
6136
6137 // Require that the source be a pointer type.
6138 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6139 if (!SrcPtr) return;
6140 QualType SrcPointee = SrcPtr->getPointeeType();
6141
6142 // Whitelist casts from cv void*. We already implicitly
6143 // whitelisted casts to cv void*, since they have alignment 1.
6144 // Also whitelist casts involving incomplete types, which implicitly
6145 // includes 'void'.
6146 if (SrcPointee->isIncompleteType()) return;
6147
6148 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6149 if (SrcAlign >= DestAlign) return;
6150
6151 Diag(TRange.getBegin(), diag::warn_cast_align)
6152 << Op->getType() << T
6153 << static_cast<unsigned>(SrcAlign.getQuantity())
6154 << static_cast<unsigned>(DestAlign.getQuantity())
6155 << TRange << Op->getSourceRange();
6156}
6157
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006158static const Type* getElementType(const Expr *BaseExpr) {
6159 const Type* EltType = BaseExpr->getType().getTypePtr();
6160 if (EltType->isAnyPointerType())
6161 return EltType->getPointeeType().getTypePtr();
6162 else if (EltType->isArrayType())
6163 return EltType->getBaseElementTypeUnsafe();
6164 return EltType;
6165}
6166
Chandler Carruthc2684342011-08-05 09:10:50 +00006167/// \brief Check whether this array fits the idiom of a size-one tail padded
6168/// array member of a struct.
6169///
6170/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6171/// commonly used to emulate flexible arrays in C89 code.
6172static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6173 const NamedDecl *ND) {
6174 if (Size != 1 || !ND) return false;
6175
6176 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6177 if (!FD) return false;
6178
6179 // Don't consider sizes resulting from macro expansions or template argument
6180 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00006181
6182 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006183 while (TInfo) {
6184 TypeLoc TL = TInfo->getTypeLoc();
6185 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00006186 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6187 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006188 TInfo = TDL->getTypeSourceInfo();
6189 continue;
6190 }
David Blaikie39e6ab42013-02-18 22:06:02 +00006191 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6192 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00006193 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6194 return false;
6195 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00006196 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00006197 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006198
6199 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00006200 if (!RD) return false;
6201 if (RD->isUnion()) return false;
6202 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6203 if (!CRD->isStandardLayout()) return false;
6204 }
Chandler Carruthc2684342011-08-05 09:10:50 +00006205
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00006206 // See if this is the last field decl in the record.
6207 const Decl *D = FD;
6208 while ((D = D->getNextDeclInContext()))
6209 if (isa<FieldDecl>(D))
6210 return false;
6211 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00006212}
6213
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006214void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006215 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00006216 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00006217 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006218 if (IndexExpr->isValueDependent())
6219 return;
6220
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00006221 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006222 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00006223 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006224 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00006225 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00006226 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00006227
Chandler Carruth34064582011-02-17 20:55:08 +00006228 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006229 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00006230 return;
Richard Smith25b009a2011-12-16 19:31:14 +00006231 if (IndexNegated)
6232 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006233
Chandler Carruthba447122011-08-05 08:07:29 +00006234 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00006235 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6236 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00006237 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00006238 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00006239
Ted Kremenek9e060ca2011-02-23 23:06:04 +00006240 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00006241 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00006242 if (!size.isStrictlyPositive())
6243 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006244
6245 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00006246 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006247 // Make sure we're comparing apples to apples when comparing index to size
6248 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6249 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006250 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006251 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006252 if (ptrarith_typesize != array_typesize) {
6253 // There's a cast to a different size type involved
6254 uint64_t ratio = array_typesize / ptrarith_typesize;
6255 // TODO: Be smarter about handling cases where array_typesize is not a
6256 // multiple of ptrarith_typesize
6257 if (ptrarith_typesize * ratio == array_typesize)
6258 size *= llvm::APInt(size.getBitWidth(), ratio);
6259 }
6260 }
6261
Chandler Carruth34064582011-02-17 20:55:08 +00006262 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006263 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006264 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006265 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006266
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006267 // For array subscripting the index must be less than size, but for pointer
6268 // arithmetic also allow the index (offset) to be equal to size since
6269 // computing the next address after the end of the array is legal and
6270 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006271 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006272 return;
6273
6274 // Also don't warn for arrays of size 1 which are members of some
6275 // structure. These are often used to approximate flexible arrays in C89
6276 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006277 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006278 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006279
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006280 // Suppress the warning if the subscript expression (as identified by the
6281 // ']' location) and the index expression are both from macro expansions
6282 // within a system header.
6283 if (ASE) {
6284 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6285 ASE->getRBracketLoc());
6286 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6287 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6288 IndexExpr->getLocStart());
6289 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6290 return;
6291 }
6292 }
6293
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006294 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006295 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006296 DiagID = diag::warn_array_index_exceeds_bounds;
6297
6298 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6299 PDiag(DiagID) << index.toString(10, true)
6300 << size.toString(10, true)
6301 << (unsigned)size.getLimitedValue(~0U)
6302 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006303 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006304 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006305 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006306 DiagID = diag::warn_ptr_arith_precedes_bounds;
6307 if (index.isNegative()) index = -index;
6308 }
6309
6310 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6311 PDiag(DiagID) << index.toString(10, true)
6312 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006313 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006314
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006315 if (!ND) {
6316 // Try harder to find a NamedDecl to point at in the note.
6317 while (const ArraySubscriptExpr *ASE =
6318 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6319 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6320 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6321 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6322 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6323 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6324 }
6325
Chandler Carruth35001ca2011-02-17 21:10:52 +00006326 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006327 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6328 PDiag(diag::note_array_index_out_of_bounds)
6329 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006330}
6331
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006332void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006333 int AllowOnePastEnd = 0;
6334 while (expr) {
6335 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006336 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006337 case Stmt::ArraySubscriptExprClass: {
6338 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006339 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006340 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006341 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006342 }
6343 case Stmt::UnaryOperatorClass: {
6344 // Only unwrap the * and & unary operators
6345 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6346 expr = UO->getSubExpr();
6347 switch (UO->getOpcode()) {
6348 case UO_AddrOf:
6349 AllowOnePastEnd++;
6350 break;
6351 case UO_Deref:
6352 AllowOnePastEnd--;
6353 break;
6354 default:
6355 return;
6356 }
6357 break;
6358 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006359 case Stmt::ConditionalOperatorClass: {
6360 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6361 if (const Expr *lhs = cond->getLHS())
6362 CheckArrayAccess(lhs);
6363 if (const Expr *rhs = cond->getRHS())
6364 CheckArrayAccess(rhs);
6365 return;
6366 }
6367 default:
6368 return;
6369 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006370 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006371}
John McCallf85e1932011-06-15 23:02:42 +00006372
6373//===--- CHECK: Objective-C retain cycles ----------------------------------//
6374
6375namespace {
6376 struct RetainCycleOwner {
6377 RetainCycleOwner() : Variable(0), Indirect(false) {}
6378 VarDecl *Variable;
6379 SourceRange Range;
6380 SourceLocation Loc;
6381 bool Indirect;
6382
6383 void setLocsFrom(Expr *e) {
6384 Loc = e->getExprLoc();
6385 Range = e->getSourceRange();
6386 }
6387 };
6388}
6389
6390/// Consider whether capturing the given variable can possibly lead to
6391/// a retain cycle.
6392static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006393 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006394 // lifetime. In MRR, it's captured strongly if the variable is
6395 // __block and has an appropriate type.
6396 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6397 return false;
6398
6399 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006400 if (ref)
6401 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006402 return true;
6403}
6404
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006405static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006406 while (true) {
6407 e = e->IgnoreParens();
6408 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6409 switch (cast->getCastKind()) {
6410 case CK_BitCast:
6411 case CK_LValueBitCast:
6412 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006413 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006414 e = cast->getSubExpr();
6415 continue;
6416
John McCallf85e1932011-06-15 23:02:42 +00006417 default:
6418 return false;
6419 }
6420 }
6421
6422 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6423 ObjCIvarDecl *ivar = ref->getDecl();
6424 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6425 return false;
6426
6427 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006428 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006429 return false;
6430
6431 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6432 owner.Indirect = true;
6433 return true;
6434 }
6435
6436 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6437 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6438 if (!var) return false;
6439 return considerVariable(var, ref, owner);
6440 }
6441
John McCallf85e1932011-06-15 23:02:42 +00006442 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6443 if (member->isArrow()) return false;
6444
6445 // Don't count this as an indirect ownership.
6446 e = member->getBase();
6447 continue;
6448 }
6449
John McCall4b9c2d22011-11-06 09:01:30 +00006450 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6451 // Only pay attention to pseudo-objects on property references.
6452 ObjCPropertyRefExpr *pre
6453 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6454 ->IgnoreParens());
6455 if (!pre) return false;
6456 if (pre->isImplicitProperty()) return false;
6457 ObjCPropertyDecl *property = pre->getExplicitProperty();
6458 if (!property->isRetaining() &&
6459 !(property->getPropertyIvarDecl() &&
6460 property->getPropertyIvarDecl()->getType()
6461 .getObjCLifetime() == Qualifiers::OCL_Strong))
6462 return false;
6463
6464 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006465 if (pre->isSuperReceiver()) {
6466 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6467 if (!owner.Variable)
6468 return false;
6469 owner.Loc = pre->getLocation();
6470 owner.Range = pre->getSourceRange();
6471 return true;
6472 }
John McCall4b9c2d22011-11-06 09:01:30 +00006473 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6474 ->getSourceExpr());
6475 continue;
6476 }
6477
John McCallf85e1932011-06-15 23:02:42 +00006478 // Array ivars?
6479
6480 return false;
6481 }
6482}
6483
6484namespace {
6485 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6486 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6487 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6488 Variable(variable), Capturer(0) {}
6489
6490 VarDecl *Variable;
6491 Expr *Capturer;
6492
6493 void VisitDeclRefExpr(DeclRefExpr *ref) {
6494 if (ref->getDecl() == Variable && !Capturer)
6495 Capturer = ref;
6496 }
6497
John McCallf85e1932011-06-15 23:02:42 +00006498 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6499 if (Capturer) return;
6500 Visit(ref->getBase());
6501 if (Capturer && ref->isFreeIvar())
6502 Capturer = ref;
6503 }
6504
6505 void VisitBlockExpr(BlockExpr *block) {
6506 // Look inside nested blocks
6507 if (block->getBlockDecl()->capturesVariable(Variable))
6508 Visit(block->getBlockDecl()->getBody());
6509 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006510
6511 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6512 if (Capturer) return;
6513 if (OVE->getSourceExpr())
6514 Visit(OVE->getSourceExpr());
6515 }
John McCallf85e1932011-06-15 23:02:42 +00006516 };
6517}
6518
6519/// Check whether the given argument is a block which captures a
6520/// variable.
6521static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6522 assert(owner.Variable && owner.Loc.isValid());
6523
6524 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006525
6526 // Look through [^{...} copy] and Block_copy(^{...}).
6527 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6528 Selector Cmd = ME->getSelector();
6529 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6530 e = ME->getInstanceReceiver();
6531 if (!e)
6532 return 0;
6533 e = e->IgnoreParenCasts();
6534 }
6535 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6536 if (CE->getNumArgs() == 1) {
6537 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006538 if (Fn) {
6539 const IdentifierInfo *FnI = Fn->getIdentifier();
6540 if (FnI && FnI->isStr("_Block_copy")) {
6541 e = CE->getArg(0)->IgnoreParenCasts();
6542 }
6543 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006544 }
6545 }
6546
John McCallf85e1932011-06-15 23:02:42 +00006547 BlockExpr *block = dyn_cast<BlockExpr>(e);
6548 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6549 return 0;
6550
6551 FindCaptureVisitor visitor(S.Context, owner.Variable);
6552 visitor.Visit(block->getBlockDecl()->getBody());
6553 return visitor.Capturer;
6554}
6555
6556static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6557 RetainCycleOwner &owner) {
6558 assert(capturer);
6559 assert(owner.Variable && owner.Loc.isValid());
6560
6561 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6562 << owner.Variable << capturer->getSourceRange();
6563 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6564 << owner.Indirect << owner.Range;
6565}
6566
6567/// Check for a keyword selector that starts with the word 'add' or
6568/// 'set'.
6569static bool isSetterLikeSelector(Selector sel) {
6570 if (sel.isUnarySelector()) return false;
6571
Chris Lattner5f9e2722011-07-23 10:55:15 +00006572 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006573 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006574 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006575 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006576 else if (str.startswith("add")) {
6577 // Specially whitelist 'addOperationWithBlock:'.
6578 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6579 return false;
6580 str = str.substr(3);
6581 }
John McCallf85e1932011-06-15 23:02:42 +00006582 else
6583 return false;
6584
6585 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006586 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006587}
6588
6589/// Check a message send to see if it's likely to cause a retain cycle.
6590void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6591 // Only check instance methods whose selector looks like a setter.
6592 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6593 return;
6594
6595 // Try to find a variable that the receiver is strongly owned by.
6596 RetainCycleOwner owner;
6597 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006598 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006599 return;
6600 } else {
6601 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6602 owner.Variable = getCurMethodDecl()->getSelfDecl();
6603 owner.Loc = msg->getSuperLoc();
6604 owner.Range = msg->getSuperLoc();
6605 }
6606
6607 // Check whether the receiver is captured by any of the arguments.
6608 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6609 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6610 return diagnoseRetainCycle(*this, capturer, owner);
6611}
6612
6613/// Check a property assign to see if it's likely to cause a retain cycle.
6614void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6615 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006616 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006617 return;
6618
6619 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6620 diagnoseRetainCycle(*this, capturer, owner);
6621}
6622
Jordan Rosee10f4d32012-09-15 02:48:31 +00006623void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6624 RetainCycleOwner Owner;
6625 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6626 return;
6627
6628 // Because we don't have an expression for the variable, we have to set the
6629 // location explicitly here.
6630 Owner.Loc = Var->getLocation();
6631 Owner.Range = Var->getSourceRange();
6632
6633 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6634 diagnoseRetainCycle(*this, Capturer, Owner);
6635}
6636
Ted Kremenek9d084012012-12-21 08:04:28 +00006637static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6638 Expr *RHS, bool isProperty) {
6639 // Check if RHS is an Objective-C object literal, which also can get
6640 // immediately zapped in a weak reference. Note that we explicitly
6641 // allow ObjCStringLiterals, since those are designed to never really die.
6642 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006643
Ted Kremenekd3292c82012-12-21 22:46:35 +00006644 // This enum needs to match with the 'select' in
6645 // warn_objc_arc_literal_assign (off-by-1).
6646 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6647 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6648 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006649
6650 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006651 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006652 << (isProperty ? 0 : 1)
6653 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006654
6655 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006656}
6657
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006658static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6659 Qualifiers::ObjCLifetime LT,
6660 Expr *RHS, bool isProperty) {
6661 // Strip off any implicit cast added to get to the one ARC-specific.
6662 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6663 if (cast->getCastKind() == CK_ARCConsumeObject) {
6664 S.Diag(Loc, diag::warn_arc_retained_assign)
6665 << (LT == Qualifiers::OCL_ExplicitNone)
6666 << (isProperty ? 0 : 1)
6667 << RHS->getSourceRange();
6668 return true;
6669 }
6670 RHS = cast->getSubExpr();
6671 }
6672
6673 if (LT == Qualifiers::OCL_Weak &&
6674 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6675 return true;
6676
6677 return false;
6678}
6679
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006680bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6681 QualType LHS, Expr *RHS) {
6682 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6683
6684 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6685 return false;
6686
6687 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6688 return true;
6689
6690 return false;
6691}
6692
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006693void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6694 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006695 QualType LHSType;
6696 // PropertyRef on LHS type need be directly obtained from
6697 // its declaration as it has a PsuedoType.
6698 ObjCPropertyRefExpr *PRE
6699 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6700 if (PRE && !PRE->isImplicitProperty()) {
6701 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6702 if (PD)
6703 LHSType = PD->getType();
6704 }
6705
6706 if (LHSType.isNull())
6707 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006708
6709 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6710
6711 if (LT == Qualifiers::OCL_Weak) {
6712 DiagnosticsEngine::Level Level =
6713 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6714 if (Level != DiagnosticsEngine::Ignored)
6715 getCurFunction()->markSafeWeakUse(LHS);
6716 }
6717
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006718 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6719 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006720
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006721 // FIXME. Check for other life times.
6722 if (LT != Qualifiers::OCL_None)
6723 return;
6724
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006725 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006726 if (PRE->isImplicitProperty())
6727 return;
6728 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6729 if (!PD)
6730 return;
6731
Bill Wendlingad017fa2012-12-20 19:22:21 +00006732 unsigned Attributes = PD->getPropertyAttributes();
6733 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006734 // when 'assign' attribute was not explicitly specified
6735 // by user, ignore it and rely on property type itself
6736 // for lifetime info.
6737 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6738 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6739 LHSType->isObjCRetainableType())
6740 return;
6741
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006742 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006743 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006744 Diag(Loc, diag::warn_arc_retained_property_assign)
6745 << RHS->getSourceRange();
6746 return;
6747 }
6748 RHS = cast->getSubExpr();
6749 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006750 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006751 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006752 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6753 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006754 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006755 }
6756}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006757
6758//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6759
6760namespace {
6761bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6762 SourceLocation StmtLoc,
6763 const NullStmt *Body) {
6764 // Do not warn if the body is a macro that expands to nothing, e.g:
6765 //
6766 // #define CALL(x)
6767 // if (condition)
6768 // CALL(0);
6769 //
6770 if (Body->hasLeadingEmptyMacro())
6771 return false;
6772
6773 // Get line numbers of statement and body.
6774 bool StmtLineInvalid;
6775 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6776 &StmtLineInvalid);
6777 if (StmtLineInvalid)
6778 return false;
6779
6780 bool BodyLineInvalid;
6781 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6782 &BodyLineInvalid);
6783 if (BodyLineInvalid)
6784 return false;
6785
6786 // Warn if null statement and body are on the same line.
6787 if (StmtLine != BodyLine)
6788 return false;
6789
6790 return true;
6791}
6792} // Unnamed namespace
6793
6794void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6795 const Stmt *Body,
6796 unsigned DiagID) {
6797 // Since this is a syntactic check, don't emit diagnostic for template
6798 // instantiations, this just adds noise.
6799 if (CurrentInstantiationScope)
6800 return;
6801
6802 // The body should be a null statement.
6803 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6804 if (!NBody)
6805 return;
6806
6807 // Do the usual checks.
6808 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6809 return;
6810
6811 Diag(NBody->getSemiLoc(), DiagID);
6812 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6813}
6814
6815void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6816 const Stmt *PossibleBody) {
6817 assert(!CurrentInstantiationScope); // Ensured by caller
6818
6819 SourceLocation StmtLoc;
6820 const Stmt *Body;
6821 unsigned DiagID;
6822 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6823 StmtLoc = FS->getRParenLoc();
6824 Body = FS->getBody();
6825 DiagID = diag::warn_empty_for_body;
6826 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6827 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6828 Body = WS->getBody();
6829 DiagID = diag::warn_empty_while_body;
6830 } else
6831 return; // Neither `for' nor `while'.
6832
6833 // The body should be a null statement.
6834 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6835 if (!NBody)
6836 return;
6837
6838 // Skip expensive checks if diagnostic is disabled.
6839 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6840 DiagnosticsEngine::Ignored)
6841 return;
6842
6843 // Do the usual checks.
6844 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6845 return;
6846
6847 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6848 // noise level low, emit diagnostics only if for/while is followed by a
6849 // CompoundStmt, e.g.:
6850 // for (int i = 0; i < n; i++);
6851 // {
6852 // a(i);
6853 // }
6854 // or if for/while is followed by a statement with more indentation
6855 // than for/while itself:
6856 // for (int i = 0; i < n; i++);
6857 // a(i);
6858 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6859 if (!ProbableTypo) {
6860 bool BodyColInvalid;
6861 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6862 PossibleBody->getLocStart(),
6863 &BodyColInvalid);
6864 if (BodyColInvalid)
6865 return;
6866
6867 bool StmtColInvalid;
6868 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6869 S->getLocStart(),
6870 &StmtColInvalid);
6871 if (StmtColInvalid)
6872 return;
6873
6874 if (BodyCol > StmtCol)
6875 ProbableTypo = true;
6876 }
6877
6878 if (ProbableTypo) {
6879 Diag(NBody->getSemiLoc(), DiagID);
6880 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6881 }
6882}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006883
6884//===--- Layout compatibility ----------------------------------------------//
6885
6886namespace {
6887
6888bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6889
6890/// \brief Check if two enumeration types are layout-compatible.
6891bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6892 // C++11 [dcl.enum] p8:
6893 // Two enumeration types are layout-compatible if they have the same
6894 // underlying type.
6895 return ED1->isComplete() && ED2->isComplete() &&
6896 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6897}
6898
6899/// \brief Check if two fields are layout-compatible.
6900bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6901 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6902 return false;
6903
6904 if (Field1->isBitField() != Field2->isBitField())
6905 return false;
6906
6907 if (Field1->isBitField()) {
6908 // Make sure that the bit-fields are the same length.
6909 unsigned Bits1 = Field1->getBitWidthValue(C);
6910 unsigned Bits2 = Field2->getBitWidthValue(C);
6911
6912 if (Bits1 != Bits2)
6913 return false;
6914 }
6915
6916 return true;
6917}
6918
6919/// \brief Check if two standard-layout structs are layout-compatible.
6920/// (C++11 [class.mem] p17)
6921bool isLayoutCompatibleStruct(ASTContext &C,
6922 RecordDecl *RD1,
6923 RecordDecl *RD2) {
6924 // If both records are C++ classes, check that base classes match.
6925 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6926 // If one of records is a CXXRecordDecl we are in C++ mode,
6927 // thus the other one is a CXXRecordDecl, too.
6928 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6929 // Check number of base classes.
6930 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6931 return false;
6932
6933 // Check the base classes.
6934 for (CXXRecordDecl::base_class_const_iterator
6935 Base1 = D1CXX->bases_begin(),
6936 BaseEnd1 = D1CXX->bases_end(),
6937 Base2 = D2CXX->bases_begin();
6938 Base1 != BaseEnd1;
6939 ++Base1, ++Base2) {
6940 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6941 return false;
6942 }
6943 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6944 // If only RD2 is a C++ class, it should have zero base classes.
6945 if (D2CXX->getNumBases() > 0)
6946 return false;
6947 }
6948
6949 // Check the fields.
6950 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6951 Field2End = RD2->field_end(),
6952 Field1 = RD1->field_begin(),
6953 Field1End = RD1->field_end();
6954 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6955 if (!isLayoutCompatible(C, *Field1, *Field2))
6956 return false;
6957 }
6958 if (Field1 != Field1End || Field2 != Field2End)
6959 return false;
6960
6961 return true;
6962}
6963
6964/// \brief Check if two standard-layout unions are layout-compatible.
6965/// (C++11 [class.mem] p18)
6966bool isLayoutCompatibleUnion(ASTContext &C,
6967 RecordDecl *RD1,
6968 RecordDecl *RD2) {
6969 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6970 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6971 Field2End = RD2->field_end();
6972 Field2 != Field2End; ++Field2) {
6973 UnmatchedFields.insert(*Field2);
6974 }
6975
6976 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6977 Field1End = RD1->field_end();
6978 Field1 != Field1End; ++Field1) {
6979 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6980 I = UnmatchedFields.begin(),
6981 E = UnmatchedFields.end();
6982
6983 for ( ; I != E; ++I) {
6984 if (isLayoutCompatible(C, *Field1, *I)) {
6985 bool Result = UnmatchedFields.erase(*I);
6986 (void) Result;
6987 assert(Result);
6988 break;
6989 }
6990 }
6991 if (I == E)
6992 return false;
6993 }
6994
6995 return UnmatchedFields.empty();
6996}
6997
6998bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6999 if (RD1->isUnion() != RD2->isUnion())
7000 return false;
7001
7002 if (RD1->isUnion())
7003 return isLayoutCompatibleUnion(C, RD1, RD2);
7004 else
7005 return isLayoutCompatibleStruct(C, RD1, RD2);
7006}
7007
7008/// \brief Check if two types are layout-compatible in C++11 sense.
7009bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7010 if (T1.isNull() || T2.isNull())
7011 return false;
7012
7013 // C++11 [basic.types] p11:
7014 // If two types T1 and T2 are the same type, then T1 and T2 are
7015 // layout-compatible types.
7016 if (C.hasSameType(T1, T2))
7017 return true;
7018
7019 T1 = T1.getCanonicalType().getUnqualifiedType();
7020 T2 = T2.getCanonicalType().getUnqualifiedType();
7021
7022 const Type::TypeClass TC1 = T1->getTypeClass();
7023 const Type::TypeClass TC2 = T2->getTypeClass();
7024
7025 if (TC1 != TC2)
7026 return false;
7027
7028 if (TC1 == Type::Enum) {
7029 return isLayoutCompatible(C,
7030 cast<EnumType>(T1)->getDecl(),
7031 cast<EnumType>(T2)->getDecl());
7032 } else if (TC1 == Type::Record) {
7033 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7034 return false;
7035
7036 return isLayoutCompatible(C,
7037 cast<RecordType>(T1)->getDecl(),
7038 cast<RecordType>(T2)->getDecl());
7039 }
7040
7041 return false;
7042}
7043}
7044
7045//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7046
7047namespace {
7048/// \brief Given a type tag expression find the type tag itself.
7049///
7050/// \param TypeExpr Type tag expression, as it appears in user's code.
7051///
7052/// \param VD Declaration of an identifier that appears in a type tag.
7053///
7054/// \param MagicValue Type tag magic value.
7055bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7056 const ValueDecl **VD, uint64_t *MagicValue) {
7057 while(true) {
7058 if (!TypeExpr)
7059 return false;
7060
7061 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7062
7063 switch (TypeExpr->getStmtClass()) {
7064 case Stmt::UnaryOperatorClass: {
7065 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7066 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7067 TypeExpr = UO->getSubExpr();
7068 continue;
7069 }
7070 return false;
7071 }
7072
7073 case Stmt::DeclRefExprClass: {
7074 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7075 *VD = DRE->getDecl();
7076 return true;
7077 }
7078
7079 case Stmt::IntegerLiteralClass: {
7080 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7081 llvm::APInt MagicValueAPInt = IL->getValue();
7082 if (MagicValueAPInt.getActiveBits() <= 64) {
7083 *MagicValue = MagicValueAPInt.getZExtValue();
7084 return true;
7085 } else
7086 return false;
7087 }
7088
7089 case Stmt::BinaryConditionalOperatorClass:
7090 case Stmt::ConditionalOperatorClass: {
7091 const AbstractConditionalOperator *ACO =
7092 cast<AbstractConditionalOperator>(TypeExpr);
7093 bool Result;
7094 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7095 if (Result)
7096 TypeExpr = ACO->getTrueExpr();
7097 else
7098 TypeExpr = ACO->getFalseExpr();
7099 continue;
7100 }
7101 return false;
7102 }
7103
7104 case Stmt::BinaryOperatorClass: {
7105 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7106 if (BO->getOpcode() == BO_Comma) {
7107 TypeExpr = BO->getRHS();
7108 continue;
7109 }
7110 return false;
7111 }
7112
7113 default:
7114 return false;
7115 }
7116 }
7117}
7118
7119/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7120///
7121/// \param TypeExpr Expression that specifies a type tag.
7122///
7123/// \param MagicValues Registered magic values.
7124///
7125/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7126/// kind.
7127///
7128/// \param TypeInfo Information about the corresponding C type.
7129///
7130/// \returns true if the corresponding C type was found.
7131bool GetMatchingCType(
7132 const IdentifierInfo *ArgumentKind,
7133 const Expr *TypeExpr, const ASTContext &Ctx,
7134 const llvm::DenseMap<Sema::TypeTagMagicValue,
7135 Sema::TypeTagData> *MagicValues,
7136 bool &FoundWrongKind,
7137 Sema::TypeTagData &TypeInfo) {
7138 FoundWrongKind = false;
7139
7140 // Variable declaration that has type_tag_for_datatype attribute.
7141 const ValueDecl *VD = NULL;
7142
7143 uint64_t MagicValue;
7144
7145 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7146 return false;
7147
7148 if (VD) {
7149 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7150 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7151 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7152 I != E; ++I) {
7153 if (I->getArgumentKind() != ArgumentKind) {
7154 FoundWrongKind = true;
7155 return false;
7156 }
7157 TypeInfo.Type = I->getMatchingCType();
7158 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7159 TypeInfo.MustBeNull = I->getMustBeNull();
7160 return true;
7161 }
7162 return false;
7163 }
7164
7165 if (!MagicValues)
7166 return false;
7167
7168 llvm::DenseMap<Sema::TypeTagMagicValue,
7169 Sema::TypeTagData>::const_iterator I =
7170 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7171 if (I == MagicValues->end())
7172 return false;
7173
7174 TypeInfo = I->second;
7175 return true;
7176}
7177} // unnamed namespace
7178
7179void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7180 uint64_t MagicValue, QualType Type,
7181 bool LayoutCompatible,
7182 bool MustBeNull) {
7183 if (!TypeTagForDatatypeMagicValues)
7184 TypeTagForDatatypeMagicValues.reset(
7185 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7186
7187 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7188 (*TypeTagForDatatypeMagicValues)[Magic] =
7189 TypeTagData(Type, LayoutCompatible, MustBeNull);
7190}
7191
7192namespace {
7193bool IsSameCharType(QualType T1, QualType T2) {
7194 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7195 if (!BT1)
7196 return false;
7197
7198 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7199 if (!BT2)
7200 return false;
7201
7202 BuiltinType::Kind T1Kind = BT1->getKind();
7203 BuiltinType::Kind T2Kind = BT2->getKind();
7204
7205 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7206 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7207 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7208 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7209}
7210} // unnamed namespace
7211
7212void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7213 const Expr * const *ExprArgs) {
7214 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7215 bool IsPointerAttr = Attr->getIsPointer();
7216
7217 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7218 bool FoundWrongKind;
7219 TypeTagData TypeInfo;
7220 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7221 TypeTagForDatatypeMagicValues.get(),
7222 FoundWrongKind, TypeInfo)) {
7223 if (FoundWrongKind)
7224 Diag(TypeTagExpr->getExprLoc(),
7225 diag::warn_type_tag_for_datatype_wrong_kind)
7226 << TypeTagExpr->getSourceRange();
7227 return;
7228 }
7229
7230 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7231 if (IsPointerAttr) {
7232 // Skip implicit cast of pointer to `void *' (as a function argument).
7233 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00007234 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00007235 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00007236 ArgumentExpr = ICE->getSubExpr();
7237 }
7238 QualType ArgumentType = ArgumentExpr->getType();
7239
7240 // Passing a `void*' pointer shouldn't trigger a warning.
7241 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7242 return;
7243
7244 if (TypeInfo.MustBeNull) {
7245 // Type tag with matching void type requires a null pointer.
7246 if (!ArgumentExpr->isNullPointerConstant(Context,
7247 Expr::NPC_ValueDependentIsNotNull)) {
7248 Diag(ArgumentExpr->getExprLoc(),
7249 diag::warn_type_safety_null_pointer_required)
7250 << ArgumentKind->getName()
7251 << ArgumentExpr->getSourceRange()
7252 << TypeTagExpr->getSourceRange();
7253 }
7254 return;
7255 }
7256
7257 QualType RequiredType = TypeInfo.Type;
7258 if (IsPointerAttr)
7259 RequiredType = Context.getPointerType(RequiredType);
7260
7261 bool mismatch = false;
7262 if (!TypeInfo.LayoutCompatible) {
7263 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7264
7265 // C++11 [basic.fundamental] p1:
7266 // Plain char, signed char, and unsigned char are three distinct types.
7267 //
7268 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7269 // char' depending on the current char signedness mode.
7270 if (mismatch)
7271 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7272 RequiredType->getPointeeType())) ||
7273 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7274 mismatch = false;
7275 } else
7276 if (IsPointerAttr)
7277 mismatch = !isLayoutCompatible(Context,
7278 ArgumentType->getPointeeType(),
7279 RequiredType->getPointeeType());
7280 else
7281 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7282
7283 if (mismatch)
7284 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7285 << ArgumentType << ArgumentKind->getName()
7286 << TypeInfo.LayoutCompatible << RequiredType
7287 << ArgumentExpr->getSourceRange()
7288 << TypeTagExpr->getSourceRange();
7289}