blob: c0dd9fc46dd2b252810885c3b5b24bad167f5790 [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"
35#include "llvm/ADT/BitVector.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/SmallString.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000040#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000041using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000042using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000043
Chris Lattner60800082009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
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;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000309 case llvm::Triple::mips:
310 case llvm::Triple::mipsel:
311 case llvm::Triple::mips64:
312 case llvm::Triple::mips64el:
313 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
314 return ExprError();
315 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000316 default:
317 break;
318 }
319 }
320
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000321 return TheCallResult;
Nate Begeman26a31422010-06-08 02:47:44 +0000322}
323
Nate Begeman61eecf52010-06-14 05:21:25 +0000324// Get the valid immediate range for the specified NEON type code.
325static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilsonda95f732011-11-08 01:16:11 +0000326 NeonTypeFlags Type(t);
327 int IsQuad = Type.isQuad();
328 switch (Type.getEltType()) {
329 case NeonTypeFlags::Int8:
330 case NeonTypeFlags::Poly8:
331 return shift ? 7 : (8 << IsQuad) - 1;
332 case NeonTypeFlags::Int16:
333 case NeonTypeFlags::Poly16:
334 return shift ? 15 : (4 << IsQuad) - 1;
335 case NeonTypeFlags::Int32:
336 return shift ? 31 : (2 << IsQuad) - 1;
337 case NeonTypeFlags::Int64:
338 return shift ? 63 : (1 << IsQuad) - 1;
339 case NeonTypeFlags::Float16:
340 assert(!shift && "cannot shift float types!");
341 return (4 << IsQuad) - 1;
342 case NeonTypeFlags::Float32:
343 assert(!shift && "cannot shift float types!");
344 return (2 << IsQuad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000345 }
David Blaikie7530c032012-01-17 06:56:22 +0000346 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman61eecf52010-06-14 05:21:25 +0000347}
348
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000349/// getNeonEltType - Return the QualType corresponding to the elements of
350/// the vector type specified by the NeonTypeFlags. This is used to check
351/// the pointer arguments for Neon load/store intrinsics.
352static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
353 switch (Flags.getEltType()) {
354 case NeonTypeFlags::Int8:
355 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
356 case NeonTypeFlags::Int16:
357 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
358 case NeonTypeFlags::Int32:
359 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
360 case NeonTypeFlags::Int64:
361 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
362 case NeonTypeFlags::Poly8:
363 return Context.SignedCharTy;
364 case NeonTypeFlags::Poly16:
365 return Context.ShortTy;
366 case NeonTypeFlags::Float16:
367 return Context.UnsignedShortTy;
368 case NeonTypeFlags::Float32:
369 return Context.FloatTy;
370 }
David Blaikie7530c032012-01-17 06:56:22 +0000371 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000372}
373
Nate Begeman26a31422010-06-08 02:47:44 +0000374bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000375 llvm::APSInt Result;
376
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000377 uint64_t mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000378 unsigned TV = 0;
Bob Wilson46482552011-11-16 21:32:23 +0000379 int PtrArgNum = -1;
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000380 bool HasConstPtr = false;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000381 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000382#define GET_NEON_OVERLOAD_CHECK
383#include "clang/Basic/arm_neon.inc"
384#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000385 }
386
Nate Begeman0d15c532010-06-13 04:47:52 +0000387 // For NEON intrinsics which are overloaded on vector element type, validate
388 // the immediate which specifies which variant to emit.
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000389 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begeman0d15c532010-06-13 04:47:52 +0000390 if (mask) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000391 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begeman0d15c532010-06-13 04:47:52 +0000392 return true;
393
Bob Wilsonda95f732011-11-08 01:16:11 +0000394 TV = Result.getLimitedValue(64);
Richard Smithf8ee6bc2012-08-14 01:28:02 +0000395 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000396 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000397 << TheCall->getArg(ImmArg)->getSourceRange();
398 }
399
Bob Wilson46482552011-11-16 21:32:23 +0000400 if (PtrArgNum >= 0) {
Bob Wilson6f9f03e2011-11-08 05:04:11 +0000401 // Check that pointer arguments have the specified type.
Bob Wilson46482552011-11-16 21:32:23 +0000402 Expr *Arg = TheCall->getArg(PtrArgNum);
403 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
404 Arg = ICE->getSubExpr();
405 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
406 QualType RHSTy = RHS.get()->getType();
407 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
408 if (HasConstPtr)
409 EltTy = EltTy.withConst();
410 QualType LHSTy = Context.getPointerType(EltTy);
411 AssignConvertType ConvTy;
412 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
413 if (RHS.isInvalid())
414 return true;
415 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
416 RHS.get(), AA_Assigning))
417 return true;
Nate Begeman0d15c532010-06-13 04:47:52 +0000418 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000419
Nate Begeman0d15c532010-06-13 04:47:52 +0000420 // For NEON intrinsics which take an immediate value as part of the
421 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000422 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000423 switch (BuiltinID) {
424 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000425 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
426 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000427 case ARM::BI__builtin_arm_vcvtr_f:
428 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000429#define GET_NEON_IMMEDIATE_CHECK
430#include "clang/Basic/arm_neon.inc"
431#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000432 };
433
Douglas Gregor592a4232012-06-29 01:05:22 +0000434 // We can't check the value of a dependent argument.
435 if (TheCall->getArg(i)->isTypeDependent() ||
436 TheCall->getArg(i)->isValueDependent())
437 return false;
438
Nate Begeman61eecf52010-06-14 05:21:25 +0000439 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000440 if (SemaBuiltinConstantArg(TheCall, i, Result))
441 return true;
442
Nate Begeman61eecf52010-06-14 05:21:25 +0000443 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000444 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000445 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000446 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000447 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000448
Nate Begeman99c40bb2010-08-03 21:32:34 +0000449 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000450 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000451}
Daniel Dunbarde454282008-10-02 18:44:07 +0000452
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000453bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
454 unsigned i = 0, l = 0, u = 0;
455 switch (BuiltinID) {
456 default: return false;
457 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
458 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyanbe22cb82012-08-27 12:29:20 +0000459 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
460 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
461 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
462 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
463 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanfad0a322012-07-08 09:30:00 +0000464 };
465
466 // We can't check the value of a dependent argument.
467 if (TheCall->getArg(i)->isTypeDependent() ||
468 TheCall->getArg(i)->isValueDependent())
469 return false;
470
471 // Check that the immediate argument is actually a constant.
472 llvm::APSInt Result;
473 if (SemaBuiltinConstantArg(TheCall, i, Result))
474 return true;
475
476 // Range check against the upper/lower values for this instruction.
477 unsigned Val = Result.getZExtValue();
478 if (Val < l || Val > u)
479 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
480 << l << u << TheCall->getArg(i)->getSourceRange();
481
482 return false;
483}
484
Richard Smith831421f2012-06-25 20:30:08 +0000485/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
486/// parameter with the FormatAttr's correct format_idx and firstDataArg.
487/// Returns true when the format fits the function and the FormatStringInfo has
488/// been populated.
489bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
490 FormatStringInfo *FSI) {
491 FSI->HasVAListArg = Format->getFirstArg() == 0;
492 FSI->FormatIdx = Format->getFormatIdx() - 1;
493 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssond406bf02009-08-16 01:56:34 +0000494
Richard Smith831421f2012-06-25 20:30:08 +0000495 // The way the format attribute works in GCC, the implicit this argument
496 // of member functions is counted. However, it doesn't appear in our own
497 // lists, so decrement format_idx in that case.
498 if (IsCXXMember) {
499 if(FSI->FormatIdx == 0)
500 return false;
501 --FSI->FormatIdx;
502 if (FSI->FirstDataArg != 0)
503 --FSI->FirstDataArg;
504 }
505 return true;
506}
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Richard Smith831421f2012-06-25 20:30:08 +0000508/// Handles the checks for format strings, non-POD arguments to vararg
509/// functions, and NULL arguments passed to non-NULL parameters.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000510void Sema::checkCall(NamedDecl *FDecl,
511 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000512 unsigned NumProtoArgs,
513 bool IsMemberFunction,
514 SourceLocation Loc,
515 SourceRange Range,
516 VariadicCallType CallType) {
Jordan Rose66360e22012-10-02 01:49:54 +0000517 if (CurContext->isDependentContext())
518 return;
Daniel Dunbarde454282008-10-02 18:44:07 +0000519
Ted Kremenekc82faca2010-09-09 04:33:05 +0000520 // Printf and scanf checking.
Richard Smith831421f2012-06-25 20:30:08 +0000521 bool HandledFormatString = false;
Richard Trieu0538f0e2013-06-22 00:20:41 +0000522 if (FDecl)
523 for (specific_attr_iterator<FormatAttr>
524 I = FDecl->specific_attr_begin<FormatAttr>(),
525 E = FDecl->specific_attr_end<FormatAttr>(); I != E ; ++I)
526 if (CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc,
527 Range))
528 HandledFormatString = true;
Richard Smith831421f2012-06-25 20:30:08 +0000529
530 // Refuse POD arguments that weren't caught by the format string
531 // checks above.
532 if (!HandledFormatString && CallType != VariadicDoesNotApply)
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000533 for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000534 // Args[ArgIdx] can be null in malformed code.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000535 if (const Expr *Arg = Args[ArgIdx])
Ted Kremenek0234bfa2012-10-11 19:06:43 +0000536 variadicArgumentPODCheck(Arg, CallType);
537 }
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Richard Trieu0538f0e2013-06-22 00:20:41 +0000539 if (FDecl) {
540 for (specific_attr_iterator<NonNullAttr>
541 I = FDecl->specific_attr_begin<NonNullAttr>(),
542 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
543 CheckNonNullArguments(*I, Args.data(), Loc);
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000544
Richard Trieu0538f0e2013-06-22 00:20:41 +0000545 // Type safety checking.
546 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
547 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
548 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
549 i != e; ++i) {
550 CheckArgumentWithTypeTag(*i, Args.data());
551 }
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +0000552 }
Richard Smith831421f2012-06-25 20:30:08 +0000553}
554
555/// CheckConstructorCall - Check a constructor call for correctness and safety
556/// properties not enforced by the C type system.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000557void Sema::CheckConstructorCall(FunctionDecl *FDecl,
558 ArrayRef<const Expr *> Args,
Richard Smith831421f2012-06-25 20:30:08 +0000559 const FunctionProtoType *Proto,
560 SourceLocation Loc) {
561 VariadicCallType CallType =
562 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000563 checkCall(FDecl, Args, Proto->getNumArgs(),
Richard Smith831421f2012-06-25 20:30:08 +0000564 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
565}
566
567/// CheckFunctionCall - Check a direct function call for various correctness
568/// and safety properties not strictly enforced by the C type system.
569bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
570 const FunctionProtoType *Proto) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000571 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
572 isa<CXXMethodDecl>(FDecl);
573 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
574 IsMemberOperatorCall;
Richard Smith831421f2012-06-25 20:30:08 +0000575 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
576 TheCall->getCallee());
577 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Eli Friedman2edcde82012-10-11 00:30:58 +0000578 Expr** Args = TheCall->getArgs();
579 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmandf75b0c2012-10-11 00:34:15 +0000580 if (IsMemberOperatorCall) {
Eli Friedman2edcde82012-10-11 00:30:58 +0000581 // If this is a call to a member operator, hide the first argument
582 // from checkCall.
583 // FIXME: Our choice of AST representation here is less than ideal.
584 ++Args;
585 --NumArgs;
586 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000587 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
588 NumProtoArgs,
Richard Smith831421f2012-06-25 20:30:08 +0000589 IsMemberFunction, TheCall->getRParenLoc(),
590 TheCall->getCallee()->getSourceRange(), CallType);
591
592 IdentifierInfo *FnInfo = FDecl->getIdentifier();
593 // None of the checks below are needed for functions that don't have
594 // simple names (e.g., C++ conversion functions).
595 if (!FnInfo)
596 return false;
Sebastian Redl0eb23302009-01-19 00:08:26 +0000597
Anna Zaks0a151a12012-01-17 00:37:07 +0000598 unsigned CMId = FDecl->getMemoryFunctionKind();
599 if (CMId == 0)
Anna Zaksd9b859a2012-01-13 21:52:01 +0000600 return false;
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000601
Anna Zaksd9b859a2012-01-13 21:52:01 +0000602 // Handle memory setting and copying functions.
Anna Zaks0a151a12012-01-17 00:37:07 +0000603 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenekbd5da9d2011-08-18 20:55:45 +0000604 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaksc36bedc2012-02-01 19:08:57 +0000605 else if (CMId == Builtin::BIstrncat)
606 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaksd9b859a2012-01-13 21:52:01 +0000607 else
Anna Zaks0a151a12012-01-17 00:37:07 +0000608 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000609
Anders Carlssond406bf02009-08-16 01:56:34 +0000610 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000611}
612
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000613bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000614 ArrayRef<const Expr *> Args) {
Richard Smith831421f2012-06-25 20:30:08 +0000615 VariadicCallType CallType =
616 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000617
Dmitri Gribenko287f24d2013-05-05 19:42:09 +0000618 checkCall(Method, Args, Method->param_size(),
Richard Smith831421f2012-06-25 20:30:08 +0000619 /*IsMemberFunction=*/false,
620 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000621
622 return false;
623}
624
Richard Trieuf462b012013-06-20 21:03:13 +0000625bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
626 const FunctionProtoType *Proto) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000627 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
628 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000629 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000631 QualType Ty = V->getType();
Richard Trieuf462b012013-06-20 21:03:13 +0000632 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000633 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Richard Trieuf462b012013-06-20 21:03:13 +0000635 VariadicCallType CallType;
Richard Trieua4993772013-06-20 23:21:54 +0000636 if (!Proto || !Proto->isVariadic()) {
Richard Trieuf462b012013-06-20 21:03:13 +0000637 CallType = VariadicDoesNotApply;
638 } else if (Ty->isBlockPointerType()) {
639 CallType = VariadicBlock;
640 } else { // Ty->isFunctionPointerType()
641 CallType = VariadicFunction;
642 }
Richard Smith831421f2012-06-25 20:30:08 +0000643 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
Anders Carlssond406bf02009-08-16 01:56:34 +0000644
Dmitri Gribenko1c030e92013-01-13 20:46:02 +0000645 checkCall(NDecl,
646 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
647 TheCall->getNumArgs()),
Richard Smith831421f2012-06-25 20:30:08 +0000648 NumProtoArgs, /*IsMemberFunction=*/false,
649 TheCall->getRParenLoc(),
650 TheCall->getCallee()->getSourceRange(), CallType);
651
Anders Carlssond406bf02009-08-16 01:56:34 +0000652 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000653}
654
Richard Trieu0538f0e2013-06-22 00:20:41 +0000655/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
656/// such as function pointers returned from functions.
657bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
658 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
659 TheCall->getCallee());
660 unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
661
662 checkCall(/*FDecl=*/0,
663 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
664 TheCall->getNumArgs()),
665 NumProtoArgs, /*IsMemberFunction=*/false,
666 TheCall->getRParenLoc(),
667 TheCall->getCallee()->getSourceRange(), CallType);
668
669 return false;
670}
671
Richard Smithff34d402012-04-12 05:08:17 +0000672ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
673 AtomicExpr::AtomicOp Op) {
Eli Friedman276b0612011-10-11 02:20:01 +0000674 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
675 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedman276b0612011-10-11 02:20:01 +0000676
Richard Smithff34d402012-04-12 05:08:17 +0000677 // All these operations take one of the following forms:
678 enum {
679 // C __c11_atomic_init(A *, C)
680 Init,
681 // C __c11_atomic_load(A *, int)
682 Load,
683 // void __atomic_load(A *, CP, int)
684 Copy,
685 // C __c11_atomic_add(A *, M, int)
686 Arithmetic,
687 // C __atomic_exchange_n(A *, CP, int)
688 Xchg,
689 // void __atomic_exchange(A *, C *, CP, int)
690 GNUXchg,
691 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
692 C11CmpXchg,
693 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
694 GNUCmpXchg
695 } Form = Init;
696 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
697 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
698 // where:
699 // C is an appropriate type,
700 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
701 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
702 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
703 // the int parameters are for orderings.
Eli Friedman276b0612011-10-11 02:20:01 +0000704
Richard Smithff34d402012-04-12 05:08:17 +0000705 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
706 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
707 && "need to update code for modified C11 atomics");
708 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
709 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
710 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
711 Op == AtomicExpr::AO__atomic_store_n ||
712 Op == AtomicExpr::AO__atomic_exchange_n ||
713 Op == AtomicExpr::AO__atomic_compare_exchange_n;
714 bool IsAddSub = false;
715
716 switch (Op) {
717 case AtomicExpr::AO__c11_atomic_init:
718 Form = Init;
719 break;
720
721 case AtomicExpr::AO__c11_atomic_load:
722 case AtomicExpr::AO__atomic_load_n:
723 Form = Load;
724 break;
725
726 case AtomicExpr::AO__c11_atomic_store:
727 case AtomicExpr::AO__atomic_load:
728 case AtomicExpr::AO__atomic_store:
729 case AtomicExpr::AO__atomic_store_n:
730 Form = Copy;
731 break;
732
733 case AtomicExpr::AO__c11_atomic_fetch_add:
734 case AtomicExpr::AO__c11_atomic_fetch_sub:
735 case AtomicExpr::AO__atomic_fetch_add:
736 case AtomicExpr::AO__atomic_fetch_sub:
737 case AtomicExpr::AO__atomic_add_fetch:
738 case AtomicExpr::AO__atomic_sub_fetch:
739 IsAddSub = true;
740 // Fall through.
741 case AtomicExpr::AO__c11_atomic_fetch_and:
742 case AtomicExpr::AO__c11_atomic_fetch_or:
743 case AtomicExpr::AO__c11_atomic_fetch_xor:
744 case AtomicExpr::AO__atomic_fetch_and:
745 case AtomicExpr::AO__atomic_fetch_or:
746 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smith51b92402012-04-13 06:31:38 +0000747 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithff34d402012-04-12 05:08:17 +0000748 case AtomicExpr::AO__atomic_and_fetch:
749 case AtomicExpr::AO__atomic_or_fetch:
750 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smith51b92402012-04-13 06:31:38 +0000751 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithff34d402012-04-12 05:08:17 +0000752 Form = Arithmetic;
753 break;
754
755 case AtomicExpr::AO__c11_atomic_exchange:
756 case AtomicExpr::AO__atomic_exchange_n:
757 Form = Xchg;
758 break;
759
760 case AtomicExpr::AO__atomic_exchange:
761 Form = GNUXchg;
762 break;
763
764 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
765 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
766 Form = C11CmpXchg;
767 break;
768
769 case AtomicExpr::AO__atomic_compare_exchange:
770 case AtomicExpr::AO__atomic_compare_exchange_n:
771 Form = GNUCmpXchg;
772 break;
773 }
774
775 // Check we have the right number of arguments.
776 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedman276b0612011-10-11 02:20:01 +0000777 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithff34d402012-04-12 05:08:17 +0000778 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000779 << TheCall->getCallee()->getSourceRange();
780 return ExprError();
Richard Smithff34d402012-04-12 05:08:17 +0000781 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
782 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedman276b0612011-10-11 02:20:01 +0000783 diag::err_typecheck_call_too_many_args)
Richard Smithff34d402012-04-12 05:08:17 +0000784 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedman276b0612011-10-11 02:20:01 +0000785 << TheCall->getCallee()->getSourceRange();
786 return ExprError();
787 }
788
Richard Smithff34d402012-04-12 05:08:17 +0000789 // Inspect the first argument of the atomic operation.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000790 Expr *Ptr = TheCall->getArg(0);
Eli Friedman276b0612011-10-11 02:20:01 +0000791 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
792 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
793 if (!pointerType) {
Richard Smithff34d402012-04-12 05:08:17 +0000794 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedman276b0612011-10-11 02:20:01 +0000795 << Ptr->getType() << Ptr->getSourceRange();
796 return ExprError();
797 }
798
Richard Smithff34d402012-04-12 05:08:17 +0000799 // For a __c11 builtin, this should be a pointer to an _Atomic type.
800 QualType AtomTy = pointerType->getPointeeType(); // 'A'
801 QualType ValType = AtomTy; // 'C'
802 if (IsC11) {
803 if (!AtomTy->isAtomicType()) {
804 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
805 << Ptr->getType() << Ptr->getSourceRange();
806 return ExprError();
807 }
Richard Smithbc57b102012-09-15 06:09:58 +0000808 if (AtomTy.isConstQualified()) {
809 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
810 << Ptr->getType() << Ptr->getSourceRange();
811 return ExprError();
812 }
Richard Smithff34d402012-04-12 05:08:17 +0000813 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedman276b0612011-10-11 02:20:01 +0000814 }
Eli Friedman276b0612011-10-11 02:20:01 +0000815
Richard Smithff34d402012-04-12 05:08:17 +0000816 // For an arithmetic operation, the implied arithmetic must be well-formed.
817 if (Form == Arithmetic) {
818 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
819 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
820 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
821 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
822 return ExprError();
823 }
824 if (!IsAddSub && !ValType->isIntegerType()) {
825 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
826 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
827 return ExprError();
828 }
829 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
830 // For __atomic_*_n operations, the value type must be a scalar integral or
831 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedman276b0612011-10-11 02:20:01 +0000832 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithff34d402012-04-12 05:08:17 +0000833 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
834 return ExprError();
835 }
836
837 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context)) {
838 // For GNU atomics, require a trivially-copyable type. This is not part of
839 // the GNU atomics specification, but we enforce it for sanity.
840 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedman276b0612011-10-11 02:20:01 +0000841 << Ptr->getType() << Ptr->getSourceRange();
842 return ExprError();
843 }
844
Richard Smithff34d402012-04-12 05:08:17 +0000845 // FIXME: For any builtin other than a load, the ValType must not be
846 // const-qualified.
Eli Friedman276b0612011-10-11 02:20:01 +0000847
848 switch (ValType.getObjCLifetime()) {
849 case Qualifiers::OCL_None:
850 case Qualifiers::OCL_ExplicitNone:
851 // okay
852 break;
853
854 case Qualifiers::OCL_Weak:
855 case Qualifiers::OCL_Strong:
856 case Qualifiers::OCL_Autoreleasing:
Richard Smithff34d402012-04-12 05:08:17 +0000857 // FIXME: Can this happen? By this point, ValType should be known
858 // to be trivially copyable.
Eli Friedman276b0612011-10-11 02:20:01 +0000859 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
860 << ValType << Ptr->getSourceRange();
861 return ExprError();
862 }
863
864 QualType ResultType = ValType;
Richard Smithff34d402012-04-12 05:08:17 +0000865 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedman276b0612011-10-11 02:20:01 +0000866 ResultType = Context.VoidTy;
Richard Smithff34d402012-04-12 05:08:17 +0000867 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedman276b0612011-10-11 02:20:01 +0000868 ResultType = Context.BoolTy;
869
Richard Smithff34d402012-04-12 05:08:17 +0000870 // The type of a parameter passed 'by value'. In the GNU atomics, such
871 // arguments are actually passed as pointers.
872 QualType ByValType = ValType; // 'CP'
873 if (!IsC11 && !IsN)
874 ByValType = Ptr->getType();
875
Eli Friedman276b0612011-10-11 02:20:01 +0000876 // The first argument --- the pointer --- has a fixed type; we
877 // deduce the types of the rest of the arguments accordingly. Walk
878 // the remaining arguments, converting them to the deduced value type.
Richard Smithff34d402012-04-12 05:08:17 +0000879 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedman276b0612011-10-11 02:20:01 +0000880 QualType Ty;
Richard Smithff34d402012-04-12 05:08:17 +0000881 if (i < NumVals[Form] + 1) {
882 switch (i) {
883 case 1:
884 // The second argument is the non-atomic operand. For arithmetic, this
885 // is always passed by value, and for a compare_exchange it is always
886 // passed by address. For the rest, GNU uses by-address and C11 uses
887 // by-value.
888 assert(Form != Load);
889 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
890 Ty = ValType;
891 else if (Form == Copy || Form == Xchg)
892 Ty = ByValType;
893 else if (Form == Arithmetic)
894 Ty = Context.getPointerDiffType();
895 else
896 Ty = Context.getPointerType(ValType.getUnqualifiedType());
897 break;
898 case 2:
899 // The third argument to compare_exchange / GNU exchange is a
900 // (pointer to a) desired value.
901 Ty = ByValType;
902 break;
903 case 3:
904 // The fourth argument to GNU compare_exchange is a 'weak' flag.
905 Ty = Context.BoolTy;
906 break;
907 }
Eli Friedman276b0612011-10-11 02:20:01 +0000908 } else {
909 // The order(s) are always converted to int.
910 Ty = Context.IntTy;
911 }
Richard Smithff34d402012-04-12 05:08:17 +0000912
Eli Friedman276b0612011-10-11 02:20:01 +0000913 InitializedEntity Entity =
914 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithff34d402012-04-12 05:08:17 +0000915 ExprResult Arg = TheCall->getArg(i);
Eli Friedman276b0612011-10-11 02:20:01 +0000916 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
917 if (Arg.isInvalid())
918 return true;
919 TheCall->setArg(i, Arg.get());
920 }
921
Richard Smithff34d402012-04-12 05:08:17 +0000922 // Permute the arguments into a 'consistent' order.
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000923 SmallVector<Expr*, 5> SubExprs;
924 SubExprs.push_back(Ptr);
Richard Smithff34d402012-04-12 05:08:17 +0000925 switch (Form) {
926 case Init:
927 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnall7a7ee302012-01-16 17:27:18 +0000928 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000929 break;
930 case Load:
931 SubExprs.push_back(TheCall->getArg(1)); // Order
932 break;
933 case Copy:
934 case Arithmetic:
935 case Xchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000936 SubExprs.push_back(TheCall->getArg(2)); // Order
937 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithff34d402012-04-12 05:08:17 +0000938 break;
939 case GNUXchg:
940 // Note, AtomicExpr::getVal2() has a special case for this atomic.
941 SubExprs.push_back(TheCall->getArg(3)); // Order
942 SubExprs.push_back(TheCall->getArg(1)); // Val1
943 SubExprs.push_back(TheCall->getArg(2)); // Val2
944 break;
945 case C11CmpXchg:
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000946 SubExprs.push_back(TheCall->getArg(3)); // Order
947 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000948 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall2ebb98a2012-03-29 17:58:59 +0000949 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithff34d402012-04-12 05:08:17 +0000950 break;
951 case GNUCmpXchg:
952 SubExprs.push_back(TheCall->getArg(4)); // Order
953 SubExprs.push_back(TheCall->getArg(1)); // Val1
954 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
955 SubExprs.push_back(TheCall->getArg(2)); // Val2
956 SubExprs.push_back(TheCall->getArg(3)); // Weak
957 break;
Eli Friedman276b0612011-10-11 02:20:01 +0000958 }
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000959
960 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
961 SubExprs, ResultType, Op,
962 TheCall->getRParenLoc());
963
964 if ((Op == AtomicExpr::AO__c11_atomic_load ||
965 (Op == AtomicExpr::AO__c11_atomic_store)) &&
966 Context.AtomicUsesUnsupportedLibcall(AE))
967 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
968 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedmandfa64ba2011-10-14 22:48:56 +0000969
Fariborz Jahanian538bbe52013-05-28 17:37:39 +0000970 return Owned(AE);
Eli Friedman276b0612011-10-11 02:20:01 +0000971}
972
973
John McCall5f8d6042011-08-27 01:09:30 +0000974/// checkBuiltinArgument - Given a call to a builtin function, perform
975/// normal type-checking on the given argument, updating the call in
976/// place. This is useful when a builtin function requires custom
977/// type-checking for some of its arguments but not necessarily all of
978/// them.
979///
980/// Returns true on error.
981static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
982 FunctionDecl *Fn = E->getDirectCallee();
983 assert(Fn && "builtin call without direct callee!");
984
985 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
986 InitializedEntity Entity =
987 InitializedEntity::InitializeParameter(S.Context, Param);
988
989 ExprResult Arg = E->getArg(0);
990 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
991 if (Arg.isInvalid())
992 return true;
993
994 E->setArg(ArgIndex, Arg.take());
995 return false;
996}
997
Chris Lattner5caa3702009-05-08 06:58:22 +0000998/// SemaBuiltinAtomicOverloaded - We have a call to a function like
999/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1000/// type of its first argument. The main ActOnCallExpr routines have already
1001/// promoted the types of arguments because all of these calls are prototyped as
1002/// void(...).
1003///
1004/// This function goes through and does final semantic checking for these
1005/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +00001006ExprResult
1007Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001008 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +00001009 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1010 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1011
1012 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +00001013 if (TheCall->getNumArgs() < 1) {
1014 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1015 << 0 << 1 << TheCall->getNumArgs()
1016 << TheCall->getCallee()->getSourceRange();
1017 return ExprError();
1018 }
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Chris Lattner5caa3702009-05-08 06:58:22 +00001020 // Inspect the first argument of the atomic builtin. This should always be
1021 // a pointer type, whose element is an integral scalar or pointer type.
1022 // Because it is a pointer type, we don't have to worry about any implicit
1023 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +00001024 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +00001025 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman8c382062012-01-23 02:35:22 +00001026 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1027 if (FirstArgResult.isInvalid())
1028 return ExprError();
1029 FirstArg = FirstArgResult.take();
1030 TheCall->setArg(0, FirstArg);
1031
John McCallf85e1932011-06-15 23:02:42 +00001032 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1033 if (!pointerType) {
Chandler Carruthd2014572010-07-09 18:59:35 +00001034 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1035 << FirstArg->getType() << FirstArg->getSourceRange();
1036 return ExprError();
1037 }
Mike Stump1eb44332009-09-09 15:08:12 +00001038
John McCallf85e1932011-06-15 23:02:42 +00001039 QualType ValType = pointerType->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +00001040 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +00001041 !ValType->isBlockPointerType()) {
1042 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1043 << FirstArg->getType() << FirstArg->getSourceRange();
1044 return ExprError();
1045 }
Chris Lattner5caa3702009-05-08 06:58:22 +00001046
John McCallf85e1932011-06-15 23:02:42 +00001047 switch (ValType.getObjCLifetime()) {
1048 case Qualifiers::OCL_None:
1049 case Qualifiers::OCL_ExplicitNone:
1050 // okay
1051 break;
1052
1053 case Qualifiers::OCL_Weak:
1054 case Qualifiers::OCL_Strong:
1055 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00001056 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCallf85e1932011-06-15 23:02:42 +00001057 << ValType << FirstArg->getSourceRange();
1058 return ExprError();
1059 }
1060
John McCallb45ae252011-10-05 07:41:44 +00001061 // Strip any qualifiers off ValType.
1062 ValType = ValType.getUnqualifiedType();
1063
Chandler Carruth8d13d222010-07-18 20:54:12 +00001064 // The majority of builtins return a value, but a few have special return
1065 // types, so allow them to override appropriately below.
1066 QualType ResultType = ValType;
1067
Chris Lattner5caa3702009-05-08 06:58:22 +00001068 // We need to figure out which concrete builtin this maps onto. For example,
1069 // __sync_fetch_and_add with a 2 byte object turns into
1070 // __sync_fetch_and_add_2.
1071#define BUILTIN_ROW(x) \
1072 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1073 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
Chris Lattner5caa3702009-05-08 06:58:22 +00001075 static const unsigned BuiltinIndices[][5] = {
1076 BUILTIN_ROW(__sync_fetch_and_add),
1077 BUILTIN_ROW(__sync_fetch_and_sub),
1078 BUILTIN_ROW(__sync_fetch_and_or),
1079 BUILTIN_ROW(__sync_fetch_and_and),
1080 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +00001081
Chris Lattner5caa3702009-05-08 06:58:22 +00001082 BUILTIN_ROW(__sync_add_and_fetch),
1083 BUILTIN_ROW(__sync_sub_and_fetch),
1084 BUILTIN_ROW(__sync_and_and_fetch),
1085 BUILTIN_ROW(__sync_or_and_fetch),
1086 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner5caa3702009-05-08 06:58:22 +00001088 BUILTIN_ROW(__sync_val_compare_and_swap),
1089 BUILTIN_ROW(__sync_bool_compare_and_swap),
1090 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +00001091 BUILTIN_ROW(__sync_lock_release),
1092 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +00001093 };
Mike Stump1eb44332009-09-09 15:08:12 +00001094#undef BUILTIN_ROW
1095
Chris Lattner5caa3702009-05-08 06:58:22 +00001096 // Determine the index of the size.
1097 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +00001098 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +00001099 case 1: SizeIndex = 0; break;
1100 case 2: SizeIndex = 1; break;
1101 case 4: SizeIndex = 2; break;
1102 case 8: SizeIndex = 3; break;
1103 case 16: SizeIndex = 4; break;
1104 default:
Chandler Carruthd2014572010-07-09 18:59:35 +00001105 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1106 << FirstArg->getType() << FirstArg->getSourceRange();
1107 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +00001108 }
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Chris Lattner5caa3702009-05-08 06:58:22 +00001110 // Each of these builtins has one pointer argument, followed by some number of
1111 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1112 // that we ignore. Find out which row of BuiltinIndices to read from as well
1113 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +00001114 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +00001115 unsigned BuiltinIndex, NumFixed = 1;
1116 switch (BuiltinID) {
David Blaikieb219cfc2011-09-23 05:06:16 +00001117 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregora9766412011-11-28 16:30:08 +00001118 case Builtin::BI__sync_fetch_and_add:
1119 case Builtin::BI__sync_fetch_and_add_1:
1120 case Builtin::BI__sync_fetch_and_add_2:
1121 case Builtin::BI__sync_fetch_and_add_4:
1122 case Builtin::BI__sync_fetch_and_add_8:
1123 case Builtin::BI__sync_fetch_and_add_16:
1124 BuiltinIndex = 0;
1125 break;
1126
1127 case Builtin::BI__sync_fetch_and_sub:
1128 case Builtin::BI__sync_fetch_and_sub_1:
1129 case Builtin::BI__sync_fetch_and_sub_2:
1130 case Builtin::BI__sync_fetch_and_sub_4:
1131 case Builtin::BI__sync_fetch_and_sub_8:
1132 case Builtin::BI__sync_fetch_and_sub_16:
1133 BuiltinIndex = 1;
1134 break;
1135
1136 case Builtin::BI__sync_fetch_and_or:
1137 case Builtin::BI__sync_fetch_and_or_1:
1138 case Builtin::BI__sync_fetch_and_or_2:
1139 case Builtin::BI__sync_fetch_and_or_4:
1140 case Builtin::BI__sync_fetch_and_or_8:
1141 case Builtin::BI__sync_fetch_and_or_16:
1142 BuiltinIndex = 2;
1143 break;
1144
1145 case Builtin::BI__sync_fetch_and_and:
1146 case Builtin::BI__sync_fetch_and_and_1:
1147 case Builtin::BI__sync_fetch_and_and_2:
1148 case Builtin::BI__sync_fetch_and_and_4:
1149 case Builtin::BI__sync_fetch_and_and_8:
1150 case Builtin::BI__sync_fetch_and_and_16:
1151 BuiltinIndex = 3;
1152 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregora9766412011-11-28 16:30:08 +00001154 case Builtin::BI__sync_fetch_and_xor:
1155 case Builtin::BI__sync_fetch_and_xor_1:
1156 case Builtin::BI__sync_fetch_and_xor_2:
1157 case Builtin::BI__sync_fetch_and_xor_4:
1158 case Builtin::BI__sync_fetch_and_xor_8:
1159 case Builtin::BI__sync_fetch_and_xor_16:
1160 BuiltinIndex = 4;
1161 break;
1162
1163 case Builtin::BI__sync_add_and_fetch:
1164 case Builtin::BI__sync_add_and_fetch_1:
1165 case Builtin::BI__sync_add_and_fetch_2:
1166 case Builtin::BI__sync_add_and_fetch_4:
1167 case Builtin::BI__sync_add_and_fetch_8:
1168 case Builtin::BI__sync_add_and_fetch_16:
1169 BuiltinIndex = 5;
1170 break;
1171
1172 case Builtin::BI__sync_sub_and_fetch:
1173 case Builtin::BI__sync_sub_and_fetch_1:
1174 case Builtin::BI__sync_sub_and_fetch_2:
1175 case Builtin::BI__sync_sub_and_fetch_4:
1176 case Builtin::BI__sync_sub_and_fetch_8:
1177 case Builtin::BI__sync_sub_and_fetch_16:
1178 BuiltinIndex = 6;
1179 break;
1180
1181 case Builtin::BI__sync_and_and_fetch:
1182 case Builtin::BI__sync_and_and_fetch_1:
1183 case Builtin::BI__sync_and_and_fetch_2:
1184 case Builtin::BI__sync_and_and_fetch_4:
1185 case Builtin::BI__sync_and_and_fetch_8:
1186 case Builtin::BI__sync_and_and_fetch_16:
1187 BuiltinIndex = 7;
1188 break;
1189
1190 case Builtin::BI__sync_or_and_fetch:
1191 case Builtin::BI__sync_or_and_fetch_1:
1192 case Builtin::BI__sync_or_and_fetch_2:
1193 case Builtin::BI__sync_or_and_fetch_4:
1194 case Builtin::BI__sync_or_and_fetch_8:
1195 case Builtin::BI__sync_or_and_fetch_16:
1196 BuiltinIndex = 8;
1197 break;
1198
1199 case Builtin::BI__sync_xor_and_fetch:
1200 case Builtin::BI__sync_xor_and_fetch_1:
1201 case Builtin::BI__sync_xor_and_fetch_2:
1202 case Builtin::BI__sync_xor_and_fetch_4:
1203 case Builtin::BI__sync_xor_and_fetch_8:
1204 case Builtin::BI__sync_xor_and_fetch_16:
1205 BuiltinIndex = 9;
1206 break;
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Chris Lattner5caa3702009-05-08 06:58:22 +00001208 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001209 case Builtin::BI__sync_val_compare_and_swap_1:
1210 case Builtin::BI__sync_val_compare_and_swap_2:
1211 case Builtin::BI__sync_val_compare_and_swap_4:
1212 case Builtin::BI__sync_val_compare_and_swap_8:
1213 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001214 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +00001215 NumFixed = 2;
1216 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001217
Chris Lattner5caa3702009-05-08 06:58:22 +00001218 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregora9766412011-11-28 16:30:08 +00001219 case Builtin::BI__sync_bool_compare_and_swap_1:
1220 case Builtin::BI__sync_bool_compare_and_swap_2:
1221 case Builtin::BI__sync_bool_compare_and_swap_4:
1222 case Builtin::BI__sync_bool_compare_and_swap_8:
1223 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001224 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +00001225 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001226 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001227 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001228
1229 case Builtin::BI__sync_lock_test_and_set:
1230 case Builtin::BI__sync_lock_test_and_set_1:
1231 case Builtin::BI__sync_lock_test_and_set_2:
1232 case Builtin::BI__sync_lock_test_and_set_4:
1233 case Builtin::BI__sync_lock_test_and_set_8:
1234 case Builtin::BI__sync_lock_test_and_set_16:
1235 BuiltinIndex = 12;
1236 break;
1237
Chris Lattner5caa3702009-05-08 06:58:22 +00001238 case Builtin::BI__sync_lock_release:
Douglas Gregora9766412011-11-28 16:30:08 +00001239 case Builtin::BI__sync_lock_release_1:
1240 case Builtin::BI__sync_lock_release_2:
1241 case Builtin::BI__sync_lock_release_4:
1242 case Builtin::BI__sync_lock_release_8:
1243 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +00001244 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +00001245 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +00001246 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +00001247 break;
Douglas Gregora9766412011-11-28 16:30:08 +00001248
1249 case Builtin::BI__sync_swap:
1250 case Builtin::BI__sync_swap_1:
1251 case Builtin::BI__sync_swap_2:
1252 case Builtin::BI__sync_swap_4:
1253 case Builtin::BI__sync_swap_8:
1254 case Builtin::BI__sync_swap_16:
1255 BuiltinIndex = 14;
1256 break;
Chris Lattner5caa3702009-05-08 06:58:22 +00001257 }
Mike Stump1eb44332009-09-09 15:08:12 +00001258
Chris Lattner5caa3702009-05-08 06:58:22 +00001259 // Now that we know how many fixed arguments we expect, first check that we
1260 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +00001261 if (TheCall->getNumArgs() < 1+NumFixed) {
1262 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1263 << 0 << 1+NumFixed << TheCall->getNumArgs()
1264 << TheCall->getCallee()->getSourceRange();
1265 return ExprError();
1266 }
Mike Stump1eb44332009-09-09 15:08:12 +00001267
Chris Lattnere7ac0a92009-05-08 15:36:58 +00001268 // Get the decl for the concrete builtin from this, we can tell what the
1269 // concrete integer type we should convert to is.
1270 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1271 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara2ad11cd2012-09-22 09:05:22 +00001272 FunctionDecl *NewBuiltinDecl;
1273 if (NewBuiltinID == BuiltinID)
1274 NewBuiltinDecl = FDecl;
1275 else {
1276 // Perform builtin lookup to avoid redeclaring it.
1277 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1278 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1279 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1280 assert(Res.getFoundDecl());
1281 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1282 if (NewBuiltinDecl == 0)
1283 return ExprError();
1284 }
Chandler Carruthd2014572010-07-09 18:59:35 +00001285
John McCallf871d0c2010-08-07 06:22:56 +00001286 // The first argument --- the pointer --- has a fixed type; we
1287 // deduce the types of the rest of the arguments accordingly. Walk
1288 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +00001289 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +00001290 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Chris Lattner5caa3702009-05-08 06:58:22 +00001292 // GCC does an implicit conversion to the pointer or integer ValType. This
1293 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb45ae252011-10-05 07:41:44 +00001294 // Initialize the argument.
1295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1296 ValType, /*consume*/ false);
1297 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley429bb272011-04-08 18:41:53 +00001298 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +00001299 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Chris Lattner5caa3702009-05-08 06:58:22 +00001301 // Okay, we have something that *can* be converted to the right type. Check
1302 // to see if there is a potentially weird extension going on here. This can
1303 // happen when you do an atomic operation on something like an char* and
1304 // pass in 42. The 42 gets converted to char. This is even more strange
1305 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +00001306 // FIXME: Do this check.
John McCallb45ae252011-10-05 07:41:44 +00001307 TheCall->setArg(i+1, Arg.take());
Chris Lattner5caa3702009-05-08 06:58:22 +00001308 }
Mike Stump1eb44332009-09-09 15:08:12 +00001309
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001310 ASTContext& Context = this->getASTContext();
1311
1312 // Create a new DeclRefExpr to refer to the new decl.
1313 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1314 Context,
1315 DRE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001316 SourceLocation(),
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001317 NewBuiltinDecl,
John McCallf4b88a42012-03-10 09:33:50 +00001318 /*enclosing*/ false,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001319 DRE->getLocation(),
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001320 Context.BuiltinFnTy,
Douglas Gregorbbcb7ea2011-09-09 16:51:10 +00001321 DRE->getValueKind());
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Chris Lattner5caa3702009-05-08 06:58:22 +00001323 // Set the callee in the CallExpr.
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001324 // FIXME: This loses syntactic information.
1325 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1326 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1327 CK_BuiltinFnToFnPtr);
John Wiegley429bb272011-04-08 18:41:53 +00001328 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Chandler Carruthdb4325b2010-07-18 07:23:17 +00001330 // Change the result type of the call to match the original value type. This
1331 // is arbitrary, but the codegen for these builtins ins design to handle it
1332 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +00001333 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +00001334
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001335 return TheCallResult;
Chris Lattner5caa3702009-05-08 06:58:22 +00001336}
1337
Chris Lattner69039812009-02-18 06:01:06 +00001338/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +00001339/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +00001340/// Note: It might also make sense to do the UTF-16 conversion here (would
1341/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +00001342bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +00001343 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +00001344 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1345
Douglas Gregor5cee1192011-07-27 05:40:30 +00001346 if (!Literal || !Literal->isAscii()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001347 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1348 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001349 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +00001350 }
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001352 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001353 StringRef String = Literal->getString();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001354 unsigned NumBytes = String.size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001355 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divacky31ba6132012-09-06 15:59:27 +00001356 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian7da71022010-09-07 19:38:13 +00001357 UTF16 *ToPtr = &ToBuf[0];
1358
1359 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1360 &ToPtr, ToPtr + NumBytes,
1361 strictConversion);
1362 // Check for conversion failure.
1363 if (Result != conversionOK)
1364 Diag(Arg->getLocStart(),
1365 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1366 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +00001367 return false;
Chris Lattner59907c42007-08-10 20:18:51 +00001368}
1369
Chris Lattnerc27c6652007-12-20 00:05:45 +00001370/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1371/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +00001372bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1373 Expr *Fn = TheCall->getCallee();
1374 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +00001375 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001376 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001377 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1378 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +00001379 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001380 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +00001381 return true;
1382 }
Eli Friedman56f20ae2008-12-15 22:05:35 +00001383
1384 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +00001385 return Diag(TheCall->getLocEnd(),
1386 diag::err_typecheck_call_too_few_args_at_least)
1387 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +00001388 }
1389
John McCall5f8d6042011-08-27 01:09:30 +00001390 // Type-check the first argument normally.
1391 if (checkBuiltinArgument(*this, TheCall, 0))
1392 return true;
1393
Chris Lattnerc27c6652007-12-20 00:05:45 +00001394 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +00001395 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +00001396 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001397 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +00001398 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +00001399 else if (FunctionDecl *FD = getCurFunctionDecl())
1400 isVariadic = FD->isVariadic();
1401 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001402 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +00001403
Chris Lattnerc27c6652007-12-20 00:05:45 +00001404 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001405 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1406 return true;
1407 }
Mike Stump1eb44332009-09-09 15:08:12 +00001408
Chris Lattner30ce3442007-12-19 23:59:04 +00001409 // Verify that the second argument to the builtin is the last argument of the
1410 // current function or method.
1411 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +00001412 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Nico Weberb07d4482013-05-24 23:31:57 +00001414 // These are valid if SecondArgIsLastNamedArgument is false after the next
1415 // block.
1416 QualType Type;
1417 SourceLocation ParamLoc;
1418
Anders Carlsson88cf2262008-02-11 04:20:54 +00001419 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1420 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +00001421 // FIXME: This isn't correct for methods (results in bogus warning).
1422 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +00001423 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +00001424 if (CurBlock)
1425 LastArg = *(CurBlock->TheDecl->param_end()-1);
1426 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +00001427 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001428 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001429 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +00001430 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weberb07d4482013-05-24 23:31:57 +00001431
1432 Type = PV->getType();
1433 ParamLoc = PV->getLocation();
Chris Lattner30ce3442007-12-19 23:59:04 +00001434 }
1435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Chris Lattner30ce3442007-12-19 23:59:04 +00001437 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +00001438 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +00001439 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weberb07d4482013-05-24 23:31:57 +00001440 else if (Type->isReferenceType()) {
1441 Diag(Arg->getLocStart(),
1442 diag::warn_va_start_of_reference_type_is_undefined);
1443 Diag(ParamLoc, diag::note_parameter_type) << Type;
1444 }
1445
Chris Lattner30ce3442007-12-19 23:59:04 +00001446 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +00001447}
Chris Lattner30ce3442007-12-19 23:59:04 +00001448
Chris Lattner1b9a0792007-12-20 00:26:33 +00001449/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1450/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +00001451bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1452 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +00001453 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001454 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +00001455 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +00001456 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001457 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001458 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001459 << SourceRange(TheCall->getArg(2)->getLocStart(),
1460 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001461
John Wiegley429bb272011-04-08 18:41:53 +00001462 ExprResult OrigArg0 = TheCall->getArg(0);
1463 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +00001464
Chris Lattner1b9a0792007-12-20 00:26:33 +00001465 // Do standard promotions between the two arguments, returning their common
1466 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +00001467 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +00001468 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1469 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +00001470
1471 // Make sure any conversions are pushed back into the call; this is
1472 // type safe since unordered compare builtins are declared as "_Bool
1473 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +00001474 TheCall->setArg(0, OrigArg0.get());
1475 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +00001476
John Wiegley429bb272011-04-08 18:41:53 +00001477 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +00001478 return false;
1479
Chris Lattner1b9a0792007-12-20 00:26:33 +00001480 // If the common type isn't a real floating type, then the arguments were
1481 // invalid for this operation.
Eli Friedman860a3192012-06-16 02:19:17 +00001482 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +00001483 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001484 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +00001485 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1486 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00001487
Chris Lattner1b9a0792007-12-20 00:26:33 +00001488 return false;
1489}
1490
Benjamin Kramere771a7a2010-02-15 22:42:31 +00001491/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1492/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001493/// to check everything. We expect the last argument to be a floating point
1494/// value.
1495bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1496 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +00001497 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +00001498 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001499 if (TheCall->getNumArgs() > NumArgs)
1500 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001501 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001502 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001503 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001504 (*(TheCall->arg_end()-1))->getLocEnd());
1505
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +00001506 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +00001507
Eli Friedman9ac6f622009-08-31 20:06:00 +00001508 if (OrigArg->isTypeDependent())
1509 return false;
1510
Chris Lattner81368fb2010-05-06 05:50:07 +00001511 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +00001512 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +00001513 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +00001514 diag::err_typecheck_call_invalid_unary_fp)
1515 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001516
Chris Lattner81368fb2010-05-06 05:50:07 +00001517 // If this is an implicit conversion from float -> double, remove it.
1518 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1519 Expr *CastArg = Cast->getSubExpr();
1520 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1521 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1522 "promotion from float to double is the only expected cast here");
1523 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +00001524 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner81368fb2010-05-06 05:50:07 +00001525 }
1526 }
1527
Eli Friedman9ac6f622009-08-31 20:06:00 +00001528 return false;
1529}
1530
Eli Friedmand38617c2008-05-14 19:38:39 +00001531/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1532// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +00001533ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001534 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001535 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +00001536 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +00001537 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +00001538 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001539
Nate Begeman37b6a572010-06-08 00:16:34 +00001540 // Determine which of the following types of shufflevector we're checking:
1541 // 1) unary, vector mask: (lhs, mask)
1542 // 2) binary, vector mask: (lhs, rhs, mask)
1543 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1544 QualType resType = TheCall->getArg(0)->getType();
1545 unsigned numElements = 0;
1546
Douglas Gregorcde01732009-05-19 22:10:17 +00001547 if (!TheCall->getArg(0)->isTypeDependent() &&
1548 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +00001549 QualType LHSType = TheCall->getArg(0)->getType();
1550 QualType RHSType = TheCall->getArg(1)->getType();
1551
1552 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001553 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001554 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001555 TheCall->getArg(1)->getLocEnd());
1556 return ExprError();
1557 }
Nate Begeman37b6a572010-06-08 00:16:34 +00001558
1559 numElements = LHSType->getAs<VectorType>()->getNumElements();
1560 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +00001561
Nate Begeman37b6a572010-06-08 00:16:34 +00001562 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1563 // with mask. If so, verify that RHS is an integer vector type with the
1564 // same number of elts as lhs.
1565 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru4cb3d902013-07-06 08:00:09 +00001566 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +00001567 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1568 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1569 << SourceRange(TheCall->getArg(1)->getLocStart(),
1570 TheCall->getArg(1)->getLocEnd());
Nate Begeman37b6a572010-06-08 00:16:34 +00001571 }
1572 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001573 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +00001574 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +00001575 TheCall->getArg(1)->getLocEnd());
1576 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +00001577 } else if (numElements != numResElements) {
1578 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +00001579 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +00001580 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +00001581 }
Eli Friedmand38617c2008-05-14 19:38:39 +00001582 }
1583
1584 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +00001585 if (TheCall->getArg(i)->isTypeDependent() ||
1586 TheCall->getArg(i)->isValueDependent())
1587 continue;
1588
Nate Begeman37b6a572010-06-08 00:16:34 +00001589 llvm::APSInt Result(32);
1590 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1591 return ExprError(Diag(TheCall->getLocStart(),
1592 diag::err_shufflevector_nonconstant_argument)
1593 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +00001594
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001595 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001596 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001597 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +00001598 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +00001599 }
1600
Chris Lattner5f9e2722011-07-23 10:55:15 +00001601 SmallVector<Expr*, 32> exprs;
Eli Friedmand38617c2008-05-14 19:38:39 +00001602
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +00001603 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +00001604 exprs.push_back(TheCall->getArg(i));
1605 TheCall->setArg(i, 0);
1606 }
1607
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001608 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +00001609 TheCall->getCallee()->getLocStart(),
1610 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +00001611}
Chris Lattner30ce3442007-12-19 23:59:04 +00001612
Daniel Dunbar4493f792008-07-21 22:59:13 +00001613/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1614// This is declared to take (const void*, ...) and can take two
1615// optional constant int args.
1616bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001617 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001618
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001619 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +00001620 return Diag(TheCall->getLocEnd(),
1621 diag::err_typecheck_call_too_many_args_at_most)
1622 << 0 /*function call*/ << 3 << NumArgs
1623 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001624
1625 // Argument 0 is checked for us and the remaining arguments must be
1626 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001627 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +00001628 Expr *Arg = TheCall->getArg(i);
Douglas Gregor592a4232012-06-29 01:05:22 +00001629
1630 // We can't check the value of a dependent argument.
1631 if (Arg->isTypeDependent() || Arg->isValueDependent())
1632 continue;
1633
Eli Friedman9aef7262009-12-04 00:30:06 +00001634 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +00001635 if (SemaBuiltinConstantArg(TheCall, i, Result))
1636 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001637
Daniel Dunbar4493f792008-07-21 22:59:13 +00001638 // FIXME: gcc issues a warning and rewrites these to 0. These
1639 // seems especially odd for the third argument since the default
1640 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001641 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +00001642 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001643 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001644 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001645 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +00001646 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001647 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +00001648 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +00001649 }
1650 }
1651
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001652 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +00001653}
1654
Eric Christopher691ebc32010-04-17 02:26:23 +00001655/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1656/// TheCall is a constant expression.
1657bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1658 llvm::APSInt &Result) {
1659 Expr *Arg = TheCall->getArg(ArgNum);
1660 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1661 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1662
1663 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1664
1665 if (!Arg->isIntegerConstantExpr(Result, Context))
1666 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +00001667 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +00001668
Chris Lattner21fb98e2009-09-23 06:06:36 +00001669 return false;
1670}
1671
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001672/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1673/// int type). This simply type checks that type is one of the defined
1674/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00001675// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001676bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +00001677 llvm::APSInt Result;
Douglas Gregor592a4232012-06-29 01:05:22 +00001678
1679 // We can't check the value of a dependent argument.
1680 if (TheCall->getArg(1)->isTypeDependent() ||
1681 TheCall->getArg(1)->isValueDependent())
1682 return false;
1683
Eric Christopher691ebc32010-04-17 02:26:23 +00001684 // Check constant-ness first.
1685 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1686 return true;
1687
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001688 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001689 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001690 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1691 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +00001692 }
1693
1694 return false;
1695}
1696
Eli Friedman586d6a82009-05-03 06:04:26 +00001697/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +00001698/// This checks that val is a constant 1.
1699bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1700 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +00001701 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +00001702
Eric Christopher691ebc32010-04-17 02:26:23 +00001703 // TODO: This is less than ideal. Overload this to take a value.
1704 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1705 return true;
1706
1707 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +00001708 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1709 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1710
1711 return false;
1712}
1713
Richard Smith831421f2012-06-25 20:30:08 +00001714// Determine if an expression is a string literal or constant string.
1715// If this function returns false on the arguments to a function expecting a
1716// format string, we will usually need to emit a warning.
1717// True string literals are then checked by CheckFormatString.
1718Sema::StringLiteralCheckType
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001719Sema::checkFormatStringExpr(const Expr *E, ArrayRef<const Expr *> Args,
1720 bool HasVAListArg,
Richard Smith831421f2012-06-25 20:30:08 +00001721 unsigned format_idx, unsigned firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001722 FormatStringType Type, VariadicCallType CallType,
1723 bool inFunctionCall) {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001724 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +00001725 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith831421f2012-06-25 20:30:08 +00001726 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001727
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001728 E = E->IgnoreParenCasts();
Peter Collingbournef111d932011-04-15 00:35:48 +00001729
David Blaikiea73cdcb2012-02-10 21:07:25 +00001730 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1731 // Technically -Wformat-nonliteral does not warn about this case.
1732 // The behavior of printf and friends in this case is implementation
1733 // dependent. Ideally if the format string cannot be null then
1734 // it should have a 'nonnull' attribute in the function prototype.
Richard Smith831421f2012-06-25 20:30:08 +00001735 return SLCT_CheckedLiteral;
David Blaikiea73cdcb2012-02-10 21:07:25 +00001736
Ted Kremenekd30ef872009-01-12 23:09:09 +00001737 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +00001738 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +00001739 case Stmt::ConditionalOperatorClass: {
Richard Smith831421f2012-06-25 20:30:08 +00001740 // The expression is a literal if both sub-expressions were, and it was
1741 // completely checked only if both sub-expressions were checked.
1742 const AbstractConditionalOperator *C =
1743 cast<AbstractConditionalOperator>(E);
1744 StringLiteralCheckType Left =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001745 checkFormatStringExpr(C->getTrueExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001746 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001747 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001748 if (Left == SLCT_NotALiteral)
1749 return SLCT_NotALiteral;
1750 StringLiteralCheckType Right =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001751 checkFormatStringExpr(C->getFalseExpr(), Args,
Richard Smith831421f2012-06-25 20:30:08 +00001752 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001753 Type, CallType, inFunctionCall);
Richard Smith831421f2012-06-25 20:30:08 +00001754 return Left < Right ? Left : Right;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001755 }
1756
1757 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +00001758 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1759 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001760 }
1761
John McCall56ca35d2011-02-17 10:25:35 +00001762 case Stmt::OpaqueValueExprClass:
1763 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1764 E = src;
1765 goto tryAgain;
1766 }
Richard Smith831421f2012-06-25 20:30:08 +00001767 return SLCT_NotALiteral;
John McCall56ca35d2011-02-17 10:25:35 +00001768
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001769 case Stmt::PredefinedExprClass:
1770 // While __func__, etc., are technically not string literals, they
1771 // cannot contain format specifiers and thus are not a security
1772 // liability.
Richard Smith831421f2012-06-25 20:30:08 +00001773 return SLCT_UncheckedLiteral;
Ted Kremenekb43e8ad2011-02-24 23:03:04 +00001774
Ted Kremenek082d9362009-03-20 21:35:28 +00001775 case Stmt::DeclRefExprClass: {
1776 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Ted Kremenek082d9362009-03-20 21:35:28 +00001778 // As an exception, do not flag errors for variables binding to
1779 // const string literals.
1780 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1781 bool isConstant = false;
1782 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001783
Ted Kremenek082d9362009-03-20 21:35:28 +00001784 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1785 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001786 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001787 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +00001788 PT->getPointeeType().isConstant(Context);
Jean-Daniel Dupase98e5b52012-01-25 10:35:33 +00001789 } else if (T->isObjCObjectPointerType()) {
1790 // In ObjC, there is usually no "const ObjectPointer" type,
1791 // so don't check if the pointee type is constant.
1792 isConstant = T.isConstant(Context);
Ted Kremenek082d9362009-03-20 21:35:28 +00001793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Ted Kremenek082d9362009-03-20 21:35:28 +00001795 if (isConstant) {
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001796 if (const Expr *Init = VD->getAnyInitializer()) {
1797 // Look through initializers like const char c[] = { "foo" }
1798 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
1799 if (InitList->isStringLiteralInit())
1800 Init = InitList->getInit(0)->IgnoreParenImpCasts();
1801 }
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001802 return checkFormatStringExpr(Init, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001803 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001804 firstDataArg, Type, CallType,
Richard Smith831421f2012-06-25 20:30:08 +00001805 /*inFunctionCall*/false);
Matt Beaumont-Gaye2c60662012-05-11 22:10:59 +00001806 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001807 }
Mike Stump1eb44332009-09-09 15:08:12 +00001808
Anders Carlssond966a552009-06-28 19:55:58 +00001809 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1810 // special check to see if the format string is a function parameter
1811 // of the function calling the printf function. If the function
1812 // has an attribute indicating it is a printf-like function, then we
1813 // should suppress warnings concerning non-literals being used in a call
1814 // to a vprintf function. For example:
1815 //
1816 // void
1817 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1818 // va_list ap;
1819 // va_start(ap, fmt);
1820 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1821 // ...
1822 //
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001823 if (HasVAListArg) {
1824 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1825 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1826 int PVIndex = PV->getFunctionScopeIndex() + 1;
1827 for (specific_attr_iterator<FormatAttr>
1828 i = ND->specific_attr_begin<FormatAttr>(),
1829 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1830 FormatAttr *PVFormat = *i;
1831 // adjust for implicit parameter
1832 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1833 if (MD->isInstance())
1834 ++PVIndex;
1835 // We also check if the formats are compatible.
1836 // We can't pass a 'scanf' string to a 'printf' function.
1837 if (PVIndex == PVFormat->getFormatIdx() &&
1838 Type == GetFormatStringType(PVFormat))
Richard Smith831421f2012-06-25 20:30:08 +00001839 return SLCT_UncheckedLiteral;
Jean-Daniel Dupasf57c4132012-02-21 20:00:53 +00001840 }
1841 }
1842 }
1843 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001844 }
Mike Stump1eb44332009-09-09 15:08:12 +00001845
Richard Smith831421f2012-06-25 20:30:08 +00001846 return SLCT_NotALiteral;
Ted Kremenek082d9362009-03-20 21:35:28 +00001847 }
Ted Kremenekd30ef872009-01-12 23:09:09 +00001848
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001849 case Stmt::CallExprClass:
1850 case Stmt::CXXMemberCallExprClass: {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001851 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas52aabaf2012-02-07 19:01:42 +00001852 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1853 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1854 unsigned ArgIndex = FA->getFormatIdx();
1855 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1856 if (MD->isInstance())
1857 --ArgIndex;
1858 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001859
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001860 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001861 HasVAListArg, format_idx, firstDataArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001862 Type, CallType, inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001863 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1864 unsigned BuiltinID = FD->getBuiltinID();
1865 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
1866 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
1867 const Expr *Arg = CE->getArg(0);
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001868 return checkFormatStringExpr(Arg, Args,
Richard Smith831421f2012-06-25 20:30:08 +00001869 HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001870 firstDataArg, Type, CallType,
1871 inFunctionCall);
Jordan Rose50687312012-06-04 23:52:23 +00001872 }
Anders Carlsson8f031b32009-06-27 04:05:33 +00001873 }
1874 }
Mike Stump1eb44332009-09-09 15:08:12 +00001875
Richard Smith831421f2012-06-25 20:30:08 +00001876 return SLCT_NotALiteral;
Anders Carlsson8f031b32009-06-27 04:05:33 +00001877 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001878 case Stmt::ObjCStringLiteralClass:
1879 case Stmt::StringLiteralClass: {
1880 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001881
Ted Kremenek082d9362009-03-20 21:35:28 +00001882 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001883 StrE = ObjCFExpr->getString();
1884 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001885 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001886
Ted Kremenekd30ef872009-01-12 23:09:09 +00001887 if (StrE) {
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001888 CheckFormatString(StrE, E, Args, HasVAListArg, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001889 firstDataArg, Type, inFunctionCall, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001890 return SLCT_CheckedLiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001891 }
Mike Stump1eb44332009-09-09 15:08:12 +00001892
Richard Smith831421f2012-06-25 20:30:08 +00001893 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001894 }
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Ted Kremenek082d9362009-03-20 21:35:28 +00001896 default:
Richard Smith831421f2012-06-25 20:30:08 +00001897 return SLCT_NotALiteral;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001898 }
1899}
1900
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001901void
Mike Stump1eb44332009-09-09 15:08:12 +00001902Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001903 const Expr * const *ExprArgs,
1904 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001905 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1906 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001907 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001908 const Expr *ArgExpr = ExprArgs[*i];
Nick Lewycky3edf3872013-01-23 05:08:29 +00001909
1910 // As a special case, transparent unions initialized with zero are
1911 // considered null for the purposes of the nonnull attribute.
1912 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
1913 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1914 if (const CompoundLiteralExpr *CLE =
1915 dyn_cast<CompoundLiteralExpr>(ArgExpr))
1916 if (const InitListExpr *ILE =
1917 dyn_cast<InitListExpr>(CLE->getInitializer()))
1918 ArgExpr = ILE->getInit(0);
1919 }
1920
1921 bool Result;
1922 if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
Nick Lewycky909a70d2011-03-25 01:44:32 +00001923 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001924 }
1925}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001926
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001927Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1928 return llvm::StringSwitch<FormatStringType>(Format->getType())
1929 .Case("scanf", FST_Scanf)
1930 .Cases("printf", "printf0", FST_Printf)
1931 .Cases("NSString", "CFString", FST_NSString)
1932 .Case("strftime", FST_Strftime)
1933 .Case("strfmon", FST_Strfmon)
1934 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1935 .Default(FST_Unknown);
1936}
1937
Jordan Roseddcfbc92012-07-19 18:10:23 +00001938/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek826a3452010-07-16 02:11:22 +00001939/// functions) for correct use of format strings.
Richard Smith831421f2012-06-25 20:30:08 +00001940/// Returns true if a format string has been fully checked.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001941bool Sema::CheckFormatArguments(const FormatAttr *Format,
1942 ArrayRef<const Expr *> Args,
1943 bool IsCXXMember,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001944 VariadicCallType CallType,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001945 SourceLocation Loc, SourceRange Range) {
Richard Smith831421f2012-06-25 20:30:08 +00001946 FormatStringInfo FSI;
1947 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001948 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith831421f2012-06-25 20:30:08 +00001949 FSI.FirstDataArg, GetFormatStringType(Format),
Jordan Roseddcfbc92012-07-19 18:10:23 +00001950 CallType, Loc, Range);
Richard Smith831421f2012-06-25 20:30:08 +00001951 return false;
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001952}
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001953
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001954bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001955 bool HasVAListArg, unsigned format_idx,
1956 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001957 VariadicCallType CallType,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00001958 SourceLocation Loc, SourceRange Range) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001959 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001960 if (format_idx >= Args.size()) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001961 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith831421f2012-06-25 20:30:08 +00001962 return false;
Ted Kremenek71895b92007-08-14 17:39:48 +00001963 }
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001965 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Chris Lattner59907c42007-08-10 20:18:51 +00001967 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001968 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001969 // Dynamically generated format strings are difficult to
1970 // automatically vet at compile time. Requiring that format strings
1971 // are string literals: (1) permits the checking of format strings by
1972 // the compiler and thereby (2) can practically remove the source of
1973 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001974
Mike Stump1eb44332009-09-09 15:08:12 +00001975 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001976 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001977 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001978 // the same format string checking logic for both ObjC and C strings.
Richard Smith831421f2012-06-25 20:30:08 +00001979 StringLiteralCheckType CT =
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00001980 checkFormatStringExpr(OrigFormatExpr, Args, HasVAListArg,
Jordan Roseddcfbc92012-07-19 18:10:23 +00001981 format_idx, firstDataArg, Type, CallType);
Richard Smith831421f2012-06-25 20:30:08 +00001982 if (CT != SLCT_NotALiteral)
1983 // Literal format string found, check done!
1984 return CT == SLCT_CheckedLiteral;
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001985
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001986 // Strftime is particular as it always uses a single 'time' argument,
1987 // so it is safe to pass a non-literal string.
1988 if (Type == FST_Strftime)
Richard Smith831421f2012-06-25 20:30:08 +00001989 return false;
Jean-Daniel Dupas2837a2f2012-02-07 23:10:53 +00001990
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001991 // Do not emit diag when the string param is a macro expansion and the
1992 // format is either NSString or CFString. This is a hack to prevent
1993 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1994 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupasdc170202012-05-04 21:08:08 +00001995 if (Type == FST_NSString &&
1996 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith831421f2012-06-25 20:30:08 +00001997 return false;
Jean-Daniel Dupasce3aa392012-01-30 19:46:17 +00001998
Chris Lattner655f1412009-04-29 04:59:47 +00001999 // If there are no arguments specified, warn with -Wformat-security, otherwise
2000 // warn only with -Wformat-nonliteral.
Eli Friedman2243e782013-06-18 18:10:01 +00002001 if (Args.size() == firstDataArg)
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002002 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002003 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00002004 << OrigFormatExpr->getSourceRange();
2005 else
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002006 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00002007 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00002008 << OrigFormatExpr->getSourceRange();
Richard Smith831421f2012-06-25 20:30:08 +00002009 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00002010}
Ted Kremenek71895b92007-08-14 17:39:48 +00002011
Ted Kremeneke0e53132010-01-28 23:39:18 +00002012namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00002013class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2014protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00002015 Sema &S;
2016 const StringLiteral *FExpr;
2017 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00002018 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002019 const unsigned NumDataArgs;
Ted Kremeneke0e53132010-01-28 23:39:18 +00002020 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00002021 const bool HasVAListArg;
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002022 ArrayRef<const Expr *> Args;
Ted Kremenek0d277352010-01-29 01:06:55 +00002023 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002024 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00002025 bool usesPositionalArgs;
2026 bool atFirstArg;
Richard Trieu55733de2011-10-28 00:41:25 +00002027 bool inFunctionCall;
Jordan Roseddcfbc92012-07-19 18:10:23 +00002028 Sema::VariadicCallType CallType;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002029public:
Ted Kremenek826a3452010-07-16 02:11:22 +00002030 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00002031 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002032 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002033 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002034 unsigned formatIdx, bool inFunctionCall,
2035 Sema::VariadicCallType callType)
Ted Kremeneke0e53132010-01-28 23:39:18 +00002036 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose50687312012-06-04 23:52:23 +00002037 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2038 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002039 Args(Args), FormatIdx(formatIdx),
Richard Trieu55733de2011-10-28 00:41:25 +00002040 usesPositionalArgs(false), atFirstArg(true),
Jordan Roseddcfbc92012-07-19 18:10:23 +00002041 inFunctionCall(inFunctionCall), CallType(callType) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002042 CoveredArgs.resize(numDataArgs);
2043 CoveredArgs.reset();
2044 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002045
Ted Kremenek07d161f2010-01-29 01:50:07 +00002046 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002047
Ted Kremenek826a3452010-07-16 02:11:22 +00002048 void HandleIncompleteSpecifier(const char *startSpecifier,
2049 unsigned specifierLen);
Hans Wennborg76517422012-02-22 10:17:01 +00002050
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002051 void HandleInvalidLengthModifier(
2052 const analyze_format_string::FormatSpecifier &FS,
2053 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002054 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002055
Hans Wennborg76517422012-02-22 10:17:01 +00002056 void HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002057 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002058 const char *startSpecifier, unsigned specifierLen);
2059
2060 void HandleNonStandardConversionSpecifier(
2061 const analyze_format_string::ConversionSpecifier &CS,
2062 const char *startSpecifier, unsigned specifierLen);
2063
Hans Wennborgf8562642012-03-09 10:10:54 +00002064 virtual void HandlePosition(const char *startPos, unsigned posLen);
2065
Ted Kremenekefaff192010-02-27 01:41:03 +00002066 virtual void HandleInvalidPosition(const char *startSpecifier,
2067 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00002068 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00002069
2070 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2071
Ted Kremeneke0e53132010-01-28 23:39:18 +00002072 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002073
Richard Trieu55733de2011-10-28 00:41:25 +00002074 template <typename Range>
2075 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2076 const Expr *ArgumentExpr,
2077 PartialDiagnostic PDiag,
2078 SourceLocation StringLoc,
2079 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002080 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002081
Ted Kremenek826a3452010-07-16 02:11:22 +00002082protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002083 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2084 const char *startSpec,
2085 unsigned specifierLen,
2086 const char *csStart, unsigned csLen);
Richard Trieu55733de2011-10-28 00:41:25 +00002087
2088 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2089 const char *startSpec,
2090 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002091
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002092 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00002093 CharSourceRange getSpecifierRange(const char *startSpecifier,
2094 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002095 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002096
Ted Kremenek0d277352010-01-29 01:06:55 +00002097 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00002098
2099 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2100 const analyze_format_string::ConversionSpecifier &CS,
2101 const char *startSpecifier, unsigned specifierLen,
2102 unsigned argIndex);
Richard Trieu55733de2011-10-28 00:41:25 +00002103
2104 template <typename Range>
2105 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2106 bool IsStringLocation, Range StringRange,
Dmitri Gribenko55431692013-05-05 00:41:58 +00002107 ArrayRef<FixItHint> Fixit = None);
Richard Trieu55733de2011-10-28 00:41:25 +00002108
2109 void CheckPositionalAndNonpositionalArgs(
2110 const analyze_format_string::FormatSpecifier *FS);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002111};
2112}
2113
Ted Kremenek826a3452010-07-16 02:11:22 +00002114SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00002115 return OrigFormatExpr->getSourceRange();
2116}
2117
Ted Kremenek826a3452010-07-16 02:11:22 +00002118CharSourceRange CheckFormatHandler::
2119getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002120 SourceLocation Start = getLocationOfByte(startSpecifier);
2121 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2122
2123 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002124 End = End.getLocWithOffset(1);
Tom Care45f9b7e2010-06-21 21:21:01 +00002125
2126 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002127}
2128
Ted Kremenek826a3452010-07-16 02:11:22 +00002129SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002130 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00002131}
2132
Ted Kremenek826a3452010-07-16 02:11:22 +00002133void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2134 unsigned specifierLen){
Richard Trieu55733de2011-10-28 00:41:25 +00002135 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2136 getLocationOfByte(startSpecifier),
2137 /*IsStringLocation*/true,
2138 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek808015a2010-01-29 03:16:21 +00002139}
2140
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002141void CheckFormatHandler::HandleInvalidLengthModifier(
2142 const analyze_format_string::FormatSpecifier &FS,
2143 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose8be066e2012-09-08 04:00:12 +00002144 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002145 using namespace analyze_format_string;
2146
2147 const LengthModifier &LM = FS.getLengthModifier();
2148 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2149
2150 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002151 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002152 if (FixedLM) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002153 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002154 getLocationOfByte(LM.getStart()),
2155 /*IsStringLocation*/true,
2156 getSpecifierRange(startSpecifier, specifierLen));
2157
2158 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2159 << FixedLM->toString()
2160 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2161
2162 } else {
Jordan Rose8be066e2012-09-08 04:00:12 +00002163 FixItHint Hint;
2164 if (DiagID == diag::warn_format_nonsensical_length)
2165 Hint = FixItHint::CreateRemoval(LMRange);
2166
2167 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002168 getLocationOfByte(LM.getStart()),
2169 /*IsStringLocation*/true,
2170 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose8be066e2012-09-08 04:00:12 +00002171 Hint);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002172 }
2173}
2174
Hans Wennborg76517422012-02-22 10:17:01 +00002175void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose8be066e2012-09-08 04:00:12 +00002176 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborg76517422012-02-22 10:17:01 +00002177 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose8be066e2012-09-08 04:00:12 +00002178 using namespace analyze_format_string;
2179
2180 const LengthModifier &LM = FS.getLengthModifier();
2181 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2182
2183 // See if we know how to fix this length modifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002184 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose8be066e2012-09-08 04:00:12 +00002185 if (FixedLM) {
2186 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2187 << LM.toString() << 0,
2188 getLocationOfByte(LM.getStart()),
2189 /*IsStringLocation*/true,
2190 getSpecifierRange(startSpecifier, specifierLen));
2191
2192 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2193 << FixedLM->toString()
2194 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2195
2196 } else {
2197 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2198 << LM.toString() << 0,
2199 getLocationOfByte(LM.getStart()),
2200 /*IsStringLocation*/true,
2201 getSpecifierRange(startSpecifier, specifierLen));
2202 }
Hans Wennborg76517422012-02-22 10:17:01 +00002203}
2204
2205void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2206 const analyze_format_string::ConversionSpecifier &CS,
2207 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose670941c2012-09-13 02:11:15 +00002208 using namespace analyze_format_string;
2209
2210 // See if we know how to fix this conversion specifier.
David Blaikiedc84cd52013-02-20 22:23:23 +00002211 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose670941c2012-09-13 02:11:15 +00002212 if (FixedCS) {
2213 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2214 << CS.toString() << /*conversion specifier*/1,
2215 getLocationOfByte(CS.getStart()),
2216 /*IsStringLocation*/true,
2217 getSpecifierRange(startSpecifier, specifierLen));
2218
2219 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2220 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2221 << FixedCS->toString()
2222 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2223 } else {
2224 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2225 << CS.toString() << /*conversion specifier*/1,
2226 getLocationOfByte(CS.getStart()),
2227 /*IsStringLocation*/true,
2228 getSpecifierRange(startSpecifier, specifierLen));
2229 }
Hans Wennborg76517422012-02-22 10:17:01 +00002230}
2231
Hans Wennborgf8562642012-03-09 10:10:54 +00002232void CheckFormatHandler::HandlePosition(const char *startPos,
2233 unsigned posLen) {
2234 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2235 getLocationOfByte(startPos),
2236 /*IsStringLocation*/true,
2237 getSpecifierRange(startPos, posLen));
2238}
2239
Ted Kremenekefaff192010-02-27 01:41:03 +00002240void
Ted Kremenek826a3452010-07-16 02:11:22 +00002241CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2242 analyze_format_string::PositionContext p) {
Richard Trieu55733de2011-10-28 00:41:25 +00002243 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2244 << (unsigned) p,
2245 getLocationOfByte(startPos), /*IsStringLocation*/true,
2246 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002247}
2248
Ted Kremenek826a3452010-07-16 02:11:22 +00002249void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00002250 unsigned posLen) {
Richard Trieu55733de2011-10-28 00:41:25 +00002251 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2252 getLocationOfByte(startPos),
2253 /*IsStringLocation*/true,
2254 getSpecifierRange(startPos, posLen));
Ted Kremenekefaff192010-02-27 01:41:03 +00002255}
2256
Ted Kremenek826a3452010-07-16 02:11:22 +00002257void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose50687312012-06-04 23:52:23 +00002258 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0c069442011-03-15 21:18:48 +00002259 // The presence of a null character is likely an error.
Richard Trieu55733de2011-10-28 00:41:25 +00002260 EmitFormatDiagnostic(
2261 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2262 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2263 getFormatStringRange());
Ted Kremenek0c069442011-03-15 21:18:48 +00002264 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002265}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002266
Jordan Rose48716662012-07-19 18:10:08 +00002267// Note that this may return NULL if there was an error parsing or building
2268// one of the argument expressions.
Ted Kremenek826a3452010-07-16 02:11:22 +00002269const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002270 return Args[FirstDataArg + i];
Ted Kremenek826a3452010-07-16 02:11:22 +00002271}
2272
2273void CheckFormatHandler::DoneProcessing() {
2274 // Does the number of data arguments exceed the number of
2275 // format conversions in the format string?
2276 if (!HasVAListArg) {
2277 // Find any arguments that weren't covered.
2278 CoveredArgs.flip();
2279 signed notCoveredArg = CoveredArgs.find_first();
2280 if (notCoveredArg >= 0) {
2281 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose48716662012-07-19 18:10:08 +00002282 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2283 SourceLocation Loc = E->getLocStart();
2284 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2285 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2286 Loc, /*IsStringLocation*/false,
2287 getFormatStringRange());
2288 }
Bob Wilsonc03f2df2012-05-03 19:47:19 +00002289 }
Ted Kremenek826a3452010-07-16 02:11:22 +00002290 }
2291 }
2292}
2293
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002294bool
2295CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2296 SourceLocation Loc,
2297 const char *startSpec,
2298 unsigned specifierLen,
2299 const char *csStart,
2300 unsigned csLen) {
2301
2302 bool keepGoing = true;
2303 if (argIndex < NumDataArgs) {
2304 // Consider the argument coverered, even though the specifier doesn't
2305 // make sense.
2306 CoveredArgs.set(argIndex);
2307 }
2308 else {
2309 // If argIndex exceeds the number of data arguments we
2310 // don't issue a warning because that is just a cascade of warnings (and
2311 // they may have intended '%%' anyway). We don't want to continue processing
2312 // the format string after this point, however, as we will like just get
2313 // gibberish when trying to match arguments.
2314 keepGoing = false;
2315 }
2316
Richard Trieu55733de2011-10-28 00:41:25 +00002317 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2318 << StringRef(csStart, csLen),
2319 Loc, /*IsStringLocation*/true,
2320 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002321
2322 return keepGoing;
2323}
2324
Richard Trieu55733de2011-10-28 00:41:25 +00002325void
2326CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2327 const char *startSpec,
2328 unsigned specifierLen) {
2329 EmitFormatDiagnostic(
2330 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2331 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2332}
2333
Ted Kremenek666a1972010-07-26 19:45:42 +00002334bool
2335CheckFormatHandler::CheckNumArgs(
2336 const analyze_format_string::FormatSpecifier &FS,
2337 const analyze_format_string::ConversionSpecifier &CS,
2338 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2339
2340 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002341 PartialDiagnostic PDiag = FS.usesPositionalArg()
2342 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2343 << (argIndex+1) << NumDataArgs)
2344 : S.PDiag(diag::warn_printf_insufficient_data_args);
2345 EmitFormatDiagnostic(
2346 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2347 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek666a1972010-07-26 19:45:42 +00002348 return false;
2349 }
2350 return true;
2351}
2352
Richard Trieu55733de2011-10-28 00:41:25 +00002353template<typename Range>
2354void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2355 SourceLocation Loc,
2356 bool IsStringLocation,
2357 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002358 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00002359 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu55733de2011-10-28 00:41:25 +00002360 Loc, IsStringLocation, StringRange, FixIt);
2361}
2362
2363/// \brief If the format string is not within the funcion call, emit a note
2364/// so that the function call and string are in diagnostic messages.
2365///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002366/// \param InFunctionCall if true, the format string is within the function
Richard Trieu55733de2011-10-28 00:41:25 +00002367/// call and only one diagnostic message will be produced. Otherwise, an
2368/// extra note will be emitted pointing to location of the format string.
2369///
2370/// \param ArgumentExpr the expression that is passed as the format string
2371/// argument in the function call. Used for getting locations when two
2372/// diagnostics are emitted.
2373///
2374/// \param PDiag the callee should already have provided any strings for the
2375/// diagnostic message. This function only adds locations and fixits
2376/// to diagnostics.
2377///
2378/// \param Loc primary location for diagnostic. If two diagnostics are
2379/// required, one will be at Loc and a new SourceLocation will be created for
2380/// the other one.
2381///
2382/// \param IsStringLocation if true, Loc points to the format string should be
2383/// used for the note. Otherwise, Loc points to the argument list and will
2384/// be used with PDiag.
2385///
2386/// \param StringRange some or all of the string to highlight. This is
2387/// templated so it can accept either a CharSourceRange or a SourceRange.
2388///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00002389/// \param FixIt optional fix it hint for the format string.
Richard Trieu55733de2011-10-28 00:41:25 +00002390template<typename Range>
2391void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2392 const Expr *ArgumentExpr,
2393 PartialDiagnostic PDiag,
2394 SourceLocation Loc,
2395 bool IsStringLocation,
2396 Range StringRange,
Jordan Roseec087352012-09-05 22:56:26 +00002397 ArrayRef<FixItHint> FixIt) {
2398 if (InFunctionCall) {
2399 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2400 D << StringRange;
2401 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2402 I != E; ++I) {
2403 D << *I;
2404 }
2405 } else {
Richard Trieu55733de2011-10-28 00:41:25 +00002406 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2407 << ArgumentExpr->getSourceRange();
Jordan Roseec087352012-09-05 22:56:26 +00002408
2409 const Sema::SemaDiagnosticBuilder &Note =
2410 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2411 diag::note_format_string_defined);
2412
2413 Note << StringRange;
2414 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2415 I != E; ++I) {
2416 Note << *I;
2417 }
Richard Trieu55733de2011-10-28 00:41:25 +00002418 }
2419}
2420
Ted Kremenek826a3452010-07-16 02:11:22 +00002421//===--- CHECK: Printf format string checking ------------------------------===//
2422
2423namespace {
2424class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose50687312012-06-04 23:52:23 +00002425 bool ObjCContext;
Ted Kremenek826a3452010-07-16 02:11:22 +00002426public:
2427 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2428 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00002429 unsigned numDataArgs, bool isObjC,
Ted Kremenek826a3452010-07-16 02:11:22 +00002430 const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002431 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002432 unsigned formatIdx, bool inFunctionCall,
2433 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00002434 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00002435 numDataArgs, beg, hasVAListArg, Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00002436 formatIdx, inFunctionCall, CallType), ObjCContext(isObjC)
2437 {}
2438
Ted Kremenek826a3452010-07-16 02:11:22 +00002439
2440 bool HandleInvalidPrintfConversionSpecifier(
2441 const analyze_printf::PrintfSpecifier &FS,
2442 const char *startSpecifier,
2443 unsigned specifierLen);
2444
2445 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2446 const char *startSpecifier,
2447 unsigned specifierLen);
Richard Smith831421f2012-06-25 20:30:08 +00002448 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2449 const char *StartSpecifier,
2450 unsigned SpecifierLen,
2451 const Expr *E);
2452
Ted Kremenek826a3452010-07-16 02:11:22 +00002453 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2454 const char *startSpecifier, unsigned specifierLen);
2455 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2456 const analyze_printf::OptionalAmount &Amt,
2457 unsigned type,
2458 const char *startSpecifier, unsigned specifierLen);
2459 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2460 const analyze_printf::OptionalFlag &flag,
2461 const char *startSpecifier, unsigned specifierLen);
2462 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2463 const analyze_printf::OptionalFlag &ignoredFlag,
2464 const analyze_printf::OptionalFlag &flag,
2465 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgf3749f42012-08-07 08:11:26 +00002466 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith831421f2012-06-25 20:30:08 +00002467 const Expr *E, const CharSourceRange &CSR);
2468
Ted Kremenek826a3452010-07-16 02:11:22 +00002469};
2470}
2471
2472bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2473 const analyze_printf::PrintfSpecifier &FS,
2474 const char *startSpecifier,
2475 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002476 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002477 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00002478
Ted Kremenekc09b6a52010-07-19 21:25:57 +00002479 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2480 getLocationOfByte(CS.getStart()),
2481 startSpecifier, specifierLen,
2482 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00002483}
2484
Ted Kremenek826a3452010-07-16 02:11:22 +00002485bool CheckPrintfHandler::HandleAmount(
2486 const analyze_format_string::OptionalAmount &Amt,
2487 unsigned k, const char *startSpecifier,
2488 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002489
2490 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002491 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002492 unsigned argIndex = Amt.getArgIndex();
2493 if (argIndex >= NumDataArgs) {
Richard Trieu55733de2011-10-28 00:41:25 +00002494 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2495 << k,
2496 getLocationOfByte(Amt.getStart()),
2497 /*IsStringLocation*/true,
2498 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002499 // Don't do any more checking. We will just emit
2500 // spurious errors.
2501 return false;
2502 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002503
Ted Kremenek0d277352010-01-29 01:06:55 +00002504 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00002505 // Although not in conformance with C99, we also allow the argument to be
2506 // an 'unsigned int' as that is a reasonably safe case. GCC also
2507 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002508 CoveredArgs.set(argIndex);
2509 const Expr *Arg = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00002510 if (!Arg)
2511 return false;
2512
Ted Kremenek0d277352010-01-29 01:06:55 +00002513 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002514
Hans Wennborgf3749f42012-08-07 08:11:26 +00002515 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2516 assert(AT.isValid());
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002517
Hans Wennborgf3749f42012-08-07 08:11:26 +00002518 if (!AT.matchesType(S.Context, T)) {
Richard Trieu55733de2011-10-28 00:41:25 +00002519 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgf3749f42012-08-07 08:11:26 +00002520 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu55733de2011-10-28 00:41:25 +00002521 << T << Arg->getSourceRange(),
2522 getLocationOfByte(Amt.getStart()),
2523 /*IsStringLocation*/true,
2524 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek0d277352010-01-29 01:06:55 +00002525 // Don't do any more checking. We will just emit
2526 // spurious errors.
2527 return false;
2528 }
2529 }
2530 }
2531 return true;
2532}
Ted Kremenek0d277352010-01-29 01:06:55 +00002533
Tom Caree4ee9662010-06-17 19:00:27 +00002534void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00002535 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002536 const analyze_printf::OptionalAmount &Amt,
2537 unsigned type,
2538 const char *startSpecifier,
2539 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002540 const analyze_printf::PrintfConversionSpecifier &CS =
2541 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00002542
Richard Trieu55733de2011-10-28 00:41:25 +00002543 FixItHint fixit =
2544 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2545 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2546 Amt.getConstantLength()))
2547 : FixItHint();
2548
2549 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2550 << type << CS.toString(),
2551 getLocationOfByte(Amt.getStart()),
2552 /*IsStringLocation*/true,
2553 getSpecifierRange(startSpecifier, specifierLen),
2554 fixit);
Tom Caree4ee9662010-06-17 19:00:27 +00002555}
2556
Ted Kremenek826a3452010-07-16 02:11:22 +00002557void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002558 const analyze_printf::OptionalFlag &flag,
2559 const char *startSpecifier,
2560 unsigned specifierLen) {
2561 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002562 const analyze_printf::PrintfConversionSpecifier &CS =
2563 FS.getConversionSpecifier();
Richard Trieu55733de2011-10-28 00:41:25 +00002564 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2565 << flag.toString() << CS.toString(),
2566 getLocationOfByte(flag.getPosition()),
2567 /*IsStringLocation*/true,
2568 getSpecifierRange(startSpecifier, specifierLen),
2569 FixItHint::CreateRemoval(
2570 getSpecifierRange(flag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002571}
2572
2573void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00002574 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00002575 const analyze_printf::OptionalFlag &ignoredFlag,
2576 const analyze_printf::OptionalFlag &flag,
2577 const char *startSpecifier,
2578 unsigned specifierLen) {
2579 // Warn about ignored flag with a fixit removal.
Richard Trieu55733de2011-10-28 00:41:25 +00002580 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2581 << ignoredFlag.toString() << flag.toString(),
2582 getLocationOfByte(ignoredFlag.getPosition()),
2583 /*IsStringLocation*/true,
2584 getSpecifierRange(startSpecifier, specifierLen),
2585 FixItHint::CreateRemoval(
2586 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Caree4ee9662010-06-17 19:00:27 +00002587}
2588
Richard Smith831421f2012-06-25 20:30:08 +00002589// Determines if the specified is a C++ class or struct containing
2590// a member with the specified name and kind (e.g. a CXXMethodDecl named
2591// "c_str()").
2592template<typename MemberKind>
2593static llvm::SmallPtrSet<MemberKind*, 1>
2594CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2595 const RecordType *RT = Ty->getAs<RecordType>();
2596 llvm::SmallPtrSet<MemberKind*, 1> Results;
2597
2598 if (!RT)
2599 return Results;
2600 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2601 if (!RD)
2602 return Results;
2603
2604 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2605 Sema::LookupMemberName);
2606
2607 // We just need to include all members of the right kind turned up by the
2608 // filter, at this point.
2609 if (S.LookupQualifiedName(R, RT->getDecl()))
2610 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2611 NamedDecl *decl = (*I)->getUnderlyingDecl();
2612 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2613 Results.insert(FK);
2614 }
2615 return Results;
2616}
2617
2618// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgf3749f42012-08-07 08:11:26 +00002619// better diagnostic if so. AT is assumed to be valid.
Richard Smith831421f2012-06-25 20:30:08 +00002620// Returns true when a c_str() conversion method is found.
2621bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgf3749f42012-08-07 08:11:26 +00002622 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith831421f2012-06-25 20:30:08 +00002623 const CharSourceRange &CSR) {
2624 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2625
2626 MethodSet Results =
2627 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2628
2629 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2630 MI != ME; ++MI) {
2631 const CXXMethodDecl *Method = *MI;
2632 if (Method->getNumParams() == 0 &&
Hans Wennborgf3749f42012-08-07 08:11:26 +00002633 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith831421f2012-06-25 20:30:08 +00002634 // FIXME: Suggest parens if the expression needs them.
2635 SourceLocation EndLoc =
2636 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2637 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2638 << "c_str()"
2639 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2640 return true;
2641 }
2642 }
2643
2644 return false;
2645}
2646
Ted Kremeneke0e53132010-01-28 23:39:18 +00002647bool
Ted Kremenek826a3452010-07-16 02:11:22 +00002648CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00002649 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00002650 const char *startSpecifier,
2651 unsigned specifierLen) {
2652
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002653 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00002654 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00002655 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00002656
Ted Kremenekbaa40062010-07-19 22:01:06 +00002657 if (FS.consumesDataArgument()) {
2658 if (atFirstArg) {
2659 atFirstArg = false;
2660 usesPositionalArgs = FS.usesPositionalArg();
2661 }
2662 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00002663 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2664 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00002665 return false;
2666 }
Ted Kremenek0d277352010-01-29 01:06:55 +00002667 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002668
Ted Kremenekefaff192010-02-27 01:41:03 +00002669 // First check if the field width, precision, and conversion specifier
2670 // have matching data arguments.
2671 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2672 startSpecifier, specifierLen)) {
2673 return false;
2674 }
2675
2676 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2677 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00002678 return false;
2679 }
2680
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002681 if (!CS.consumesDataArgument()) {
2682 // FIXME: Technically specifying a precision or field width here
2683 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00002684 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00002685 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002686
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002687 // Consume the argument.
2688 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00002689 if (argIndex < NumDataArgs) {
2690 // The check to see if the argIndex is valid will come later.
2691 // We set the bit here because we may exit early from this
2692 // function if we encounter some other error.
2693 CoveredArgs.set(argIndex);
2694 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002695
2696 // Check for using an Objective-C specific conversion specifier
2697 // in a non-ObjC literal.
Jordan Rose50687312012-06-04 23:52:23 +00002698 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00002699 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2700 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00002701 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002702
Tom Caree4ee9662010-06-17 19:00:27 +00002703 // Check for invalid use of field width
2704 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00002705 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00002706 startSpecifier, specifierLen);
2707 }
2708
2709 // Check for invalid use of precision
2710 if (!FS.hasValidPrecision()) {
2711 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2712 startSpecifier, specifierLen);
2713 }
2714
2715 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00002716 if (!FS.hasValidThousandsGroupingPrefix())
2717 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002718 if (!FS.hasValidLeadingZeros())
2719 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2720 if (!FS.hasValidPlusPrefix())
2721 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00002722 if (!FS.hasValidSpacePrefix())
2723 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002724 if (!FS.hasValidAlternativeForm())
2725 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2726 if (!FS.hasValidLeftJustified())
2727 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2728
2729 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00002730 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2731 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2732 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00002733 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2734 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2735 startSpecifier, specifierLen);
2736
2737 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002738 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00002739 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2740 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002741 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00002742 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002743 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00002744 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
2745 diag::warn_format_non_standard_conversion_spec);
Tom Caree4ee9662010-06-17 19:00:27 +00002746
Jordan Rosebbb6bb42012-09-08 04:00:03 +00002747 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
2748 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2749
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002750 // The remaining checks depend on the data arguments.
2751 if (HasVAListArg)
2752 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002753
Ted Kremenek666a1972010-07-26 19:45:42 +00002754 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00002755 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002756
Jordan Rose48716662012-07-19 18:10:08 +00002757 const Expr *Arg = getDataArg(argIndex);
2758 if (!Arg)
2759 return true;
2760
2761 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith831421f2012-06-25 20:30:08 +00002762}
2763
Jordan Roseec087352012-09-05 22:56:26 +00002764static bool requiresParensToAddCast(const Expr *E) {
2765 // FIXME: We should have a general way to reason about operator
2766 // precedence and whether parens are actually needed here.
2767 // Take care of a few common cases where they aren't.
2768 const Expr *Inside = E->IgnoreImpCasts();
2769 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
2770 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
2771
2772 switch (Inside->getStmtClass()) {
2773 case Stmt::ArraySubscriptExprClass:
2774 case Stmt::CallExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002775 case Stmt::CharacterLiteralClass:
2776 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002777 case Stmt::DeclRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002778 case Stmt::FloatingLiteralClass:
2779 case Stmt::IntegerLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002780 case Stmt::MemberExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002781 case Stmt::ObjCArrayLiteralClass:
2782 case Stmt::ObjCBoolLiteralExprClass:
2783 case Stmt::ObjCBoxedExprClass:
2784 case Stmt::ObjCDictionaryLiteralClass:
2785 case Stmt::ObjCEncodeExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002786 case Stmt::ObjCIvarRefExprClass:
2787 case Stmt::ObjCMessageExprClass:
2788 case Stmt::ObjCPropertyRefExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002789 case Stmt::ObjCStringLiteralClass:
2790 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseec087352012-09-05 22:56:26 +00002791 case Stmt::ParenExprClass:
Jordan Rose17ddc542012-12-05 18:44:44 +00002792 case Stmt::StringLiteralClass:
Jordan Roseec087352012-09-05 22:56:26 +00002793 case Stmt::UnaryOperatorClass:
2794 return false;
2795 default:
2796 return true;
2797 }
2798}
2799
Richard Smith831421f2012-06-25 20:30:08 +00002800bool
2801CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2802 const char *StartSpecifier,
2803 unsigned SpecifierLen,
2804 const Expr *E) {
2805 using namespace analyze_format_string;
2806 using namespace analyze_printf;
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002807 // Now type check the data expression that matches the
2808 // format specifier.
Hans Wennborgf3749f42012-08-07 08:11:26 +00002809 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
2810 ObjCContext);
Jordan Rose614a8652012-09-05 22:56:19 +00002811 if (!AT.isValid())
2812 return true;
Jordan Roseec087352012-09-05 22:56:26 +00002813
Jordan Rose448ac3e2012-12-05 18:44:40 +00002814 QualType ExprTy = E->getType();
Ted Kremenek02be9682013-04-10 06:26:26 +00002815 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
2816 ExprTy = TET->getUnderlyingExpr()->getType();
2817 }
2818
Jordan Rose448ac3e2012-12-05 18:44:40 +00002819 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002820 return true;
Jordan Roseee0259d2012-06-04 22:48:57 +00002821
Jordan Rose614a8652012-09-05 22:56:19 +00002822 // Look through argument promotions for our error message's reported type.
2823 // This includes the integral and floating promotions, but excludes array
2824 // and function pointer decay; seeing that an argument intended to be a
2825 // string has type 'char [6]' is probably more confusing than 'char *'.
2826 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
2827 if (ICE->getCastKind() == CK_IntegralCast ||
2828 ICE->getCastKind() == CK_FloatingCast) {
2829 E = ICE->getSubExpr();
Jordan Rose448ac3e2012-12-05 18:44:40 +00002830 ExprTy = E->getType();
Jordan Rose614a8652012-09-05 22:56:19 +00002831
2832 // Check if we didn't match because of an implicit cast from a 'char'
2833 // or 'short' to an 'int'. This is done because printf is a varargs
2834 // function.
2835 if (ICE->getType() == S.Context.IntTy ||
2836 ICE->getType() == S.Context.UnsignedIntTy) {
2837 // All further checking is done on the subexpression.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002838 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose614a8652012-09-05 22:56:19 +00002839 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00002840 }
Jordan Roseee0259d2012-06-04 22:48:57 +00002841 }
Jordan Rose448ac3e2012-12-05 18:44:40 +00002842 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
2843 // Special case for 'a', which has type 'int' in C.
2844 // Note, however, that we do /not/ want to treat multibyte constants like
2845 // 'MooV' as characters! This form is deprecated but still exists.
2846 if (ExprTy == S.Context.IntTy)
2847 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
2848 ExprTy = S.Context.CharTy;
Jordan Rose614a8652012-09-05 22:56:19 +00002849 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002850
Jordan Rose2cd34402012-12-05 18:44:49 +00002851 // %C in an Objective-C context prints a unichar, not a wchar_t.
2852 // If the argument is an integer of some kind, believe the %C and suggest
2853 // a cast instead of changing the conversion specifier.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002854 QualType IntendedTy = ExprTy;
Jordan Rose2cd34402012-12-05 18:44:49 +00002855 if (ObjCContext &&
2856 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
2857 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
2858 !ExprTy->isCharType()) {
2859 // 'unichar' is defined as a typedef of unsigned short, but we should
2860 // prefer using the typedef if it is visible.
2861 IntendedTy = S.Context.UnsignedShortTy;
2862
2863 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
2864 Sema::LookupOrdinaryName);
2865 if (S.LookupName(Result, S.getCurScope())) {
2866 NamedDecl *ND = Result.getFoundDecl();
2867 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
2868 if (TD->getUnderlyingType() == IntendedTy)
2869 IntendedTy = S.Context.getTypedefType(TD);
2870 }
2871 }
2872 }
2873
2874 // Special-case some of Darwin's platform-independence types by suggesting
2875 // casts to primitive types that are known to be large enough.
2876 bool ShouldNotPrintDirectly = false;
Jordan Roseec087352012-09-05 22:56:26 +00002877 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenek6edb0292013-03-25 22:28:37 +00002878 // Use a 'while' to peel off layers of typedefs.
2879 QualType TyTy = IntendedTy;
2880 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseec087352012-09-05 22:56:26 +00002881 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose2cd34402012-12-05 18:44:49 +00002882 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseec087352012-09-05 22:56:26 +00002883 .Case("NSInteger", S.Context.LongTy)
2884 .Case("NSUInteger", S.Context.UnsignedLongTy)
2885 .Case("SInt32", S.Context.IntTy)
2886 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose2cd34402012-12-05 18:44:49 +00002887 .Default(QualType());
2888
2889 if (!CastTy.isNull()) {
2890 ShouldNotPrintDirectly = true;
2891 IntendedTy = CastTy;
Ted Kremenek6edb0292013-03-25 22:28:37 +00002892 break;
Jordan Rose2cd34402012-12-05 18:44:49 +00002893 }
Ted Kremenek6edb0292013-03-25 22:28:37 +00002894 TyTy = UserTy->desugar();
Jordan Roseec087352012-09-05 22:56:26 +00002895 }
2896 }
2897
Jordan Rose614a8652012-09-05 22:56:19 +00002898 // We may be able to offer a FixItHint if it is a supported type.
2899 PrintfSpecifier fixedFS = FS;
Jordan Roseec087352012-09-05 22:56:26 +00002900 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose614a8652012-09-05 22:56:19 +00002901 S.Context, ObjCContext);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002902
Jordan Rose614a8652012-09-05 22:56:19 +00002903 if (success) {
2904 // Get the fix string from the fixed format specifier
2905 SmallString<16> buf;
2906 llvm::raw_svector_ostream os(buf);
2907 fixedFS.toString(os);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00002908
Jordan Roseec087352012-09-05 22:56:26 +00002909 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
2910
Jordan Rose2cd34402012-12-05 18:44:49 +00002911 if (IntendedTy == ExprTy) {
2912 // In this case, the specifier is wrong and should be changed to match
2913 // the argument.
2914 EmitFormatDiagnostic(
2915 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2916 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
2917 << E->getSourceRange(),
2918 E->getLocStart(),
2919 /*IsStringLocation*/false,
2920 SpecRange,
2921 FixItHint::CreateReplacement(SpecRange, os.str()));
2922
2923 } else {
Jordan Roseec087352012-09-05 22:56:26 +00002924 // The canonical type for formatting this value is different from the
2925 // actual type of the expression. (This occurs, for example, with Darwin's
2926 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
2927 // should be printed as 'long' for 64-bit compatibility.)
2928 // Rather than emitting a normal format/argument mismatch, we want to
2929 // add a cast to the recommended type (and correct the format string
2930 // if necessary).
2931 SmallString<16> CastBuf;
2932 llvm::raw_svector_ostream CastFix(CastBuf);
2933 CastFix << "(";
2934 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
2935 CastFix << ")";
2936
2937 SmallVector<FixItHint,4> Hints;
2938 if (!AT.matchesType(S.Context, IntendedTy))
2939 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
2940
2941 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
2942 // If there's already a cast present, just replace it.
2943 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
2944 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
2945
2946 } else if (!requiresParensToAddCast(E)) {
2947 // If the expression has high enough precedence,
2948 // just write the C-style cast.
2949 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2950 CastFix.str()));
2951 } else {
2952 // Otherwise, add parens around the expression as well as the cast.
2953 CastFix << "(";
2954 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
2955 CastFix.str()));
2956
2957 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
2958 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
2959 }
2960
Jordan Rose2cd34402012-12-05 18:44:49 +00002961 if (ShouldNotPrintDirectly) {
2962 // The expression has a type that should not be printed directly.
2963 // We extract the name from the typedef because we don't want to show
2964 // the underlying type in the diagnostic.
2965 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseec087352012-09-05 22:56:26 +00002966
Jordan Rose2cd34402012-12-05 18:44:49 +00002967 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
2968 << Name << IntendedTy
2969 << E->getSourceRange(),
2970 E->getLocStart(), /*IsStringLocation=*/false,
2971 SpecRange, Hints);
2972 } else {
2973 // In this case, the expression could be printed using a different
2974 // specifier, but we've decided that the specifier is probably correct
2975 // and we should cast instead. Just use the normal warning message.
2976 EmitFormatDiagnostic(
2977 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2978 << AT.getRepresentativeTypeName(S.Context) << ExprTy
2979 << E->getSourceRange(),
2980 E->getLocStart(), /*IsStringLocation*/false,
2981 SpecRange, Hints);
2982 }
Jordan Roseec087352012-09-05 22:56:26 +00002983 }
Jordan Rose614a8652012-09-05 22:56:19 +00002984 } else {
2985 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
2986 SpecifierLen);
2987 // Since the warning for passing non-POD types to variadic functions
2988 // was deferred until now, we emit a warning for non-POD
2989 // arguments here.
Jordan Rose448ac3e2012-12-05 18:44:40 +00002990 if (S.isValidVarArgType(ExprTy) == Sema::VAK_Invalid) {
Jordan Rose614a8652012-09-05 22:56:19 +00002991 unsigned DiagKind;
Jordan Rose448ac3e2012-12-05 18:44:40 +00002992 if (ExprTy->isObjCObjectType())
Jordan Rose614a8652012-09-05 22:56:19 +00002993 DiagKind = diag::err_cannot_pass_objc_interface_to_vararg_format;
2994 else
2995 DiagKind = diag::warn_non_pod_vararg_with_format_string;
2996
2997 EmitFormatDiagnostic(
2998 S.PDiag(DiagKind)
Richard Smith80ad52f2013-01-02 11:42:31 +00002999 << S.getLangOpts().CPlusPlus11
Jordan Rose448ac3e2012-12-05 18:44:40 +00003000 << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003001 << CallType
3002 << AT.getRepresentativeTypeName(S.Context)
3003 << CSR
3004 << E->getSourceRange(),
3005 E->getLocStart(), /*IsStringLocation*/false, CSR);
3006
3007 checkForCStrMembers(AT, E, CSR);
3008 } else
Richard Trieu55733de2011-10-28 00:41:25 +00003009 EmitFormatDiagnostic(
3010 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Jordan Rose448ac3e2012-12-05 18:44:40 +00003011 << AT.getRepresentativeTypeName(S.Context) << ExprTy
Jordan Rose614a8652012-09-05 22:56:19 +00003012 << CSR
Richard Smith831421f2012-06-25 20:30:08 +00003013 << E->getSourceRange(),
Jordan Rose614a8652012-09-05 22:56:19 +00003014 E->getLocStart(), /*IsStringLocation*/false, CSR);
Michael J. Spencer96827eb2010-07-27 04:46:02 +00003015 }
3016
Ted Kremeneke0e53132010-01-28 23:39:18 +00003017 return true;
3018}
3019
Ted Kremenek826a3452010-07-16 02:11:22 +00003020//===--- CHECK: Scanf format string checking ------------------------------===//
3021
3022namespace {
3023class CheckScanfHandler : public CheckFormatHandler {
3024public:
3025 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3026 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003027 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003028 ArrayRef<const Expr *> Args,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003029 unsigned formatIdx, bool inFunctionCall,
3030 Sema::VariadicCallType CallType)
Ted Kremenek826a3452010-07-16 02:11:22 +00003031 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003032 numDataArgs, beg, hasVAListArg,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003033 Args, formatIdx, inFunctionCall, CallType)
Jordan Roseddcfbc92012-07-19 18:10:23 +00003034 {}
Ted Kremenek826a3452010-07-16 02:11:22 +00003035
3036 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3037 const char *startSpecifier,
3038 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003039
3040 bool HandleInvalidScanfConversionSpecifier(
3041 const analyze_scanf::ScanfSpecifier &FS,
3042 const char *startSpecifier,
3043 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00003044
3045 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00003046};
Ted Kremenek07d161f2010-01-29 01:50:07 +00003047}
Ted Kremeneke0e53132010-01-28 23:39:18 +00003048
Ted Kremenekb7c21012010-07-16 18:28:03 +00003049void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3050 const char *end) {
Richard Trieu55733de2011-10-28 00:41:25 +00003051 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3052 getLocationOfByte(end), /*IsStringLocation*/true,
3053 getSpecifierRange(start, end - start));
Ted Kremenekb7c21012010-07-16 18:28:03 +00003054}
3055
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003056bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3057 const analyze_scanf::ScanfSpecifier &FS,
3058 const char *startSpecifier,
3059 unsigned specifierLen) {
3060
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003061 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00003062 FS.getConversionSpecifier();
3063
3064 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3065 getLocationOfByte(CS.getStart()),
3066 startSpecifier, specifierLen,
3067 CS.getStart(), CS.getLength());
3068}
3069
Ted Kremenek826a3452010-07-16 02:11:22 +00003070bool CheckScanfHandler::HandleScanfSpecifier(
3071 const analyze_scanf::ScanfSpecifier &FS,
3072 const char *startSpecifier,
3073 unsigned specifierLen) {
3074
3075 using namespace analyze_scanf;
3076 using namespace analyze_format_string;
3077
Ted Kremenek6ecb9502010-07-20 20:04:27 +00003078 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00003079
Ted Kremenekbaa40062010-07-19 22:01:06 +00003080 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3081 // be used to decide if we are using positional arguments consistently.
3082 if (FS.consumesDataArgument()) {
3083 if (atFirstArg) {
3084 atFirstArg = false;
3085 usesPositionalArgs = FS.usesPositionalArg();
3086 }
3087 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003088 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3089 startSpecifier, specifierLen);
Ted Kremenekbaa40062010-07-19 22:01:06 +00003090 return false;
3091 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003092 }
3093
3094 // Check if the field with is non-zero.
3095 const OptionalAmount &Amt = FS.getFieldWidth();
3096 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3097 if (Amt.getConstantAmount() == 0) {
3098 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3099 Amt.getConstantLength());
Richard Trieu55733de2011-10-28 00:41:25 +00003100 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3101 getLocationOfByte(Amt.getStart()),
3102 /*IsStringLocation*/true, R,
3103 FixItHint::CreateRemoval(R));
Ted Kremenek826a3452010-07-16 02:11:22 +00003104 }
3105 }
3106
3107 if (!FS.consumesDataArgument()) {
3108 // FIXME: Technically specifying a precision or field width here
3109 // makes no sense. Worth issuing a warning at some point.
3110 return true;
3111 }
3112
3113 // Consume the argument.
3114 unsigned argIndex = FS.getArgIndex();
3115 if (argIndex < NumDataArgs) {
3116 // The check to see if the argIndex is valid will come later.
3117 // We set the bit here because we may exit early from this
3118 // function if we encounter some other error.
3119 CoveredArgs.set(argIndex);
3120 }
3121
Ted Kremenek1e51c202010-07-20 20:04:47 +00003122 // Check the length modifier is valid with the given conversion specifier.
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003123 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose8be066e2012-09-08 04:00:12 +00003124 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3125 diag::warn_format_nonsensical_length);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003126 else if (!FS.hasStandardLengthModifier())
Jordan Rose8be066e2012-09-08 04:00:12 +00003127 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003128 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose8be066e2012-09-08 04:00:12 +00003129 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3130 diag::warn_format_non_standard_conversion_spec);
Hans Wennborg76517422012-02-22 10:17:01 +00003131
Jordan Rosebbb6bb42012-09-08 04:00:03 +00003132 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3133 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3134
Ted Kremenek826a3452010-07-16 02:11:22 +00003135 // The remaining checks depend on the data arguments.
3136 if (HasVAListArg)
3137 return true;
3138
Ted Kremenek666a1972010-07-26 19:45:42 +00003139 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00003140 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00003141
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003142 // Check that the argument type matches the format specifier.
3143 const Expr *Ex = getDataArg(argIndex);
Jordan Rose48716662012-07-19 18:10:08 +00003144 if (!Ex)
3145 return true;
3146
Hans Wennborg58e1e542012-08-07 08:59:46 +00003147 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3148 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003149 ScanfSpecifier fixedFS = FS;
David Blaikie4e4d0842012-03-11 07:00:24 +00003150 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgbe6126a2012-02-15 09:59:46 +00003151 S.Context);
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003152
3153 if (success) {
3154 // Get the fix string from the fixed format specifier.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003155 SmallString<128> buf;
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003156 llvm::raw_svector_ostream os(buf);
3157 fixedFS.toString(os);
3158
3159 EmitFormatDiagnostic(
3160 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003161 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003162 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003163 Ex->getLocStart(),
3164 /*IsStringLocation*/false,
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003165 getSpecifierRange(startSpecifier, specifierLen),
3166 FixItHint::CreateReplacement(
3167 getSpecifierRange(startSpecifier, specifierLen),
3168 os.str()));
3169 } else {
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003170 EmitFormatDiagnostic(
3171 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborg58e1e542012-08-07 08:59:46 +00003172 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003173 << Ex->getSourceRange(),
Matt Beaumont-Gayabf145a2012-05-17 00:03:16 +00003174 Ex->getLocStart(),
3175 /*IsStringLocation*/false,
Jean-Daniel Dupas220947b2012-01-31 18:12:08 +00003176 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborg6fcd9322011-12-10 13:20:11 +00003177 }
3178 }
3179
Ted Kremenek826a3452010-07-16 02:11:22 +00003180 return true;
3181}
3182
3183void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00003184 const Expr *OrigFormatExpr,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003185 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003186 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003187 unsigned firstDataArg, FormatStringType Type,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003188 bool inFunctionCall, VariadicCallType CallType) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003189
Ted Kremeneke0e53132010-01-28 23:39:18 +00003190 // CHECK: is the format string a wide literal?
Richard Smithdf9ef1b2012-06-13 05:37:23 +00003191 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu55733de2011-10-28 00:41:25 +00003192 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003193 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003194 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3195 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003196 return;
3197 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003198
Ted Kremeneke0e53132010-01-28 23:39:18 +00003199 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner5f9e2722011-07-23 10:55:15 +00003200 StringRef StrRef = FExpr->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00003201 const char *Str = StrRef.data();
3202 unsigned StrLen = StrRef.size();
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003203 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek826a3452010-07-16 02:11:22 +00003204
Ted Kremeneke0e53132010-01-28 23:39:18 +00003205 // CHECK: empty format string?
Ted Kremenek4cd57912011-09-29 05:52:16 +00003206 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu55733de2011-10-28 00:41:25 +00003207 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00003208 *this, inFunctionCall, Args[format_idx],
Richard Trieu55733de2011-10-28 00:41:25 +00003209 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3210 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremeneke0e53132010-01-28 23:39:18 +00003211 return;
3212 }
Ted Kremenek826a3452010-07-16 02:11:22 +00003213
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003214 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek826a3452010-07-16 02:11:22 +00003215 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose50687312012-06-04 23:52:23 +00003216 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003217 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003218 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003219
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003220 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003221 getLangOpts(),
3222 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003223 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003224 } else if (Type == FST_Scanf) {
Jordan Rose50687312012-06-04 23:52:23 +00003225 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko1c030e92013-01-13 20:46:02 +00003226 Str, HasVAListArg, Args, format_idx,
Jordan Roseddcfbc92012-07-19 18:10:23 +00003227 inFunctionCall, CallType);
Ted Kremenek826a3452010-07-16 02:11:22 +00003228
Hans Wennborgd02deeb2011-12-15 10:25:47 +00003229 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose275b6f52012-09-13 02:11:03 +00003230 getLangOpts(),
3231 Context.getTargetInfo()))
Ted Kremenek826a3452010-07-16 02:11:22 +00003232 H.DoneProcessing();
Jean-Daniel Dupas34269df2012-01-30 08:46:47 +00003233 } // TODO: handle other formats
Ted Kremenekce7024e2010-01-28 01:18:22 +00003234}
3235
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003236//===--- CHECK: Standard memory functions ---------------------------------===//
3237
Douglas Gregor2a053a32011-05-03 20:05:22 +00003238/// \brief Determine whether the given type is a dynamic class type (e.g.,
3239/// whether it has a vtable).
3240static bool isDynamicClassType(QualType T) {
3241 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3242 if (CXXRecordDecl *Definition = Record->getDefinition())
3243 if (Definition->isDynamicClass())
3244 return true;
3245
3246 return false;
3247}
3248
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003249/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth000d4282011-06-16 09:09:40 +00003250/// otherwise returns NULL.
3251static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Webere4a1c642011-06-14 16:14:58 +00003252 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth000d4282011-06-16 09:09:40 +00003253 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3254 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3255 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003256
Chandler Carruth000d4282011-06-16 09:09:40 +00003257 return 0;
3258}
3259
Chandler Carrutha72a12f2011-06-21 23:04:20 +00003260/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth000d4282011-06-16 09:09:40 +00003261static QualType getSizeOfArgType(const Expr* E) {
3262 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3263 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3264 if (SizeOf->getKind() == clang::UETT_SizeOf)
3265 return SizeOf->getTypeOfArgument();
3266
3267 return QualType();
Nico Webere4a1c642011-06-14 16:14:58 +00003268}
3269
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003270/// \brief Check for dangerous or invalid arguments to memset().
3271///
Chandler Carruth929f0132011-06-03 06:23:57 +00003272/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003273/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3274/// function calls.
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003275///
3276/// \param Call The call expression to diagnose.
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003277void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks0a151a12012-01-17 00:37:07 +00003278 unsigned BId,
Matt Beaumont-Gaycc2f30c2011-08-05 00:22:34 +00003279 IdentifierInfo *FnName) {
Anna Zaks0a151a12012-01-17 00:37:07 +00003280 assert(BId != 0);
3281
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003282 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor707a23e2011-06-16 17:56:04 +00003283 // we have enough arguments, and if not, abort further checking.
Anna Zaks0a151a12012-01-17 00:37:07 +00003284 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Webercda57822011-10-13 22:30:23 +00003285 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00003286 return;
3287
Anna Zaks0a151a12012-01-17 00:37:07 +00003288 unsigned LastArg = (BId == Builtin::BImemset ||
3289 BId == Builtin::BIstrndup ? 1 : 2);
3290 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Webercda57822011-10-13 22:30:23 +00003291 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth000d4282011-06-16 09:09:40 +00003292
3293 // We have special checking when the length is a sizeof expression.
3294 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3295 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3296 llvm::FoldingSetNodeID SizeOfArgID;
3297
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003298 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3299 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Webere4a1c642011-06-14 16:14:58 +00003300 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003301
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003302 QualType DestTy = Dest->getType();
3303 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3304 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00003305
Chandler Carruth000d4282011-06-16 09:09:40 +00003306 // Never warn about void type pointers. This can be used to suppress
3307 // false positives.
3308 if (PointeeTy->isVoidType())
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003309 continue;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003310
Chandler Carruth000d4282011-06-16 09:09:40 +00003311 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3312 // actually comparing the expressions for equality. Because computing the
3313 // expression IDs can be expensive, we only do this if the diagnostic is
3314 // enabled.
3315 if (SizeOfArg &&
3316 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3317 SizeOfArg->getExprLoc())) {
3318 // We only compute IDs for expressions if the warning is enabled, and
3319 // cache the sizeof arg's ID.
3320 if (SizeOfArgID == llvm::FoldingSetNodeID())
3321 SizeOfArg->Profile(SizeOfArgID, Context, true);
3322 llvm::FoldingSetNodeID DestID;
3323 Dest->Profile(DestID, Context, true);
3324 if (DestID == SizeOfArgID) {
Nico Webercda57822011-10-13 22:30:23 +00003325 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3326 // over sizeof(src) as well.
Chandler Carruth000d4282011-06-16 09:09:40 +00003327 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003328 StringRef ReadableName = FnName->getName();
3329
Chandler Carruth000d4282011-06-16 09:09:40 +00003330 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaks90c78322012-05-30 23:14:52 +00003331 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth000d4282011-06-16 09:09:40 +00003332 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian7adf4172013-01-30 01:12:44 +00003333 if (!PointeeTy->isIncompleteType() &&
3334 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth000d4282011-06-16 09:09:40 +00003335 ActionIdx = 2; // If the pointee's size is sizeof(char),
3336 // suggest an explicit length.
Anna Zaks6fcb3722012-05-30 00:34:21 +00003337
3338 // If the function is defined as a builtin macro, do not show macro
3339 // expansion.
3340 SourceLocation SL = SizeOfArg->getExprLoc();
3341 SourceRange DSR = Dest->getSourceRange();
3342 SourceRange SSR = SizeOfArg->getSourceRange();
3343 SourceManager &SM = PP.getSourceManager();
3344
3345 if (SM.isMacroArgExpansion(SL)) {
3346 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3347 SL = SM.getSpellingLoc(SL);
3348 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3349 SM.getSpellingLoc(DSR.getEnd()));
3350 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3351 SM.getSpellingLoc(SSR.getEnd()));
3352 }
3353
Anna Zaks90c78322012-05-30 23:14:52 +00003354 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth000d4282011-06-16 09:09:40 +00003355 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks6fcb3722012-05-30 00:34:21 +00003356 << ReadableName
Anna Zaks90c78322012-05-30 23:14:52 +00003357 << PointeeTy
3358 << DestTy
Anna Zaks6fcb3722012-05-30 00:34:21 +00003359 << DSR
Anna Zaks90c78322012-05-30 23:14:52 +00003360 << SSR);
3361 DiagRuntimeBehavior(SL, SizeOfArg,
3362 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3363 << ActionIdx
3364 << SSR);
3365
Chandler Carruth000d4282011-06-16 09:09:40 +00003366 break;
3367 }
3368 }
3369
3370 // Also check for cases where the sizeof argument is the exact same
3371 // type as the memory argument, and where it points to a user-defined
3372 // record type.
3373 if (SizeOfArgTy != QualType()) {
3374 if (PointeeTy->isRecordType() &&
3375 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3376 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3377 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3378 << FnName << SizeOfArgTy << ArgIdx
3379 << PointeeTy << Dest->getSourceRange()
3380 << LenExpr->getSourceRange());
3381 break;
3382 }
Nico Webere4a1c642011-06-14 16:14:58 +00003383 }
3384
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003385 // Always complain about dynamic classes.
Anna Zaks0a151a12012-01-17 00:37:07 +00003386 if (isDynamicClassType(PointeeTy)) {
3387
3388 unsigned OperationType = 0;
3389 // "overwritten" if we're warning about the destination for any call
3390 // but memcmp; otherwise a verb appropriate to the call.
3391 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3392 if (BId == Builtin::BImemcpy)
3393 OperationType = 1;
3394 else if(BId == Builtin::BImemmove)
3395 OperationType = 2;
3396 else if (BId == Builtin::BImemcmp)
3397 OperationType = 3;
3398 }
3399
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003400 DiagRuntimeBehavior(
3401 Dest->getExprLoc(), Dest,
3402 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks0a151a12012-01-17 00:37:07 +00003403 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaksd9b859a2012-01-13 21:52:01 +00003404 << FnName << PointeeTy
Anna Zaks0a151a12012-01-17 00:37:07 +00003405 << OperationType
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003406 << Call->getCallee()->getSourceRange());
Anna Zaks0a151a12012-01-17 00:37:07 +00003407 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3408 BId != Builtin::BImemset)
Matt Beaumont-Gay5c5218e2011-08-19 20:40:18 +00003409 DiagRuntimeBehavior(
3410 Dest->getExprLoc(), Dest,
3411 PDiag(diag::warn_arc_object_memaccess)
3412 << ArgIdx << FnName << PointeeTy
3413 << Call->getCallee()->getSourceRange());
John McCallf85e1932011-06-15 23:02:42 +00003414 else
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003415 continue;
John McCallf85e1932011-06-15 23:02:42 +00003416
3417 DiagRuntimeBehavior(
3418 Dest->getExprLoc(), Dest,
Chandler Carruth929f0132011-06-03 06:23:57 +00003419 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor06bc9eb2011-05-03 20:37:33 +00003420 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3421 break;
3422 }
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00003423 }
3424}
3425
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003426// A little helper routine: ignore addition and subtraction of integer literals.
3427// This intentionally does not ignore all integer constant expressions because
3428// we don't want to remove sizeof().
3429static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3430 Ex = Ex->IgnoreParenCasts();
3431
3432 for (;;) {
3433 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3434 if (!BO || !BO->isAdditiveOp())
3435 break;
3436
3437 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3438 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3439
3440 if (isa<IntegerLiteral>(RHS))
3441 Ex = LHS;
3442 else if (isa<IntegerLiteral>(LHS))
3443 Ex = RHS;
3444 else
3445 break;
3446 }
3447
3448 return Ex;
3449}
3450
Anna Zaks0f38ace2012-08-08 21:42:23 +00003451static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3452 ASTContext &Context) {
3453 // Only handle constant-sized or VLAs, but not flexible members.
3454 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3455 // Only issue the FIXIT for arrays of size > 1.
3456 if (CAT->getSize().getSExtValue() <= 1)
3457 return false;
3458 } else if (!Ty->isVariableArrayType()) {
3459 return false;
3460 }
3461 return true;
3462}
3463
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003464// Warn if the user has made the 'size' argument to strlcpy or strlcat
3465// be the size of the source, instead of the destination.
3466void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3467 IdentifierInfo *FnName) {
3468
3469 // Don't crash if the user has the wrong number of arguments
3470 if (Call->getNumArgs() != 3)
3471 return;
3472
3473 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3474 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3475 const Expr *CompareWithSrc = NULL;
3476
3477 // Look for 'strlcpy(dst, x, sizeof(x))'
3478 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3479 CompareWithSrc = Ex;
3480 else {
3481 // Look for 'strlcpy(dst, x, strlen(x))'
3482 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Richard Smith180f4792011-11-10 06:34:14 +00003483 if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003484 && SizeCall->getNumArgs() == 1)
3485 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3486 }
3487 }
3488
3489 if (!CompareWithSrc)
3490 return;
3491
3492 // Determine if the argument to sizeof/strlen is equal to the source
3493 // argument. In principle there's all kinds of things you could do
3494 // here, for instance creating an == expression and evaluating it with
3495 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3496 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3497 if (!SrcArgDRE)
3498 return;
3499
3500 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3501 if (!CompareWithSrcDRE ||
3502 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3503 return;
3504
3505 const Expr *OriginalSizeArg = Call->getArg(2);
3506 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3507 << OriginalSizeArg->getSourceRange() << FnName;
3508
3509 // Output a FIXIT hint if the destination is an array (rather than a
3510 // pointer to an array). This could be enhanced to handle some
3511 // pointers if we know the actual size, like if DstArg is 'array+2'
3512 // we could say 'sizeof(array)-2'.
3513 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks0f38ace2012-08-08 21:42:23 +00003514 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek8f746222011-08-18 22:48:41 +00003515 return;
Ted Kremenek8f746222011-08-18 22:48:41 +00003516
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003517 SmallString<128> sizeString;
Ted Kremenek8f746222011-08-18 22:48:41 +00003518 llvm::raw_svector_ostream OS(sizeString);
3519 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003520 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek8f746222011-08-18 22:48:41 +00003521 OS << ")";
3522
3523 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3524 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3525 OS.str());
Ted Kremenekbd5da9d2011-08-18 20:55:45 +00003526}
3527
Anna Zaksc36bedc2012-02-01 19:08:57 +00003528/// Check if two expressions refer to the same declaration.
3529static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3530 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3531 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3532 return D1->getDecl() == D2->getDecl();
3533 return false;
3534}
3535
3536static const Expr *getStrlenExprArg(const Expr *E) {
3537 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3538 const FunctionDecl *FD = CE->getDirectCallee();
3539 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3540 return 0;
3541 return CE->getArg(0)->IgnoreParenCasts();
3542 }
3543 return 0;
3544}
3545
3546// Warn on anti-patterns as the 'size' argument to strncat.
3547// The correct size argument should look like following:
3548// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3549void Sema::CheckStrncatArguments(const CallExpr *CE,
3550 IdentifierInfo *FnName) {
3551 // Don't crash if the user has the wrong number of arguments.
3552 if (CE->getNumArgs() < 3)
3553 return;
3554 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3555 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3556 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3557
3558 // Identify common expressions, which are wrongly used as the size argument
3559 // to strncat and may lead to buffer overflows.
3560 unsigned PatternType = 0;
3561 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3562 // - sizeof(dst)
3563 if (referToTheSameDecl(SizeOfArg, DstArg))
3564 PatternType = 1;
3565 // - sizeof(src)
3566 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3567 PatternType = 2;
3568 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3569 if (BE->getOpcode() == BO_Sub) {
3570 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3571 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3572 // - sizeof(dst) - strlen(dst)
3573 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3574 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3575 PatternType = 1;
3576 // - sizeof(src) - (anything)
3577 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3578 PatternType = 2;
3579 }
3580 }
3581
3582 if (PatternType == 0)
3583 return;
3584
Anna Zaksafdb0412012-02-03 01:27:37 +00003585 // Generate the diagnostic.
3586 SourceLocation SL = LenArg->getLocStart();
3587 SourceRange SR = LenArg->getSourceRange();
3588 SourceManager &SM = PP.getSourceManager();
3589
3590 // If the function is defined as a builtin macro, do not show macro expansion.
3591 if (SM.isMacroArgExpansion(SL)) {
3592 SL = SM.getSpellingLoc(SL);
3593 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3594 SM.getSpellingLoc(SR.getEnd()));
3595 }
3596
Anna Zaks0f38ace2012-08-08 21:42:23 +00003597 // Check if the destination is an array (rather than a pointer to an array).
3598 QualType DstTy = DstArg->getType();
3599 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3600 Context);
3601 if (!isKnownSizeArray) {
3602 if (PatternType == 1)
3603 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3604 else
3605 Diag(SL, diag::warn_strncat_src_size) << SR;
3606 return;
3607 }
3608
Anna Zaksc36bedc2012-02-01 19:08:57 +00003609 if (PatternType == 1)
Anna Zaksafdb0412012-02-03 01:27:37 +00003610 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003611 else
Anna Zaksafdb0412012-02-03 01:27:37 +00003612 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003613
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +00003614 SmallString<128> sizeString;
Anna Zaksc36bedc2012-02-01 19:08:57 +00003615 llvm::raw_svector_ostream OS(sizeString);
3616 OS << "sizeof(";
Richard Smithd1420c62012-08-16 03:56:14 +00003617 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003618 OS << ") - ";
3619 OS << "strlen(";
Richard Smithd1420c62012-08-16 03:56:14 +00003620 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003621 OS << ") - 1";
3622
Anna Zaksafdb0412012-02-03 01:27:37 +00003623 Diag(SL, diag::note_strncat_wrong_size)
3624 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaksc36bedc2012-02-01 19:08:57 +00003625}
3626
Ted Kremenek06de2762007-08-17 16:46:58 +00003627//===--- CHECK: Return Address of Stack Variable --------------------------===//
3628
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003629static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3630 Decl *ParentDecl);
3631static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3632 Decl *ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003633
3634/// CheckReturnStackAddr - Check if a return statement returns the address
3635/// of a stack variable.
3636void
3637Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3638 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00003639
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003640 Expr *stackE = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003641 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003642
3643 // Perform checking for returned stack addresses, local blocks,
3644 // label addresses or references to temporaries.
John McCallf85e1932011-06-15 23:02:42 +00003645 if (lhsType->isPointerType() ||
David Blaikie4e4d0842012-03-11 07:00:24 +00003646 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003647 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00003648 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003649 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003650 }
3651
3652 if (stackE == 0)
3653 return; // Nothing suspicious was found.
3654
3655 SourceLocation diagLoc;
3656 SourceRange diagRange;
3657 if (refVars.empty()) {
3658 diagLoc = stackE->getLocStart();
3659 diagRange = stackE->getSourceRange();
3660 } else {
3661 // We followed through a reference variable. 'stackE' contains the
3662 // problematic expression but we will warn at the return statement pointing
3663 // at the reference variable. We will later display the "trail" of
3664 // reference variables using notes.
3665 diagLoc = refVars[0]->getLocStart();
3666 diagRange = refVars[0]->getSourceRange();
3667 }
3668
3669 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3670 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3671 : diag::warn_ret_stack_addr)
3672 << DR->getDecl()->getDeclName() << diagRange;
3673 } else if (isa<BlockExpr>(stackE)) { // local block.
3674 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3675 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3676 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3677 } else { // local temporary.
3678 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
3679 : diag::warn_ret_local_temp_addr)
3680 << diagRange;
3681 }
3682
3683 // Display the "trail" of reference variables that we followed until we
3684 // found the problematic expression using notes.
3685 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
3686 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
3687 // If this var binds to another reference var, show the range of the next
3688 // var, otherwise the var binds to the problematic expression, in which case
3689 // show the range of the expression.
3690 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
3691 : stackE->getSourceRange();
3692 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
3693 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00003694 }
3695}
3696
3697/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
3698/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003699/// to a location on the stack, a local block, an address of a label, or a
3700/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00003701/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003702/// encounter a subexpression that (1) clearly does not lead to one of the
3703/// above problematic expressions (2) is something we cannot determine leads to
3704/// a problematic expression based on such local checking.
3705///
3706/// Both EvalAddr and EvalVal follow through reference variables to evaluate
3707/// the expression that they point to. Such variables are added to the
3708/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00003709///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003710/// EvalAddr processes expressions that are pointers that are used as
3711/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003712/// At the base case of the recursion is a check for the above problematic
3713/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00003714///
3715/// This implementation handles:
3716///
3717/// * pointer-to-pointer casts
3718/// * implicit conversions from array references to pointers
3719/// * taking the address of fields
3720/// * arbitrary interplay between "&" and "*" operators
3721/// * pointer arithmetic from an address of a stack variable
3722/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003723static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3724 Decl *ParentDecl) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003725 if (E->isTypeDependent())
3726 return NULL;
3727
Ted Kremenek06de2762007-08-17 16:46:58 +00003728 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00003729 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00003730 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003731 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003732 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00003733
Peter Collingbournef111d932011-04-15 00:35:48 +00003734 E = E->IgnoreParens();
3735
Ted Kremenek06de2762007-08-17 16:46:58 +00003736 // Our "symbolic interpreter" is just a dispatch off the currently
3737 // viewed AST node. We then recursively traverse the AST by calling
3738 // EvalAddr and EvalVal appropriately.
3739 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003740 case Stmt::DeclRefExprClass: {
3741 DeclRefExpr *DR = cast<DeclRefExpr>(E);
3742
3743 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3744 // If this is a reference variable, follow through to the expression that
3745 // it points to.
3746 if (V->hasLocalStorage() &&
3747 V->getType()->isReferenceType() && V->hasInit()) {
3748 // Add the reference variable to the "trail".
3749 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003750 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003751 }
3752
3753 return NULL;
3754 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003755
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003756 case Stmt::UnaryOperatorClass: {
3757 // The only unary operator that make sense to handle here
3758 // is AddrOf. All others don't make sense as pointers.
3759 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003760
John McCall2de56d12010-08-25 11:45:40 +00003761 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003762 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003763 else
Ted Kremenek06de2762007-08-17 16:46:58 +00003764 return NULL;
3765 }
Mike Stump1eb44332009-09-09 15:08:12 +00003766
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003767 case Stmt::BinaryOperatorClass: {
3768 // Handle pointer arithmetic. All other binary operators are not valid
3769 // in this context.
3770 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00003771 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00003772
John McCall2de56d12010-08-25 11:45:40 +00003773 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003774 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00003775
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003776 Expr *Base = B->getLHS();
3777
3778 // Determine which argument is the real pointer base. It could be
3779 // the RHS argument instead of the LHS.
3780 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003782 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003783 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003784 }
Steve Naroff61f40a22008-09-10 19:17:48 +00003785
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003786 // For conditional operators we need to see if either the LHS or RHS are
3787 // valid DeclRefExpr*s. If one of them is valid, we return it.
3788 case Stmt::ConditionalOperatorClass: {
3789 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003791 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003792 if (Expr *lhsExpr = C->getLHS()) {
3793 // In C++, we can have a throw-expression, which has 'void' type.
3794 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003795 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003796 return LHS;
3797 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003798
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00003799 // In C++, we can have a throw-expression, which has 'void' type.
3800 if (C->getRHS()->getType()->isVoidType())
3801 return NULL;
3802
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003803 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003804 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003805
3806 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00003807 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003808 return E; // local block.
3809 return NULL;
3810
3811 case Stmt::AddrLabelExprClass:
3812 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00003813
John McCall80ee6e82011-11-10 05:35:25 +00003814 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003815 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
3816 ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003817
Ted Kremenek54b52742008-08-07 00:49:01 +00003818 // For casts, we need to handle conversions from arrays to
3819 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00003820 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003821 case Stmt::CStyleCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003822 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8b9414e2012-02-23 23:04:32 +00003823 case Stmt::ObjCBridgedCastExprClass:
Mike Stump1eb44332009-09-09 15:08:12 +00003824 case Stmt::CXXStaticCastExprClass:
3825 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00003826 case Stmt::CXXConstCastExprClass:
3827 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8b9414e2012-02-23 23:04:32 +00003828 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3829 switch (cast<CastExpr>(E)->getCastKind()) {
3830 case CK_BitCast:
3831 case CK_LValueToRValue:
3832 case CK_NoOp:
3833 case CK_BaseToDerived:
3834 case CK_DerivedToBase:
3835 case CK_UncheckedDerivedToBase:
3836 case CK_Dynamic:
3837 case CK_CPointerToObjCPointerCast:
3838 case CK_BlockPointerToObjCPointerCast:
3839 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003840 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003841
3842 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003843 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8b9414e2012-02-23 23:04:32 +00003844
3845 default:
3846 return 0;
3847 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003848 }
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Douglas Gregor03e80032011-06-21 17:03:29 +00003850 case Stmt::MaterializeTemporaryExprClass:
3851 if (Expr *Result = EvalAddr(
3852 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003853 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003854 return Result;
3855
3856 return E;
3857
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00003858 // Everything else: we simply don't reason about them.
3859 default:
3860 return NULL;
3861 }
Ted Kremenek06de2762007-08-17 16:46:58 +00003862}
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Ted Kremenek06de2762007-08-17 16:46:58 +00003864
3865/// EvalVal - This function is complements EvalAddr in the mutual recursion.
3866/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003867static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3868 Decl *ParentDecl) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003869do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00003870 // We should only be called for evaluating non-pointer expressions, or
3871 // expressions with a pointer type that are not used as references but instead
3872 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Ted Kremenek06de2762007-08-17 16:46:58 +00003874 // Our "symbolic interpreter" is just a dispatch off the currently
3875 // viewed AST node. We then recursively traverse the AST by calling
3876 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00003877
3878 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00003879 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003880 case Stmt::ImplicitCastExprClass: {
3881 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00003882 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00003883 E = IE->getSubExpr();
3884 continue;
3885 }
3886 return NULL;
3887 }
3888
John McCall80ee6e82011-11-10 05:35:25 +00003889 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003890 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall80ee6e82011-11-10 05:35:25 +00003891
Douglas Gregora2813ce2009-10-23 18:54:35 +00003892 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003893 // When we hit a DeclRefExpr we are looking at code that refers to a
3894 // variable's name. If it's not a reference variable we check if it has
3895 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00003896 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003897
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003898 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
3899 // Check if it refers to itself, e.g. "int& i = i;".
3900 if (V == ParentDecl)
3901 return DR;
3902
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003903 if (V->hasLocalStorage()) {
3904 if (!V->getType()->isReferenceType())
3905 return DR;
3906
3907 // Reference variable, follow through to the expression that
3908 // it points to.
3909 if (V->hasInit()) {
3910 // Add the reference variable to the "trail".
3911 refVars.push_back(DR);
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003912 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003913 }
3914 }
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003915 }
Mike Stump1eb44332009-09-09 15:08:12 +00003916
Ted Kremenek06de2762007-08-17 16:46:58 +00003917 return NULL;
3918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919
Ted Kremenek06de2762007-08-17 16:46:58 +00003920 case Stmt::UnaryOperatorClass: {
3921 // The only unary operator that make sense to handle here
3922 // is Deref. All others don't resolve to a "name." This includes
3923 // handling all sorts of rvalues passed to a unary operator.
3924 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003925
John McCall2de56d12010-08-25 11:45:40 +00003926 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003927 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003928
3929 return NULL;
3930 }
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Ted Kremenek06de2762007-08-17 16:46:58 +00003932 case Stmt::ArraySubscriptExprClass: {
3933 // Array subscripts are potential references to data on the stack. We
3934 // retrieve the DeclRefExpr* for the array variable if it indeed
3935 // has local storage.
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003936 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003937 }
Mike Stump1eb44332009-09-09 15:08:12 +00003938
Ted Kremenek06de2762007-08-17 16:46:58 +00003939 case Stmt::ConditionalOperatorClass: {
3940 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003941 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00003942 ConditionalOperator *C = cast<ConditionalOperator>(E);
3943
Anders Carlsson39073232007-11-30 19:04:31 +00003944 // Handle the GNU extension for missing LHS.
3945 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003946 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson39073232007-11-30 19:04:31 +00003947 return LHS;
3948
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003949 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003950 }
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Ted Kremenek06de2762007-08-17 16:46:58 +00003952 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00003953 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00003954 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Ted Kremenek06de2762007-08-17 16:46:58 +00003956 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00003957 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00003958 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00003959
3960 // Check whether the member type is itself a reference, in which case
3961 // we're not going to refer to the member, but to what the member refers to.
3962 if (M->getMemberDecl()->getType()->isReferenceType())
3963 return NULL;
3964
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003965 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenek06de2762007-08-17 16:46:58 +00003966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Douglas Gregor03e80032011-06-21 17:03:29 +00003968 case Stmt::MaterializeTemporaryExprClass:
3969 if (Expr *Result = EvalVal(
3970 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidise720ce72012-04-30 23:23:55 +00003971 refVars, ParentDecl))
Douglas Gregor03e80032011-06-21 17:03:29 +00003972 return Result;
3973
3974 return E;
3975
Ted Kremenek06de2762007-08-17 16:46:58 +00003976 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00003977 // Check that we don't return or take the address of a reference to a
3978 // temporary. This is only useful in C++.
3979 if (!E->isTypeDependent() && E->isRValue())
3980 return E;
3981
3982 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00003983 return NULL;
3984 }
Ted Kremenek68957a92010-08-04 20:01:07 +00003985} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00003986}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003987
3988//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3989
3990/// Check for comparisons of floating point operands using != and ==.
3991/// Issue a warning if these are no self-comparisons, as they are not likely
3992/// to do what the programmer intended.
Richard Trieudd225092011-09-15 21:56:47 +00003993void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieudd225092011-09-15 21:56:47 +00003994 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3995 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00003996
3997 // Special case: check for x == x (which is OK).
3998 // Do not emit warnings for such cases.
3999 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4000 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4001 if (DRL->getDecl() == DRR->getDecl())
David Blaikie980343b2012-07-16 20:47:22 +00004002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004003
4004
Ted Kremenek1b500bb2007-11-29 00:59:04 +00004005 // Special case: check for comparisons against literals that can be exactly
4006 // represented by APFloat. In such cases, do not emit a warning. This
4007 // is a heuristic: often comparison against such literals are used to
4008 // detect if a value in a variable has not changed. This clearly can
4009 // lead to false negatives.
David Blaikie980343b2012-07-16 20:47:22 +00004010 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4011 if (FLL->isExact())
4012 return;
4013 } else
4014 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4015 if (FLR->isExact())
4016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004017
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004018 // Check for comparisons with builtin types.
David Blaikie980343b2012-07-16 20:47:22 +00004019 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4020 if (CL->isBuiltinCall())
4021 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004022
David Blaikie980343b2012-07-16 20:47:22 +00004023 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4024 if (CR->isBuiltinCall())
4025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004027 // Emit the diagnostic.
David Blaikie980343b2012-07-16 20:47:22 +00004028 Diag(Loc, diag::warn_floatingpoint_eq)
4029 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00004030}
John McCallba26e582010-01-04 23:21:16 +00004031
John McCallf2370c92010-01-06 05:24:50 +00004032//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4033//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00004034
John McCallf2370c92010-01-06 05:24:50 +00004035namespace {
John McCallba26e582010-01-04 23:21:16 +00004036
John McCallf2370c92010-01-06 05:24:50 +00004037/// Structure recording the 'active' range of an integer-valued
4038/// expression.
4039struct IntRange {
4040 /// The number of bits active in the int.
4041 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00004042
John McCallf2370c92010-01-06 05:24:50 +00004043 /// True if the int is known not to have negative values.
4044 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00004045
John McCallf2370c92010-01-06 05:24:50 +00004046 IntRange(unsigned Width, bool NonNegative)
4047 : Width(Width), NonNegative(NonNegative)
4048 {}
John McCallba26e582010-01-04 23:21:16 +00004049
John McCall1844a6e2010-11-10 23:38:19 +00004050 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00004051 static IntRange forBoolType() {
4052 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00004053 }
4054
John McCall1844a6e2010-11-10 23:38:19 +00004055 /// Returns the range of an opaque value of the given integral type.
4056 static IntRange forValueOfType(ASTContext &C, QualType T) {
4057 return forValueOfCanonicalType(C,
4058 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00004059 }
4060
John McCall1844a6e2010-11-10 23:38:19 +00004061 /// Returns the range of an opaque value of a canonical integral type.
4062 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00004063 assert(T->isCanonicalUnqualified());
4064
4065 if (const VectorType *VT = dyn_cast<VectorType>(T))
4066 T = VT->getElementType().getTypePtr();
4067 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4068 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00004069
David Majnemerf9eaf982013-06-07 22:07:20 +00004070 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00004071 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemerf9eaf982013-06-07 22:07:20 +00004072 EnumDecl *Enum = ET->getDecl();
4073 if (!Enum->isCompleteDefinition())
4074 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall091f23f2010-11-09 22:22:12 +00004075
David Majnemerf9eaf982013-06-07 22:07:20 +00004076 unsigned NumPositive = Enum->getNumPositiveBits();
4077 unsigned NumNegative = Enum->getNumNegativeBits();
John McCall323ed742010-05-06 08:58:33 +00004078
David Majnemerf9eaf982013-06-07 22:07:20 +00004079 if (NumNegative == 0)
4080 return IntRange(NumPositive, true/*NonNegative*/);
4081 else
4082 return IntRange(std::max(NumPositive + 1, NumNegative),
4083 false/*NonNegative*/);
John McCall323ed742010-05-06 08:58:33 +00004084 }
John McCallf2370c92010-01-06 05:24:50 +00004085
4086 const BuiltinType *BT = cast<BuiltinType>(T);
4087 assert(BT->isInteger());
4088
4089 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4090 }
4091
John McCall1844a6e2010-11-10 23:38:19 +00004092 /// Returns the "target" range of a canonical integral type, i.e.
4093 /// the range of values expressible in the type.
4094 ///
4095 /// This matches forValueOfCanonicalType except that enums have the
4096 /// full range of their type, not the range of their enumerators.
4097 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4098 assert(T->isCanonicalUnqualified());
4099
4100 if (const VectorType *VT = dyn_cast<VectorType>(T))
4101 T = VT->getElementType().getTypePtr();
4102 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4103 T = CT->getElementType().getTypePtr();
4104 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor69ff26b2011-09-08 23:29:05 +00004105 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall1844a6e2010-11-10 23:38:19 +00004106
4107 const BuiltinType *BT = cast<BuiltinType>(T);
4108 assert(BT->isInteger());
4109
4110 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4111 }
4112
4113 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004114 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00004115 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00004116 L.NonNegative && R.NonNegative);
4117 }
4118
John McCall1844a6e2010-11-10 23:38:19 +00004119 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00004120 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00004121 return IntRange(std::min(L.Width, R.Width),
4122 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00004123 }
4124};
4125
Ted Kremenek0692a192012-01-31 05:37:37 +00004126static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4127 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004128 if (value.isSigned() && value.isNegative())
4129 return IntRange(value.getMinSignedBits(), false);
4130
4131 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00004132 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004133
4134 // isNonNegative() just checks the sign bit without considering
4135 // signedness.
4136 return IntRange(value.getActiveBits(), true);
4137}
4138
Ted Kremenek0692a192012-01-31 05:37:37 +00004139static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4140 unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004141 if (result.isInt())
4142 return GetValueRange(C, result.getInt(), MaxWidth);
4143
4144 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00004145 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4146 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4147 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4148 R = IntRange::join(R, El);
4149 }
John McCallf2370c92010-01-06 05:24:50 +00004150 return R;
4151 }
4152
4153 if (result.isComplexInt()) {
4154 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4155 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4156 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00004157 }
4158
4159 // This can happen with lossless casts to intptr_t of "based" lvalues.
4160 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00004161 // FIXME: The only reason we need to pass the type in here is to get
4162 // the sign right on this one case. It would be nice if APValue
4163 // preserved this.
Eli Friedman65639282012-01-04 23:13:47 +00004164 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004165 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall51313c32010-01-04 23:31:57 +00004166}
John McCallf2370c92010-01-06 05:24:50 +00004167
Eli Friedman09bddcf2013-07-08 20:20:06 +00004168static QualType GetExprType(Expr *E) {
4169 QualType Ty = E->getType();
4170 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4171 Ty = AtomicRHS->getValueType();
4172 return Ty;
4173}
4174
John McCallf2370c92010-01-06 05:24:50 +00004175/// Pseudo-evaluate the given integer expression, estimating the
4176/// range of values it might take.
4177///
4178/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek0692a192012-01-31 05:37:37 +00004179static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCallf2370c92010-01-06 05:24:50 +00004180 E = E->IgnoreParens();
4181
4182 // Try a full evaluation first.
4183 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004184 if (E->EvaluateAsRValue(result, C))
Eli Friedman09bddcf2013-07-08 20:20:06 +00004185 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00004186
4187 // I think we only want to look through implicit casts here; if the
4188 // user has an explicit widening cast, we should treat the value as
4189 // being of the new, wider type.
4190 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedmanb17ee5b2011-12-15 02:41:52 +00004191 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCallf2370c92010-01-06 05:24:50 +00004192 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4193
Eli Friedman09bddcf2013-07-08 20:20:06 +00004194 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCallf2370c92010-01-06 05:24:50 +00004195
John McCall2de56d12010-08-25 11:45:40 +00004196 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00004197
John McCallf2370c92010-01-06 05:24:50 +00004198 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00004199 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00004200 return OutputTypeRange;
4201
4202 IntRange SubRange
4203 = GetExprRange(C, CE->getSubExpr(),
4204 std::min(MaxWidth, OutputTypeRange.Width));
4205
4206 // Bail out if the subexpr's range is as wide as the cast type.
4207 if (SubRange.Width >= OutputTypeRange.Width)
4208 return OutputTypeRange;
4209
4210 // Otherwise, we take the smaller width, and we're non-negative if
4211 // either the output type or the subexpr is.
4212 return IntRange(SubRange.Width,
4213 SubRange.NonNegative || OutputTypeRange.NonNegative);
4214 }
4215
4216 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4217 // If we can fold the condition, just take that operand.
4218 bool CondResult;
4219 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4220 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4221 : CO->getFalseExpr(),
4222 MaxWidth);
4223
4224 // Otherwise, conservatively merge.
4225 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4226 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4227 return IntRange::join(L, R);
4228 }
4229
4230 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4231 switch (BO->getOpcode()) {
4232
4233 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00004234 case BO_LAnd:
4235 case BO_LOr:
4236 case BO_LT:
4237 case BO_GT:
4238 case BO_LE:
4239 case BO_GE:
4240 case BO_EQ:
4241 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00004242 return IntRange::forBoolType();
4243
John McCall862ff872011-07-13 06:35:24 +00004244 // The type of the assignments is the type of the LHS, so the RHS
4245 // is not necessarily the same type.
John McCall2de56d12010-08-25 11:45:40 +00004246 case BO_MulAssign:
4247 case BO_DivAssign:
4248 case BO_RemAssign:
4249 case BO_AddAssign:
4250 case BO_SubAssign:
John McCall862ff872011-07-13 06:35:24 +00004251 case BO_XorAssign:
4252 case BO_OrAssign:
4253 // TODO: bitfields?
Eli Friedman09bddcf2013-07-08 20:20:06 +00004254 return IntRange::forValueOfType(C, GetExprType(E));
John McCallc0cd21d2010-02-23 19:22:29 +00004255
John McCall862ff872011-07-13 06:35:24 +00004256 // Simple assignments just pass through the RHS, which will have
4257 // been coerced to the LHS type.
4258 case BO_Assign:
4259 // TODO: bitfields?
4260 return GetExprRange(C, BO->getRHS(), MaxWidth);
4261
John McCallf2370c92010-01-06 05:24:50 +00004262 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004263 case BO_PtrMemD:
4264 case BO_PtrMemI:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004265 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004266
John McCall60fad452010-01-06 22:07:33 +00004267 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00004268 case BO_And:
4269 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00004270 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4271 GetExprRange(C, BO->getRHS(), MaxWidth));
4272
John McCallf2370c92010-01-06 05:24:50 +00004273 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00004274 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00004275 // ...except that we want to treat '1 << (blah)' as logically
4276 // positive. It's an important idiom.
4277 if (IntegerLiteral *I
4278 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4279 if (I->getValue() == 1) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004280 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall3aae6092010-04-07 01:14:35 +00004281 return IntRange(R.Width, /*NonNegative*/ true);
4282 }
4283 }
4284 // fallthrough
4285
John McCall2de56d12010-08-25 11:45:40 +00004286 case BO_ShlAssign:
Eli Friedman09bddcf2013-07-08 20:20:06 +00004287 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004288
John McCall60fad452010-01-06 22:07:33 +00004289 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00004290 case BO_Shr:
4291 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00004292 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4293
4294 // If the shift amount is a positive constant, drop the width by
4295 // that much.
4296 llvm::APSInt shift;
4297 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4298 shift.isNonNegative()) {
4299 unsigned zext = shift.getZExtValue();
4300 if (zext >= L.Width)
4301 L.Width = (L.NonNegative ? 0 : 1);
4302 else
4303 L.Width -= zext;
4304 }
4305
4306 return L;
4307 }
4308
4309 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00004310 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00004311 return GetExprRange(C, BO->getRHS(), MaxWidth);
4312
John McCall60fad452010-01-06 22:07:33 +00004313 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00004314 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00004315 if (BO->getLHS()->getType()->isPointerType())
Eli Friedman09bddcf2013-07-08 20:20:06 +00004316 return IntRange::forValueOfType(C, GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004317 break;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00004318
John McCall00fe7612011-07-14 22:39:48 +00004319 // The width of a division result is mostly determined by the size
4320 // of the LHS.
4321 case BO_Div: {
4322 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004323 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004324 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4325
4326 // If the divisor is constant, use that.
4327 llvm::APSInt divisor;
4328 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4329 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4330 if (log2 >= L.Width)
4331 L.Width = (L.NonNegative ? 0 : 1);
4332 else
4333 L.Width = std::min(L.Width - log2, MaxWidth);
4334 return L;
4335 }
4336
4337 // Otherwise, just use the LHS's width.
4338 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4339 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4340 }
4341
4342 // The result of a remainder can't be larger than the result of
4343 // either side.
4344 case BO_Rem: {
4345 // Don't 'pre-truncate' the operands.
Eli Friedman09bddcf2013-07-08 20:20:06 +00004346 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall00fe7612011-07-14 22:39:48 +00004347 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4348 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4349
4350 IntRange meet = IntRange::meet(L, R);
4351 meet.Width = std::min(meet.Width, MaxWidth);
4352 return meet;
4353 }
4354
4355 // The default behavior is okay for these.
4356 case BO_Mul:
4357 case BO_Add:
4358 case BO_Xor:
4359 case BO_Or:
John McCallf2370c92010-01-06 05:24:50 +00004360 break;
4361 }
4362
John McCall00fe7612011-07-14 22:39:48 +00004363 // The default case is to treat the operation as if it were closed
4364 // on the narrowest type that encompasses both operands.
John McCallf2370c92010-01-06 05:24:50 +00004365 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4366 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4367 return IntRange::join(L, R);
4368 }
4369
4370 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4371 switch (UO->getOpcode()) {
4372 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00004373 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00004374 return IntRange::forBoolType();
4375
4376 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00004377 case UO_Deref:
4378 case UO_AddrOf: // should be impossible
Eli Friedman09bddcf2013-07-08 20:20:06 +00004379 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004380
4381 default:
4382 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4383 }
4384 }
4385
John McCall993f43f2013-05-06 21:39:12 +00004386 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004387 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor5e9ebb32011-05-21 16:28:01 +00004388 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCallf2370c92010-01-06 05:24:50 +00004389
Eli Friedman09bddcf2013-07-08 20:20:06 +00004390 return IntRange::forValueOfType(C, GetExprType(E));
John McCallf2370c92010-01-06 05:24:50 +00004391}
John McCall51313c32010-01-04 23:31:57 +00004392
Ted Kremenek0692a192012-01-31 05:37:37 +00004393static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedman09bddcf2013-07-08 20:20:06 +00004394 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCall323ed742010-05-06 08:58:33 +00004395}
4396
John McCall51313c32010-01-04 23:31:57 +00004397/// Checks whether the given value, which currently has the given
4398/// source semantics, has the same value when coerced through the
4399/// target semantics.
Ted Kremenek0692a192012-01-31 05:37:37 +00004400static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4401 const llvm::fltSemantics &Src,
4402 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004403 llvm::APFloat truncated = value;
4404
4405 bool ignored;
4406 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4407 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4408
4409 return truncated.bitwiseIsEqual(value);
4410}
4411
4412/// Checks whether the given value, which currently has the given
4413/// source semantics, has the same value when coerced through the
4414/// target semantics.
4415///
4416/// The value might be a vector of floats (or a complex number).
Ted Kremenek0692a192012-01-31 05:37:37 +00004417static bool IsSameFloatAfterCast(const APValue &value,
4418 const llvm::fltSemantics &Src,
4419 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00004420 if (value.isFloat())
4421 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4422
4423 if (value.isVector()) {
4424 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4425 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4426 return false;
4427 return true;
4428 }
4429
4430 assert(value.isComplexFloat());
4431 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4432 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4433}
4434
Ted Kremenek0692a192012-01-31 05:37:37 +00004435static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00004436
Ted Kremeneke3b159c2010-09-23 21:43:44 +00004437static bool IsZero(Sema &S, Expr *E) {
4438 // Suppress cases where we are comparing against an enum constant.
4439 if (const DeclRefExpr *DR =
4440 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4441 if (isa<EnumConstantDecl>(DR->getDecl()))
4442 return false;
4443
4444 // Suppress cases where the '0' value is expanded from a macro.
4445 if (E->getLocStart().isMacroID())
4446 return false;
4447
John McCall323ed742010-05-06 08:58:33 +00004448 llvm::APSInt Value;
4449 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4450}
4451
John McCall372e1032010-10-06 00:25:24 +00004452static bool HasEnumType(Expr *E) {
4453 // Strip off implicit integral promotions.
4454 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004455 if (ICE->getCastKind() != CK_IntegralCast &&
4456 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00004457 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00004458 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00004459 }
4460
4461 return E->getType()->isEnumeralType();
4462}
4463
Ted Kremenek0692a192012-01-31 05:37:37 +00004464static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00004465 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00004466 if (E->isValueDependent())
4467 return;
4468
John McCall2de56d12010-08-25 11:45:40 +00004469 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004470 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004471 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004472 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004473 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00004474 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004475 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00004476 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004477 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004478 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004479 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004480 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00004481 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00004482 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00004483 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00004484 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4485 }
4486}
4487
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004488static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004489 Expr *Constant, Expr *Other,
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004490 llvm::APSInt Value,
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004491 bool RhsConstant) {
Richard Trieu526e6272012-11-14 22:50:24 +00004492 // 0 values are handled later by CheckTrivialUnsignedComparison().
4493 if (Value == 0)
4494 return;
4495
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004496 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004497 QualType OtherT = Other->getType();
4498 QualType ConstantT = Constant->getType();
Richard Trieu526e6272012-11-14 22:50:24 +00004499 QualType CommonT = E->getLHS()->getType();
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004500 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004501 return;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004502 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004503 && "comparison with non-integer type");
Richard Trieu526e6272012-11-14 22:50:24 +00004504
4505 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu526e6272012-11-14 22:50:24 +00004506 bool CommonSigned = CommonT->isSignedIntegerType();
4507
4508 bool EqualityOnly = false;
4509
4510 // TODO: Investigate using GetExprRange() to get tighter bounds on
4511 // on the bit ranges.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004512 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu526e6272012-11-14 22:50:24 +00004513 unsigned OtherWidth = OtherRange.Width;
4514
4515 if (CommonSigned) {
4516 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedmand87de7b2012-11-30 23:09:29 +00004517 if (!OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004518 // Check that the constant is representable in type OtherT.
4519 if (ConstantSigned) {
4520 if (OtherWidth >= Value.getMinSignedBits())
4521 return;
4522 } else { // !ConstantSigned
4523 if (OtherWidth >= Value.getActiveBits() + 1)
4524 return;
4525 }
4526 } else { // !OtherSigned
4527 // Check that the constant is representable in type OtherT.
4528 // Negative values are out of range.
4529 if (ConstantSigned) {
4530 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4531 return;
4532 } else { // !ConstantSigned
4533 if (OtherWidth >= Value.getActiveBits())
4534 return;
4535 }
4536 }
4537 } else { // !CommonSigned
Eli Friedmand87de7b2012-11-30 23:09:29 +00004538 if (OtherRange.NonNegative) {
Richard Trieu526e6272012-11-14 22:50:24 +00004539 if (OtherWidth >= Value.getActiveBits())
4540 return;
Eli Friedmand87de7b2012-11-30 23:09:29 +00004541 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu526e6272012-11-14 22:50:24 +00004542 // Check to see if the constant is representable in OtherT.
4543 if (OtherWidth > Value.getActiveBits())
4544 return;
4545 // Check to see if the constant is equivalent to a negative value
4546 // cast to CommonT.
4547 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu5d1cf4f2012-11-15 03:43:50 +00004548 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu526e6272012-11-14 22:50:24 +00004549 return;
4550 // The constant value rests between values that OtherT can represent after
4551 // conversion. Relational comparison still works, but equality
4552 // comparisons will be tautological.
4553 EqualityOnly = true;
4554 } else { // OtherSigned && ConstantSigned
4555 assert(0 && "Two signed types converted to unsigned types.");
4556 }
4557 }
4558
4559 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4560
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004561 bool IsTrue = true;
Richard Trieu526e6272012-11-14 22:50:24 +00004562 if (op == BO_EQ || op == BO_NE) {
4563 IsTrue = op == BO_NE;
4564 } else if (EqualityOnly) {
4565 return;
4566 } else if (RhsConstant) {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004567 if (op == BO_GT || op == BO_GE)
Richard Trieu526e6272012-11-14 22:50:24 +00004568 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004569 else // op == BO_LT || op == BO_LE
Richard Trieu526e6272012-11-14 22:50:24 +00004570 IsTrue = PositiveConstant;
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004571 } else {
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004572 if (op == BO_LT || op == BO_LE)
Richard Trieu526e6272012-11-14 22:50:24 +00004573 IsTrue = !PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004574 else // op == BO_GT || op == BO_GE
Richard Trieu526e6272012-11-14 22:50:24 +00004575 IsTrue = PositiveConstant;
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004576 }
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004577
4578 // If this is a comparison to an enum constant, include that
4579 // constant in the diagnostic.
4580 const EnumConstantDecl *ED = 0;
4581 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4582 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4583
4584 SmallString<64> PrettySourceValue;
4585 llvm::raw_svector_ostream OS(PrettySourceValue);
4586 if (ED)
Ted Kremenek9de50942013-03-15 22:02:46 +00004587 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004588 else
4589 OS << Value;
4590
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004591 S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
Ted Kremenek7adf3a92013-03-15 21:50:10 +00004592 << OS.str() << OtherT << IsTrue
Richard Trieu526e6272012-11-14 22:50:24 +00004593 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004594}
4595
John McCall323ed742010-05-06 08:58:33 +00004596/// Analyze the operands of the given comparison. Implements the
4597/// fallback case from AnalyzeComparison.
Ted Kremenek0692a192012-01-31 05:37:37 +00004598static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00004599 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4600 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00004601}
John McCall51313c32010-01-04 23:31:57 +00004602
John McCallba26e582010-01-04 23:21:16 +00004603/// \brief Implements -Wsign-compare.
4604///
Richard Trieudd225092011-09-15 21:56:47 +00004605/// \param E the binary operator to check for warnings
Ted Kremenek0692a192012-01-31 05:37:37 +00004606static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCall323ed742010-05-06 08:58:33 +00004607 // The type the comparison is being performed in.
4608 QualType T = E->getLHS()->getType();
4609 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4610 && "comparison with mismatched types");
Fariborz Jahanianab4702f2012-09-18 17:46:26 +00004611 if (E->isValueDependent())
4612 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004613
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004614 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4615 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004616
4617 bool IsComparisonConstant = false;
4618
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004619 // Check whether an integer constant comparison results in a value
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004620 // of 'true' or 'false'.
4621 if (T->isIntegralType(S.Context)) {
4622 llvm::APSInt RHSValue;
4623 bool IsRHSIntegralLiteral =
4624 RHS->isIntegerConstantExpr(RHSValue, S.Context);
4625 llvm::APSInt LHSValue;
4626 bool IsLHSIntegralLiteral =
4627 LHS->isIntegerConstantExpr(LHSValue, S.Context);
4628 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4629 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4630 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4631 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4632 else
4633 IsComparisonConstant =
4634 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahaniana193f202012-09-20 19:36:41 +00004635 } else if (!T->hasUnsignedIntegerRepresentation())
4636 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004637
John McCall323ed742010-05-06 08:58:33 +00004638 // We don't do anything special if this isn't an unsigned integral
4639 // comparison: we're only interested in integral comparisons, and
4640 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00004641 //
4642 // We also don't care about value-dependent expressions or expressions
4643 // whose result is a constant.
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004644 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCall323ed742010-05-06 08:58:33 +00004645 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanian15a93562012-09-18 17:37:21 +00004646
John McCall323ed742010-05-06 08:58:33 +00004647 // Check to see if one of the (unmodified) operands is of different
4648 // signedness.
4649 Expr *signedOperand, *unsignedOperand;
Richard Trieudd225092011-09-15 21:56:47 +00004650 if (LHS->getType()->hasSignedIntegerRepresentation()) {
4651 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00004652 "unsigned comparison between two signed integer expressions?");
Richard Trieudd225092011-09-15 21:56:47 +00004653 signedOperand = LHS;
4654 unsignedOperand = RHS;
4655 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4656 signedOperand = RHS;
4657 unsignedOperand = LHS;
John McCallba26e582010-01-04 23:21:16 +00004658 } else {
John McCall323ed742010-05-06 08:58:33 +00004659 CheckTrivialUnsignedComparison(S, E);
4660 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004661 }
4662
John McCall323ed742010-05-06 08:58:33 +00004663 // Otherwise, calculate the effective range of the signed operand.
4664 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00004665
John McCall323ed742010-05-06 08:58:33 +00004666 // Go ahead and analyze implicit conversions in the operands. Note
4667 // that we skip the implicit conversions on both sides.
Richard Trieudd225092011-09-15 21:56:47 +00004668 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
4669 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00004670
John McCall323ed742010-05-06 08:58:33 +00004671 // If the signed range is non-negative, -Wsign-compare won't fire,
4672 // but we should still check for comparisons which are always true
4673 // or false.
4674 if (signedRange.NonNegative)
4675 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00004676
4677 // For (in)equality comparisons, if the unsigned operand is a
4678 // constant which cannot collide with a overflowed signed operand,
4679 // then reinterpreting the signed operand as unsigned will not
4680 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00004681 if (E->isEqualityOp()) {
4682 unsigned comparisonWidth = S.Context.getIntWidth(T);
4683 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00004684
John McCall323ed742010-05-06 08:58:33 +00004685 // We should never be unable to prove that the unsigned operand is
4686 // non-negative.
4687 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
4688
4689 if (unsignedRange.Width < comparisonWidth)
4690 return;
4691 }
4692
Douglas Gregor6d3b93d2012-05-01 01:53:49 +00004693 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4694 S.PDiag(diag::warn_mixed_sign_comparison)
4695 << LHS->getType() << RHS->getType()
4696 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallba26e582010-01-04 23:21:16 +00004697}
4698
John McCall15d7d122010-11-11 03:21:53 +00004699/// Analyzes an attempt to assign the given value to a bitfield.
4700///
4701/// Returns true if there was something fishy about the attempt.
Ted Kremenek0692a192012-01-31 05:37:37 +00004702static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
4703 SourceLocation InitLoc) {
John McCall15d7d122010-11-11 03:21:53 +00004704 assert(Bitfield->isBitField());
4705 if (Bitfield->isInvalidDecl())
4706 return false;
4707
John McCall91b60142010-11-11 05:33:51 +00004708 // White-list bool bitfields.
4709 if (Bitfield->getType()->isBooleanType())
4710 return false;
4711
Douglas Gregor46ff3032011-02-04 13:09:01 +00004712 // Ignore value- or type-dependent expressions.
4713 if (Bitfield->getBitWidth()->isValueDependent() ||
4714 Bitfield->getBitWidth()->isTypeDependent() ||
4715 Init->isValueDependent() ||
4716 Init->isTypeDependent())
4717 return false;
4718
John McCall15d7d122010-11-11 03:21:53 +00004719 Expr *OriginalInit = Init->IgnoreParenImpCasts();
4720
Richard Smith80d4b552011-12-28 19:48:30 +00004721 llvm::APSInt Value;
4722 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall15d7d122010-11-11 03:21:53 +00004723 return false;
4724
John McCall15d7d122010-11-11 03:21:53 +00004725 unsigned OriginalWidth = Value.getBitWidth();
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004726 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall15d7d122010-11-11 03:21:53 +00004727
4728 if (OriginalWidth <= FieldWidth)
4729 return false;
4730
Eli Friedman3a643af2012-01-26 23:11:39 +00004731 // Compute the value which the bitfield will contain.
Jay Foad9f71a8f2010-12-07 08:25:34 +00004732 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedman3a643af2012-01-26 23:11:39 +00004733 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall15d7d122010-11-11 03:21:53 +00004734
Eli Friedman3a643af2012-01-26 23:11:39 +00004735 // Check whether the stored value is equal to the original value.
4736 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieue1ecdc12012-07-23 20:21:35 +00004737 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall15d7d122010-11-11 03:21:53 +00004738 return false;
4739
Eli Friedman3a643af2012-01-26 23:11:39 +00004740 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedman34ff0622012-02-02 00:40:20 +00004741 // therefore don't strictly fit into a signed bitfield of width 1.
4742 if (FieldWidth == 1 && Value == 1)
Eli Friedman3a643af2012-01-26 23:11:39 +00004743 return false;
4744
John McCall15d7d122010-11-11 03:21:53 +00004745 std::string PrettyValue = Value.toString(10);
4746 std::string PrettyTrunc = TruncatedValue.toString(10);
4747
4748 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
4749 << PrettyValue << PrettyTrunc << OriginalInit->getType()
4750 << Init->getSourceRange();
4751
4752 return true;
4753}
4754
John McCallbeb22aa2010-11-09 23:24:47 +00004755/// Analyze the given simple or compound assignment for warning-worthy
4756/// operations.
Ted Kremenek0692a192012-01-31 05:37:37 +00004757static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCallbeb22aa2010-11-09 23:24:47 +00004758 // Just recurse on the LHS.
4759 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4760
4761 // We want to recurse on the RHS as normal unless we're assigning to
4762 // a bitfield.
John McCall993f43f2013-05-06 21:39:12 +00004763 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004764 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall15d7d122010-11-11 03:21:53 +00004765 E->getOperatorLoc())) {
4766 // Recurse, ignoring any implicit conversions on the RHS.
4767 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
4768 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00004769 }
4770 }
4771
4772 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4773}
4774
John McCall51313c32010-01-04 23:31:57 +00004775/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004776static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004777 SourceLocation CContext, unsigned diag,
4778 bool pruneControlFlow = false) {
4779 if (pruneControlFlow) {
4780 S.DiagRuntimeBehavior(E->getExprLoc(), E,
4781 S.PDiag(diag)
4782 << SourceType << T << E->getSourceRange()
4783 << SourceRange(CContext));
4784 return;
4785 }
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00004786 S.Diag(E->getExprLoc(), diag)
4787 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
4788}
4789
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004790/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek0692a192012-01-31 05:37:37 +00004791static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaksc36bedc2012-02-01 19:08:57 +00004792 SourceLocation CContext, unsigned diag,
4793 bool pruneControlFlow = false) {
4794 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruthe1b02e02011-04-05 06:47:57 +00004795}
4796
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004797/// Diagnose an implicit cast from a literal expression. Does not warn when the
4798/// cast wouldn't lose information.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004799void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
4800 SourceLocation CContext) {
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004801 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruthf65076e2011-04-10 08:36:24 +00004802 bool isExact = false;
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004803 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +00004804 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
4805 T->hasUnsignedIntegerRepresentation());
4806 if (Value.convertToInteger(IntegerValue,
Chandler Carruthf65076e2011-04-10 08:36:24 +00004807 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004808 == llvm::APFloat::opOK && isExact)
Chandler Carruthf65076e2011-04-10 08:36:24 +00004809 return;
4810
David Blaikiebe0ee872012-05-15 16:56:36 +00004811 SmallString<16> PrettySourceValue;
4812 Value.toString(PrettySourceValue);
David Blaikiede7e7b82012-05-15 17:18:27 +00004813 SmallString<16> PrettyTargetValue;
David Blaikiebe0ee872012-05-15 16:56:36 +00004814 if (T->isSpecificBuiltinType(BuiltinType::Bool))
4815 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
4816 else
David Blaikiede7e7b82012-05-15 17:18:27 +00004817 IntegerValue.toString(PrettyTargetValue);
David Blaikiebe0ee872012-05-15 16:56:36 +00004818
Matt Beaumont-Gay9ce63772011-10-14 15:36:25 +00004819 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikiebe0ee872012-05-15 16:56:36 +00004820 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
4821 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruthf65076e2011-04-10 08:36:24 +00004822}
4823
John McCall091f23f2010-11-09 22:22:12 +00004824std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
4825 if (!Range.Width) return "0";
4826
4827 llvm::APSInt ValueInRange = Value;
4828 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00004829 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00004830 return ValueInRange.toString(10);
4831}
4832
Hans Wennborg88617a22012-08-28 15:44:30 +00004833static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
4834 if (!isa<ImplicitCastExpr>(Ex))
4835 return false;
4836
4837 Expr *InnerE = Ex->IgnoreParenImpCasts();
4838 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
4839 const Type *Source =
4840 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
4841 if (Target->isDependentType())
4842 return false;
4843
4844 const BuiltinType *FloatCandidateBT =
4845 dyn_cast<BuiltinType>(ToBool ? Source : Target);
4846 const Type *BoolCandidateType = ToBool ? Target : Source;
4847
4848 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
4849 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
4850}
4851
4852void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
4853 SourceLocation CC) {
4854 unsigned NumArgs = TheCall->getNumArgs();
4855 for (unsigned i = 0; i < NumArgs; ++i) {
4856 Expr *CurrA = TheCall->getArg(i);
4857 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
4858 continue;
4859
4860 bool IsSwapped = ((i > 0) &&
4861 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
4862 IsSwapped |= ((i < (NumArgs - 1)) &&
4863 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
4864 if (IsSwapped) {
4865 // Warn on this floating-point to bool conversion.
4866 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
4867 CurrA->getType(), CC,
4868 diag::warn_impcast_floating_point_to_bool);
4869 }
4870 }
4871}
4872
John McCall323ed742010-05-06 08:58:33 +00004873void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00004874 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00004875 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00004876
John McCall323ed742010-05-06 08:58:33 +00004877 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
4878 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
4879 if (Source == Target) return;
4880 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00004881
Chandler Carruth108f7562011-07-26 05:40:03 +00004882 // If the conversion context location is invalid don't complain. We also
4883 // don't want to emit a warning if the issue occurs from the expansion of
4884 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
4885 // delay this check as long as possible. Once we detect we are in that
4886 // scenario, we just return.
Ted Kremenekef9ff882011-03-10 20:03:42 +00004887 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00004888 return;
4889
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004890 // Diagnose implicit casts to bool.
4891 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
4892 if (isa<StringLiteral>(E))
4893 // Warn on string literal to bool. Checks for string literals in logical
4894 // expressions, for instances, assert(0 && "error here"), is prevented
4895 // by a check in AnalyzeImplicitConversions().
4896 return DiagnoseImpCast(S, E, T, CC,
4897 diag::warn_impcast_string_literal_to_bool);
Lang Hamese14ca9f2011-12-05 20:49:50 +00004898 if (Source->isFunctionType()) {
4899 // Warn on function to bool. Checks free functions and static member
4900 // functions. Weakly imported functions are excluded from the check,
4901 // since it's common to test their value to check whether the linker
4902 // found a definition for them.
4903 ValueDecl *D = 0;
4904 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
4905 D = R->getDecl();
4906 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
4907 D = M->getMemberDecl();
4908 }
4909
4910 if (D && !D->isWeak()) {
Richard Trieu26b45d82011-12-06 04:48:01 +00004911 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
4912 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
4913 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie2def7732011-12-09 21:42:37 +00004914 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
4915 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
4916 QualType ReturnType;
4917 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiec8fa5252013-06-21 23:54:45 +00004918 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie2def7732011-12-09 21:42:37 +00004919 if (!ReturnType.isNull()
4920 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
4921 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
4922 << FixItHint::CreateInsertion(
4923 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu26b45d82011-12-06 04:48:01 +00004924 return;
4925 }
Lang Hamese14ca9f2011-12-05 20:49:50 +00004926 }
4927 }
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00004928 }
John McCall51313c32010-01-04 23:31:57 +00004929
4930 // Strip vector types.
4931 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004932 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004933 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004934 return;
John McCallb4eb64d2010-10-08 02:01:28 +00004935 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004936 }
Chris Lattnerb792b302011-06-14 04:51:15 +00004937
4938 // If the vector cast is cast between two vectors of the same size, it is
4939 // a bitcast, not a conversion.
4940 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
4941 return;
John McCall51313c32010-01-04 23:31:57 +00004942
4943 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
4944 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
4945 }
4946
4947 // Strip complex types.
4948 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00004949 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004950 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004951 return;
4952
John McCallb4eb64d2010-10-08 02:01:28 +00004953 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00004954 }
John McCall51313c32010-01-04 23:31:57 +00004955
4956 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4957 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4958 }
4959
4960 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4961 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4962
4963 // If the source is floating point...
4964 if (SourceBT && SourceBT->isFloatingPoint()) {
4965 // ...and the target is floating point...
4966 if (TargetBT && TargetBT->isFloatingPoint()) {
4967 // ...then warn if we're dropping FP rank.
4968
4969 // Builtin FP kinds are ordered by increasing FP rank.
4970 if (SourceBT->getKind() > TargetBT->getKind()) {
4971 // Don't warn about float constants that are precisely
4972 // representable in the target type.
4973 Expr::EvalResult result;
Richard Smith51f47082011-10-29 00:50:52 +00004974 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00004975 // Value might be a float, a float vector, or a float complex.
4976 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00004977 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4978 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00004979 return;
4980 }
4981
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004982 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004983 return;
4984
John McCallb4eb64d2010-10-08 02:01:28 +00004985 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00004986 }
4987 return;
4988 }
4989
Ted Kremenekef9ff882011-03-10 20:03:42 +00004990 // If the target is integral, always warn.
David Blaikiebe0ee872012-05-15 16:56:36 +00004991 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00004992 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00004993 return;
4994
Chandler Carrutha5b93322011-02-17 11:05:49 +00004995 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay634c8af2011-09-08 22:30:47 +00004996 // We also want to warn on, e.g., "int i = -1.234"
4997 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4998 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4999 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5000
Chandler Carruthf65076e2011-04-10 08:36:24 +00005001 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5002 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00005003 } else {
5004 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5005 }
5006 }
John McCall51313c32010-01-04 23:31:57 +00005007
Hans Wennborg88617a22012-08-28 15:44:30 +00005008 // If the target is bool, warn if expr is a function or method call.
5009 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5010 isa<CallExpr>(E)) {
5011 // Check last argument of function call to see if it is an
5012 // implicit cast from a type matching the type the result
5013 // is being cast to.
5014 CallExpr *CEx = cast<CallExpr>(E);
5015 unsigned NumArgs = CEx->getNumArgs();
5016 if (NumArgs > 0) {
5017 Expr *LastA = CEx->getArg(NumArgs - 1);
5018 Expr *InnerE = LastA->IgnoreParenImpCasts();
5019 const Type *InnerType =
5020 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5021 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5022 // Warn on this floating-point to bool conversion
5023 DiagnoseImpCast(S, E, T, CC,
5024 diag::warn_impcast_floating_point_to_bool);
5025 }
5026 }
5027 }
John McCall51313c32010-01-04 23:31:57 +00005028 return;
5029 }
5030
Richard Trieu1838ca52011-05-29 19:59:02 +00005031 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikieb26331b2012-06-19 21:19:06 +00005032 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiee81b43b2012-11-08 00:41:20 +00005033 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikie896c7dd2013-02-16 00:56:22 +00005034 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieb1360492012-03-16 20:30:12 +00005035 SourceLocation Loc = E->getSourceRange().getBegin();
5036 if (Loc.isMacroID())
5037 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie9fb1ac52012-05-15 21:57:38 +00005038 if (!Loc.isMacroID() || CC.isMacroID())
5039 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5040 << T << clang::SourceRange(CC)
5041 << FixItHint::CreateReplacement(Loc, S.getFixItZeroLiteralForType(T));
Richard Trieu1838ca52011-05-29 19:59:02 +00005042 }
5043
David Blaikieb26331b2012-06-19 21:19:06 +00005044 if (!Source->isIntegerType() || !Target->isIntegerType())
5045 return;
5046
David Blaikiebe0ee872012-05-15 16:56:36 +00005047 // TODO: remove this early return once the false positives for constant->bool
5048 // in templates, macros, etc, are reduced or removed.
5049 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5050 return;
5051
John McCall323ed742010-05-06 08:58:33 +00005052 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00005053 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00005054
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005055 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer25ffbef2013-03-28 19:07:11 +00005056 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005057 // TODO: this should happen for bitfield stores, too.
5058 llvm::APSInt Value(32);
5059 if (E->isIntegerConstantExpr(Value, S.Context)) {
5060 if (S.SourceMgr.isInSystemMacro(CC))
5061 return;
5062
John McCall091f23f2010-11-09 22:22:12 +00005063 std::string PrettySourceValue = Value.toString(10);
5064 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005065
Ted Kremenek5e745da2011-10-22 02:37:33 +00005066 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5067 S.PDiag(diag::warn_impcast_integer_precision_constant)
5068 << PrettySourceValue << PrettyTargetValue
5069 << E->getType() << T << E->getSourceRange()
5070 << clang::SourceRange(CC));
John McCall091f23f2010-11-09 22:22:12 +00005071 return;
5072 }
5073
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005074 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5075 if (S.SourceMgr.isInSystemMacro(CC))
5076 return;
5077
David Blaikie37050842012-04-12 22:40:54 +00005078 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaksc36bedc2012-02-01 19:08:57 +00005079 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5080 /* pruneControlFlow */ true);
John McCallb4eb64d2010-10-08 02:01:28 +00005081 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00005082 }
5083
5084 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5085 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5086 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00005087
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005088 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005089 return;
5090
John McCall323ed742010-05-06 08:58:33 +00005091 unsigned DiagID = diag::warn_impcast_integer_sign;
5092
5093 // Traditionally, gcc has warned about this under -Wsign-compare.
5094 // We also want to warn about it in -Wconversion.
5095 // So if -Wconversion is off, use a completely identical diagnostic
5096 // in the sign-compare group.
5097 // The conditional-checking code will
5098 if (ICContext) {
5099 DiagID = diag::warn_impcast_integer_sign_conditional;
5100 *ICContext = true;
5101 }
5102
John McCallb4eb64d2010-10-08 02:01:28 +00005103 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00005104 }
5105
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005106 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005107 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5108 // type, to give us better diagnostics.
5109 QualType SourceType = E->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +00005110 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005111 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5112 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5113 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5114 SourceType = S.Context.getTypeDeclType(Enum);
5115 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5116 }
5117 }
5118
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005119 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5120 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall83972f12013-03-09 00:54:27 +00005121 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5122 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00005123 SourceEnum != TargetEnum) {
Matt Beaumont-Gayd87a0cd2012-01-06 22:43:58 +00005124 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenekef9ff882011-03-10 20:03:42 +00005125 return;
5126
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00005127 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005128 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00005129 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00005130
John McCall51313c32010-01-04 23:31:57 +00005131 return;
5132}
5133
David Blaikie9fb1ac52012-05-15 21:57:38 +00005134void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5135 SourceLocation CC, QualType T);
John McCall323ed742010-05-06 08:58:33 +00005136
5137void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00005138 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00005139 E = E->IgnoreParenImpCasts();
5140
5141 if (isa<ConditionalOperator>(E))
David Blaikie9fb1ac52012-05-15 21:57:38 +00005142 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCall323ed742010-05-06 08:58:33 +00005143
John McCallb4eb64d2010-10-08 02:01:28 +00005144 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005145 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005146 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00005147 return;
5148}
5149
David Blaikie9fb1ac52012-05-15 21:57:38 +00005150void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5151 SourceLocation CC, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00005152 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00005153
5154 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00005155 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5156 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005157
5158 // If -Wconversion would have warned about either of the candidates
5159 // for a signedness conversion to the context type...
5160 if (!Suspicious) return;
5161
5162 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005163 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5164 CC))
John McCall323ed742010-05-06 08:58:33 +00005165 return;
5166
John McCall323ed742010-05-06 08:58:33 +00005167 // ...then check whether it would have warned about either of the
5168 // candidates for a signedness conversion to the condition type.
Richard Trieu52541612011-07-21 02:46:28 +00005169 if (E->getType() == T) return;
5170
5171 Suspicious = false;
5172 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5173 E->getType(), CC, &Suspicious);
5174 if (!Suspicious)
5175 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00005176 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00005177}
5178
5179/// AnalyzeImplicitConversions - Find and report any interesting
5180/// implicit conversions in the given expression. There are a couple
5181/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005182void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005183 QualType T = OrigE->getType();
5184 Expr *E = OrigE->IgnoreParenImpCasts();
5185
Douglas Gregorf8b6e152011-10-10 17:38:18 +00005186 if (E->isTypeDependent() || E->isValueDependent())
5187 return;
5188
John McCall323ed742010-05-06 08:58:33 +00005189 // For conditional operators, we analyze the arguments as if they
5190 // were being fed directly into the output.
5191 if (isa<ConditionalOperator>(E)) {
5192 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie9fb1ac52012-05-15 21:57:38 +00005193 CheckConditionalOperator(S, CO, CC, T);
John McCall323ed742010-05-06 08:58:33 +00005194 return;
5195 }
5196
Hans Wennborg88617a22012-08-28 15:44:30 +00005197 // Check implicit argument conversions for function calls.
5198 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5199 CheckImplicitArgumentConversions(S, Call, CC);
5200
John McCall323ed742010-05-06 08:58:33 +00005201 // Go ahead and check any implicit conversions we might have skipped.
5202 // The non-canonical typecheck is just an optimization;
5203 // CheckImplicitConversion will filter out dead implicit conversions.
5204 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00005205 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00005206
5207 // Now continue drilling into this expression.
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005208
5209 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005210 if (POE->getResultExpr())
5211 E = POE->getResultExpr();
Fariborz Jahanian6f2a9fa2013-05-15 19:03:04 +00005212 }
5213
Fariborz Jahaniana1bfe1c2013-05-15 22:25:03 +00005214 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5215 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5216
John McCall323ed742010-05-06 08:58:33 +00005217 // Skip past explicit casts.
5218 if (isa<ExplicitCastExpr>(E)) {
5219 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00005220 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005221 }
5222
John McCallbeb22aa2010-11-09 23:24:47 +00005223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5224 // Do a somewhat different check with comparison operators.
5225 if (BO->isComparisonOp())
5226 return AnalyzeComparison(S, BO);
5227
Timur Iskhodzhanovdff2be82013-03-29 00:22:03 +00005228 // And with simple assignments.
5229 if (BO->getOpcode() == BO_Assign)
John McCallbeb22aa2010-11-09 23:24:47 +00005230 return AnalyzeAssignment(S, BO);
5231 }
John McCall323ed742010-05-06 08:58:33 +00005232
5233 // These break the otherwise-useful invariant below. Fortunately,
5234 // we don't really need to recurse into them, because any internal
5235 // expressions should have been analyzed already when they were
5236 // built into statements.
5237 if (isa<StmtExpr>(E)) return;
5238
5239 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005240 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00005241
5242 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00005243 CC = E->getExprLoc();
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005244 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5245 bool IsLogicalOperator = BO && BO->isLogicalOp();
5246 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor54042f12012-02-09 10:18:50 +00005247 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor503384f2012-02-09 00:47:04 +00005248 if (!ChildExpr)
5249 continue;
5250
Richard Trieuf1f8b1a2011-09-23 20:10:00 +00005251 if (IsLogicalOperator &&
5252 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5253 // Ignore checking string literals that are in logical operators.
5254 continue;
5255 AnalyzeImplicitConversions(S, ChildExpr, CC);
5256 }
John McCall323ed742010-05-06 08:58:33 +00005257}
5258
5259} // end anonymous namespace
5260
5261/// Diagnoses "dangerous" implicit conversions within the given
5262/// expression (which is a full expression). Implements -Wconversion
5263/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00005264///
5265/// \param CC the "context" location of the implicit conversion, i.e.
5266/// the most location of the syntactic entity requiring the implicit
5267/// conversion
5268void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00005269 // Don't diagnose in unevaluated contexts.
David Blaikie71f55f72012-08-06 22:47:24 +00005270 if (isUnevaluatedContext())
John McCall323ed742010-05-06 08:58:33 +00005271 return;
5272
5273 // Don't diagnose for value- or type-dependent expressions.
5274 if (E->isTypeDependent() || E->isValueDependent())
5275 return;
5276
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005277 // Check for array bounds violations in cases where the check isn't triggered
5278 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5279 // ArraySubscriptExpr is on the RHS of a variable initialization.
5280 CheckArrayAccess(E);
5281
John McCallb4eb64d2010-10-08 02:01:28 +00005282 // This is not the right CC for (e.g.) a variable initialization.
5283 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00005284}
5285
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005286/// Diagnose when expression is an integer constant expression and its evaluation
5287/// results in integer overflow
5288void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanian1fd8d462013-03-15 20:47:07 +00005289 if (isa<BinaryOperator>(E->IgnoreParens())) {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005290 llvm::SmallVector<PartialDiagnosticAt, 4> Diags;
5291 E->EvaluateForOverflow(Context, &Diags);
5292 }
5293}
5294
Richard Smith6c3af3d2013-01-17 01:17:56 +00005295namespace {
5296/// \brief Visitor for expressions which looks for unsequenced operations on the
5297/// same object.
5298class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smith0c0b3902013-06-30 10:40:20 +00005299 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5300
Richard Smith6c3af3d2013-01-17 01:17:56 +00005301 /// \brief A tree of sequenced regions within an expression. Two regions are
5302 /// unsequenced if one is an ancestor or a descendent of the other. When we
5303 /// finish processing an expression with sequencing, such as a comma
5304 /// expression, we fold its tree nodes into its parent, since they are
5305 /// unsequenced with respect to nodes we will visit later.
5306 class SequenceTree {
5307 struct Value {
5308 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5309 unsigned Parent : 31;
5310 bool Merged : 1;
5311 };
5312 llvm::SmallVector<Value, 8> Values;
5313
5314 public:
5315 /// \brief A region within an expression which may be sequenced with respect
5316 /// to some other region.
5317 class Seq {
5318 explicit Seq(unsigned N) : Index(N) {}
5319 unsigned Index;
5320 friend class SequenceTree;
5321 public:
5322 Seq() : Index(0) {}
5323 };
5324
5325 SequenceTree() { Values.push_back(Value(0)); }
5326 Seq root() const { return Seq(0); }
5327
5328 /// \brief Create a new sequence of operations, which is an unsequenced
5329 /// subset of \p Parent. This sequence of operations is sequenced with
5330 /// respect to other children of \p Parent.
5331 Seq allocate(Seq Parent) {
5332 Values.push_back(Value(Parent.Index));
5333 return Seq(Values.size() - 1);
5334 }
5335
5336 /// \brief Merge a sequence of operations into its parent.
5337 void merge(Seq S) {
5338 Values[S.Index].Merged = true;
5339 }
5340
5341 /// \brief Determine whether two operations are unsequenced. This operation
5342 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5343 /// should have been merged into its parent as appropriate.
5344 bool isUnsequenced(Seq Cur, Seq Old) {
5345 unsigned C = representative(Cur.Index);
5346 unsigned Target = representative(Old.Index);
5347 while (C >= Target) {
5348 if (C == Target)
5349 return true;
5350 C = Values[C].Parent;
5351 }
5352 return false;
5353 }
5354
5355 private:
5356 /// \brief Pick a representative for a sequence.
5357 unsigned representative(unsigned K) {
5358 if (Values[K].Merged)
5359 // Perform path compression as we go.
5360 return Values[K].Parent = representative(Values[K].Parent);
5361 return K;
5362 }
5363 };
5364
5365 /// An object for which we can track unsequenced uses.
5366 typedef NamedDecl *Object;
5367
5368 /// Different flavors of object usage which we track. We only track the
5369 /// least-sequenced usage of each kind.
5370 enum UsageKind {
5371 /// A read of an object. Multiple unsequenced reads are OK.
5372 UK_Use,
5373 /// A modification of an object which is sequenced before the value
Richard Smith418dd3e2013-06-26 23:16:51 +00005374 /// computation of the expression, such as ++n in C++.
Richard Smith6c3af3d2013-01-17 01:17:56 +00005375 UK_ModAsValue,
5376 /// A modification of an object which is not sequenced before the value
5377 /// computation of the expression, such as n++.
5378 UK_ModAsSideEffect,
5379
5380 UK_Count = UK_ModAsSideEffect + 1
5381 };
5382
5383 struct Usage {
5384 Usage() : Use(0), Seq() {}
5385 Expr *Use;
5386 SequenceTree::Seq Seq;
5387 };
5388
5389 struct UsageInfo {
5390 UsageInfo() : Diagnosed(false) {}
5391 Usage Uses[UK_Count];
5392 /// Have we issued a diagnostic for this variable already?
5393 bool Diagnosed;
5394 };
5395 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5396
5397 Sema &SemaRef;
5398 /// Sequenced regions within the expression.
5399 SequenceTree Tree;
5400 /// Declaration modifications and references which we have seen.
5401 UsageInfoMap UsageMap;
5402 /// The region we are currently within.
5403 SequenceTree::Seq Region;
5404 /// Filled in with declarations which were modified as a side-effect
5405 /// (that is, post-increment operations).
5406 llvm::SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smith1a2dcd52013-01-17 23:18:09 +00005407 /// Expressions to check later. We defer checking these to reduce
5408 /// stack usage.
5409 llvm::SmallVectorImpl<Expr*> &WorkList;
Richard Smith6c3af3d2013-01-17 01:17:56 +00005410
5411 /// RAII object wrapping the visitation of a sequenced subexpression of an
5412 /// expression. At the end of this process, the side-effects of the evaluation
5413 /// become sequenced with respect to the value computation of the result, so
5414 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5415 /// UK_ModAsValue.
5416 struct SequencedSubexpression {
5417 SequencedSubexpression(SequenceChecker &Self)
5418 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5419 Self.ModAsSideEffect = &ModAsSideEffect;
5420 }
5421 ~SequencedSubexpression() {
5422 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5423 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5424 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5425 Self.addUsage(U, ModAsSideEffect[I].first,
5426 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5427 }
5428 Self.ModAsSideEffect = OldModAsSideEffect;
5429 }
5430
5431 SequenceChecker &Self;
5432 llvm::SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5433 llvm::SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5434 };
5435
Richard Smith67470052013-06-20 22:21:56 +00005436 /// RAII object wrapping the visitation of a subexpression which we might
5437 /// choose to evaluate as a constant. If any subexpression is evaluated and
5438 /// found to be non-constant, this allows us to suppress the evaluation of
5439 /// the outer expression.
5440 class EvaluationTracker {
5441 public:
5442 EvaluationTracker(SequenceChecker &Self)
5443 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5444 Self.EvalTracker = this;
5445 }
5446 ~EvaluationTracker() {
5447 Self.EvalTracker = Prev;
5448 if (Prev)
5449 Prev->EvalOK &= EvalOK;
5450 }
5451
5452 bool evaluate(const Expr *E, bool &Result) {
5453 if (!EvalOK || E->isValueDependent())
5454 return false;
5455 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5456 return EvalOK;
5457 }
5458
5459 private:
5460 SequenceChecker &Self;
5461 EvaluationTracker *Prev;
5462 bool EvalOK;
5463 } *EvalTracker;
5464
Richard Smith6c3af3d2013-01-17 01:17:56 +00005465 /// \brief Find the object which is produced by the specified expression,
5466 /// if any.
5467 Object getObject(Expr *E, bool Mod) const {
5468 E = E->IgnoreParenCasts();
5469 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5470 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5471 return getObject(UO->getSubExpr(), Mod);
5472 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5473 if (BO->getOpcode() == BO_Comma)
5474 return getObject(BO->getRHS(), Mod);
5475 if (Mod && BO->isAssignmentOp())
5476 return getObject(BO->getLHS(), Mod);
5477 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5478 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5479 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5480 return ME->getMemberDecl();
5481 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5482 // FIXME: If this is a reference, map through to its value.
5483 return DRE->getDecl();
5484 return 0;
5485 }
5486
5487 /// \brief Note that an object was modified or used by an expression.
5488 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5489 Usage &U = UI.Uses[UK];
5490 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5491 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5492 ModAsSideEffect->push_back(std::make_pair(O, U));
5493 U.Use = Ref;
5494 U.Seq = Region;
5495 }
5496 }
5497 /// \brief Check whether a modification or use conflicts with a prior usage.
5498 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5499 bool IsModMod) {
5500 if (UI.Diagnosed)
5501 return;
5502
5503 const Usage &U = UI.Uses[OtherKind];
5504 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5505 return;
5506
5507 Expr *Mod = U.Use;
5508 Expr *ModOrUse = Ref;
5509 if (OtherKind == UK_Use)
5510 std::swap(Mod, ModOrUse);
5511
5512 SemaRef.Diag(Mod->getExprLoc(),
5513 IsModMod ? diag::warn_unsequenced_mod_mod
5514 : diag::warn_unsequenced_mod_use)
5515 << O << SourceRange(ModOrUse->getExprLoc());
5516 UI.Diagnosed = true;
5517 }
5518
5519 void notePreUse(Object O, Expr *Use) {
5520 UsageInfo &U = UsageMap[O];
5521 // Uses conflict with other modifications.
5522 checkUsage(O, U, Use, UK_ModAsValue, false);
5523 }
5524 void notePostUse(Object O, Expr *Use) {
5525 UsageInfo &U = UsageMap[O];
5526 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5527 addUsage(U, O, Use, UK_Use);
5528 }
5529
5530 void notePreMod(Object O, Expr *Mod) {
5531 UsageInfo &U = UsageMap[O];
5532 // Modifications conflict with other modifications and with uses.
5533 checkUsage(O, U, Mod, UK_ModAsValue, true);
5534 checkUsage(O, U, Mod, UK_Use, false);
5535 }
5536 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5537 UsageInfo &U = UsageMap[O];
5538 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5539 addUsage(U, O, Use, UK);
5540 }
5541
5542public:
Richard Smith1a2dcd52013-01-17 23:18:09 +00005543 SequenceChecker(Sema &S, Expr *E,
5544 llvm::SmallVectorImpl<Expr*> &WorkList)
Richard Smith0c0b3902013-06-30 10:40:20 +00005545 : Base(S.Context), SemaRef(S), Region(Tree.root()),
5546 ModAsSideEffect(0), WorkList(WorkList), EvalTracker(0) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005547 Visit(E);
5548 }
5549
5550 void VisitStmt(Stmt *S) {
5551 // Skip all statements which aren't expressions for now.
5552 }
5553
5554 void VisitExpr(Expr *E) {
5555 // By default, just recurse to evaluated subexpressions.
Richard Smith0c0b3902013-06-30 10:40:20 +00005556 Base::VisitStmt(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005557 }
5558
5559 void VisitCastExpr(CastExpr *E) {
5560 Object O = Object();
5561 if (E->getCastKind() == CK_LValueToRValue)
5562 O = getObject(E->getSubExpr(), false);
5563
5564 if (O)
5565 notePreUse(O, E);
5566 VisitExpr(E);
5567 if (O)
5568 notePostUse(O, E);
5569 }
5570
5571 void VisitBinComma(BinaryOperator *BO) {
5572 // C++11 [expr.comma]p1:
5573 // Every value computation and side effect associated with the left
5574 // expression is sequenced before every value computation and side
5575 // effect associated with the right expression.
5576 SequenceTree::Seq LHS = Tree.allocate(Region);
5577 SequenceTree::Seq RHS = Tree.allocate(Region);
5578 SequenceTree::Seq OldRegion = Region;
5579
5580 {
5581 SequencedSubexpression SeqLHS(*this);
5582 Region = LHS;
5583 Visit(BO->getLHS());
5584 }
5585
5586 Region = RHS;
5587 Visit(BO->getRHS());
5588
5589 Region = OldRegion;
5590
5591 // Forget that LHS and RHS are sequenced. They are both unsequenced
5592 // with respect to other stuff.
5593 Tree.merge(LHS);
5594 Tree.merge(RHS);
5595 }
5596
5597 void VisitBinAssign(BinaryOperator *BO) {
5598 // The modification is sequenced after the value computation of the LHS
5599 // and RHS, so check it before inspecting the operands and update the
5600 // map afterwards.
5601 Object O = getObject(BO->getLHS(), true);
5602 if (!O)
5603 return VisitExpr(BO);
5604
5605 notePreMod(O, BO);
5606
5607 // C++11 [expr.ass]p7:
5608 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5609 // only once.
5610 //
5611 // Therefore, for a compound assignment operator, O is considered used
5612 // everywhere except within the evaluation of E1 itself.
5613 if (isa<CompoundAssignOperator>(BO))
5614 notePreUse(O, BO);
5615
5616 Visit(BO->getLHS());
5617
5618 if (isa<CompoundAssignOperator>(BO))
5619 notePostUse(O, BO);
5620
5621 Visit(BO->getRHS());
5622
Richard Smith418dd3e2013-06-26 23:16:51 +00005623 // C++11 [expr.ass]p1:
5624 // the assignment is sequenced [...] before the value computation of the
5625 // assignment expression.
5626 // C11 6.5.16/3 has no such rule.
5627 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5628 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005629 }
5630 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5631 VisitBinAssign(CAO);
5632 }
5633
5634 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5635 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5636 void VisitUnaryPreIncDec(UnaryOperator *UO) {
5637 Object O = getObject(UO->getSubExpr(), true);
5638 if (!O)
5639 return VisitExpr(UO);
5640
5641 notePreMod(O, UO);
5642 Visit(UO->getSubExpr());
Richard Smith418dd3e2013-06-26 23:16:51 +00005643 // C++11 [expr.pre.incr]p1:
5644 // the expression ++x is equivalent to x+=1
5645 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5646 : UK_ModAsSideEffect);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005647 }
5648
5649 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5650 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5651 void VisitUnaryPostIncDec(UnaryOperator *UO) {
5652 Object O = getObject(UO->getSubExpr(), true);
5653 if (!O)
5654 return VisitExpr(UO);
5655
5656 notePreMod(O, UO);
5657 Visit(UO->getSubExpr());
5658 notePostMod(O, UO, UK_ModAsSideEffect);
5659 }
5660
5661 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
5662 void VisitBinLOr(BinaryOperator *BO) {
5663 // The side-effects of the LHS of an '&&' are sequenced before the
5664 // value computation of the RHS, and hence before the value computation
5665 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
5666 // as if they were unconditionally sequenced.
Richard Smith67470052013-06-20 22:21:56 +00005667 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005668 {
5669 SequencedSubexpression Sequenced(*this);
5670 Visit(BO->getLHS());
5671 }
5672
5673 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005674 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005675 if (!Result)
5676 Visit(BO->getRHS());
5677 } else {
5678 // Check for unsequenced operations in the RHS, treating it as an
5679 // entirely separate evaluation.
5680 //
5681 // FIXME: If there are operations in the RHS which are unsequenced
5682 // with respect to operations outside the RHS, and those operations
5683 // are unconditionally evaluated, diagnose them.
Richard Smith1a2dcd52013-01-17 23:18:09 +00005684 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005685 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005686 }
5687 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith67470052013-06-20 22:21:56 +00005688 EvaluationTracker Eval(*this);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005689 {
5690 SequencedSubexpression Sequenced(*this);
5691 Visit(BO->getLHS());
5692 }
5693
5694 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005695 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith995e4a72013-01-17 22:06:26 +00005696 if (Result)
5697 Visit(BO->getRHS());
5698 } else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005699 WorkList.push_back(BO->getRHS());
Richard Smith995e4a72013-01-17 22:06:26 +00005700 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005701 }
5702
5703 // Only visit the condition, unless we can be sure which subexpression will
5704 // be chosen.
5705 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith67470052013-06-20 22:21:56 +00005706 EvaluationTracker Eval(*this);
Richard Smith418dd3e2013-06-26 23:16:51 +00005707 {
5708 SequencedSubexpression Sequenced(*this);
5709 Visit(CO->getCond());
5710 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005711
5712 bool Result;
Richard Smith67470052013-06-20 22:21:56 +00005713 if (Eval.evaluate(CO->getCond(), Result))
Richard Smith6c3af3d2013-01-17 01:17:56 +00005714 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005715 else {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005716 WorkList.push_back(CO->getTrueExpr());
5717 WorkList.push_back(CO->getFalseExpr());
Richard Smith995e4a72013-01-17 22:06:26 +00005718 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005719 }
5720
Richard Smith0c0b3902013-06-30 10:40:20 +00005721 void VisitCallExpr(CallExpr *CE) {
5722 // C++11 [intro.execution]p15:
5723 // When calling a function [...], every value computation and side effect
5724 // associated with any argument expression, or with the postfix expression
5725 // designating the called function, is sequenced before execution of every
5726 // expression or statement in the body of the function [and thus before
5727 // the value computation of its result].
5728 SequencedSubexpression Sequenced(*this);
5729 Base::VisitCallExpr(CE);
5730
5731 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
5732 }
5733
Richard Smith6c3af3d2013-01-17 01:17:56 +00005734 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smith0c0b3902013-06-30 10:40:20 +00005735 // This is a call, so all subexpressions are sequenced before the result.
5736 SequencedSubexpression Sequenced(*this);
5737
Richard Smith6c3af3d2013-01-17 01:17:56 +00005738 if (!CCE->isListInitialization())
5739 return VisitExpr(CCE);
5740
5741 // In C++11, list initializations are sequenced.
5742 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5743 SequenceTree::Seq Parent = Region;
5744 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
5745 E = CCE->arg_end();
5746 I != E; ++I) {
5747 Region = Tree.allocate(Parent);
5748 Elts.push_back(Region);
5749 Visit(*I);
5750 }
5751
5752 // Forget that the initializers are sequenced.
5753 Region = Parent;
5754 for (unsigned I = 0; I < Elts.size(); ++I)
5755 Tree.merge(Elts[I]);
5756 }
5757
5758 void VisitInitListExpr(InitListExpr *ILE) {
5759 if (!SemaRef.getLangOpts().CPlusPlus11)
5760 return VisitExpr(ILE);
5761
5762 // In C++11, list initializations are sequenced.
5763 llvm::SmallVector<SequenceTree::Seq, 32> Elts;
5764 SequenceTree::Seq Parent = Region;
5765 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
5766 Expr *E = ILE->getInit(I);
5767 if (!E) continue;
5768 Region = Tree.allocate(Parent);
5769 Elts.push_back(Region);
5770 Visit(E);
5771 }
5772
5773 // Forget that the initializers are sequenced.
5774 Region = Parent;
5775 for (unsigned I = 0; I < Elts.size(); ++I)
5776 Tree.merge(Elts[I]);
5777 }
5778};
5779}
5780
5781void Sema::CheckUnsequencedOperations(Expr *E) {
Richard Smith1a2dcd52013-01-17 23:18:09 +00005782 llvm::SmallVector<Expr*, 8> WorkList;
5783 WorkList.push_back(E);
5784 while (!WorkList.empty()) {
5785 Expr *Item = WorkList.back();
5786 WorkList.pop_back();
5787 SequenceChecker(*this, Item, WorkList);
5788 }
Richard Smith6c3af3d2013-01-17 01:17:56 +00005789}
5790
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005791void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
5792 bool IsConstexpr) {
Richard Smith6c3af3d2013-01-17 01:17:56 +00005793 CheckImplicitConversions(E, CheckLoc);
5794 CheckUnsequencedOperations(E);
Fariborz Jahanianad48a502013-01-24 22:11:45 +00005795 if (!IsConstexpr && !E->isValueDependent())
5796 CheckForIntOverflow(E);
Richard Smith6c3af3d2013-01-17 01:17:56 +00005797}
5798
John McCall15d7d122010-11-11 03:21:53 +00005799void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
5800 FieldDecl *BitField,
5801 Expr *Init) {
5802 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
5803}
5804
Mike Stumpf8c49212010-01-21 03:59:47 +00005805/// CheckParmsForFunctionDef - Check that the parameters of the given
5806/// function are appropriate for the definition of a function. This
5807/// takes care of any checks that cannot be performed on the
5808/// declaration itself, e.g., that the types of each of the function
5809/// parameters are complete.
Reid Kleckner8c0501c2013-06-24 14:38:26 +00005810bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
5811 ParmVarDecl *const *PEnd,
Douglas Gregor82aa7132010-11-01 18:37:59 +00005812 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005813 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00005814 for (; P != PEnd; ++P) {
5815 ParmVarDecl *Param = *P;
5816
Mike Stumpf8c49212010-01-21 03:59:47 +00005817 // C99 6.7.5.3p4: the parameters in a parameter type list in a
5818 // function declarator that is part of a function definition of
5819 // that function shall not have incomplete type.
5820 //
5821 // This is also C++ [dcl.fct]p6.
5822 if (!Param->isInvalidDecl() &&
5823 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00005824 diag::err_typecheck_decl_incomplete_type)) {
Mike Stumpf8c49212010-01-21 03:59:47 +00005825 Param->setInvalidDecl();
5826 HasInvalidParm = true;
5827 }
5828
5829 // C99 6.9.1p5: If the declarator includes a parameter type list, the
5830 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00005831 if (CheckParameterNames &&
5832 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00005833 !Param->isImplicit() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00005834 !getLangOpts().CPlusPlus)
Mike Stumpf8c49212010-01-21 03:59:47 +00005835 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00005836
5837 // C99 6.7.5.3p12:
5838 // If the function declarator is not part of a definition of that
5839 // function, parameters may have incomplete type and may use the [*]
5840 // notation in their sequences of declarator specifiers to specify
5841 // variable length array types.
5842 QualType PType = Param->getOriginalType();
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005843 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigd17e3402010-02-01 05:02:49 +00005844 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitfc093362013-03-01 21:41:22 +00005845 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigd17e3402010-02-01 05:02:49 +00005846 // information is added for it.
5847 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005848 break;
Sam Weinigd17e3402010-02-01 05:02:49 +00005849 }
Fariborz Jahaniand237d2e2013-04-29 22:01:25 +00005850 PType= AT->getElementType();
Sam Weinigd17e3402010-02-01 05:02:49 +00005851 }
Reid Kleckner9b601952013-06-21 12:45:15 +00005852
5853 // MSVC destroys objects passed by value in the callee. Therefore a
5854 // function definition which takes such a parameter must be able to call the
5855 // object's destructor.
5856 if (getLangOpts().CPlusPlus &&
5857 Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
5858 if (const RecordType *RT = Param->getType()->getAs<RecordType>())
5859 FinalizeVarWithDestructor(Param, RT);
5860 }
Mike Stumpf8c49212010-01-21 03:59:47 +00005861 }
5862
5863 return HasInvalidParm;
5864}
John McCallb7f4ffe2010-08-12 21:44:57 +00005865
5866/// CheckCastAlign - Implements -Wcast-align, which warns when a
5867/// pointer cast increases the alignment requirements.
5868void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
5869 // This is actually a lot of work to potentially be doing on every
5870 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00005871 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
5872 TRange.getBegin())
David Blaikied6471f72011-09-25 23:23:43 +00005873 == DiagnosticsEngine::Ignored)
John McCallb7f4ffe2010-08-12 21:44:57 +00005874 return;
5875
5876 // Ignore dependent types.
5877 if (T->isDependentType() || Op->getType()->isDependentType())
5878 return;
5879
5880 // Require that the destination be a pointer type.
5881 const PointerType *DestPtr = T->getAs<PointerType>();
5882 if (!DestPtr) return;
5883
5884 // If the destination has alignment 1, we're done.
5885 QualType DestPointee = DestPtr->getPointeeType();
5886 if (DestPointee->isIncompleteType()) return;
5887 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
5888 if (DestAlign.isOne()) return;
5889
5890 // Require that the source be a pointer type.
5891 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
5892 if (!SrcPtr) return;
5893 QualType SrcPointee = SrcPtr->getPointeeType();
5894
5895 // Whitelist casts from cv void*. We already implicitly
5896 // whitelisted casts to cv void*, since they have alignment 1.
5897 // Also whitelist casts involving incomplete types, which implicitly
5898 // includes 'void'.
5899 if (SrcPointee->isIncompleteType()) return;
5900
5901 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
5902 if (SrcAlign >= DestAlign) return;
5903
5904 Diag(TRange.getBegin(), diag::warn_cast_align)
5905 << Op->getType() << T
5906 << static_cast<unsigned>(SrcAlign.getQuantity())
5907 << static_cast<unsigned>(DestAlign.getQuantity())
5908 << TRange << Op->getSourceRange();
5909}
5910
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005911static const Type* getElementType(const Expr *BaseExpr) {
5912 const Type* EltType = BaseExpr->getType().getTypePtr();
5913 if (EltType->isAnyPointerType())
5914 return EltType->getPointeeType().getTypePtr();
5915 else if (EltType->isArrayType())
5916 return EltType->getBaseElementTypeUnsafe();
5917 return EltType;
5918}
5919
Chandler Carruthc2684342011-08-05 09:10:50 +00005920/// \brief Check whether this array fits the idiom of a size-one tail padded
5921/// array member of a struct.
5922///
5923/// We avoid emitting out-of-bounds access warnings for such arrays as they are
5924/// commonly used to emulate flexible arrays in C89 code.
5925static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
5926 const NamedDecl *ND) {
5927 if (Size != 1 || !ND) return false;
5928
5929 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
5930 if (!FD) return false;
5931
5932 // Don't consider sizes resulting from macro expansions or template argument
5933 // substitution to form C89 tail-padded arrays.
Sean Callanand2cf3482012-05-04 18:22:53 +00005934
5935 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005936 while (TInfo) {
5937 TypeLoc TL = TInfo->getTypeLoc();
5938 // Look through typedefs.
David Blaikie39e6ab42013-02-18 22:06:02 +00005939 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
5940 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005941 TInfo = TDL->getTypeSourceInfo();
5942 continue;
5943 }
David Blaikie39e6ab42013-02-18 22:06:02 +00005944 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
5945 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier5e253012013-02-06 00:58:34 +00005946 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
5947 return false;
5948 }
Ted Kremenek00e1f6f2012-05-09 05:35:08 +00005949 break;
Sean Callanand2cf3482012-05-04 18:22:53 +00005950 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005951
5952 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gay381711c2011-11-29 22:43:53 +00005953 if (!RD) return false;
5954 if (RD->isUnion()) return false;
5955 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5956 if (!CRD->isStandardLayout()) return false;
5957 }
Chandler Carruthc2684342011-08-05 09:10:50 +00005958
Benjamin Kramer22d4fed2011-08-06 03:04:42 +00005959 // See if this is the last field decl in the record.
5960 const Decl *D = FD;
5961 while ((D = D->getNextDeclInContext()))
5962 if (isa<FieldDecl>(D))
5963 return false;
5964 return true;
Chandler Carruthc2684342011-08-05 09:10:50 +00005965}
5966
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005967void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005968 const ArraySubscriptExpr *ASE,
Richard Smith25b009a2011-12-16 19:31:14 +00005969 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman92b670e2012-02-27 21:21:40 +00005970 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005971 if (IndexExpr->isValueDependent())
5972 return;
5973
Matt Beaumont-Gay8ef8f432011-12-12 22:35:02 +00005974 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005975 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00005976 const ConstantArrayType *ArrayTy =
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005977 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00005978 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00005979 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00005980
Chandler Carruth34064582011-02-17 20:55:08 +00005981 llvm::APSInt index;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00005982 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00005983 return;
Richard Smith25b009a2011-12-16 19:31:14 +00005984 if (IndexNegated)
5985 index = -index;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00005986
Chandler Carruthba447122011-08-05 08:07:29 +00005987 const NamedDecl *ND = NULL;
Chandler Carruthba447122011-08-05 08:07:29 +00005988 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
5989 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruthc2684342011-08-05 09:10:50 +00005990 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruthba447122011-08-05 08:07:29 +00005991 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruthba447122011-08-05 08:07:29 +00005992
Ted Kremenek9e060ca2011-02-23 23:06:04 +00005993 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00005994 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00005995 if (!size.isStrictlyPositive())
5996 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00005997
5998 const Type* BaseType = getElementType(BaseExpr);
Nico Weberde5998f2011-09-17 22:59:41 +00005999 if (BaseType != EffectiveType) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006000 // Make sure we're comparing apples to apples when comparing index to size
6001 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6002 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhraind10f4bc2011-08-10 19:47:25 +00006003 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhrain18f16972011-08-10 18:49:28 +00006004 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006005 if (ptrarith_typesize != array_typesize) {
6006 // There's a cast to a different size type involved
6007 uint64_t ratio = array_typesize / ptrarith_typesize;
6008 // TODO: Be smarter about handling cases where array_typesize is not a
6009 // multiple of ptrarith_typesize
6010 if (ptrarith_typesize * ratio == array_typesize)
6011 size *= llvm::APInt(size.getBitWidth(), ratio);
6012 }
6013 }
6014
Chandler Carruth34064582011-02-17 20:55:08 +00006015 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006016 index = index.zext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006017 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman92b670e2012-02-27 21:21:40 +00006018 size = size.zext(index.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00006019
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006020 // For array subscripting the index must be less than size, but for pointer
6021 // arithmetic also allow the index (offset) to be equal to size since
6022 // computing the next address after the end of the array is legal and
6023 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman92b670e2012-02-27 21:21:40 +00006024 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruthba447122011-08-05 08:07:29 +00006025 return;
6026
6027 // Also don't warn for arrays of size 1 which are members of some
6028 // structure. These are often used to approximate flexible arrays in C89
6029 // code.
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006030 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00006031 return;
Chandler Carruth34064582011-02-17 20:55:08 +00006032
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006033 // Suppress the warning if the subscript expression (as identified by the
6034 // ']' location) and the index expression are both from macro expansions
6035 // within a system header.
6036 if (ASE) {
6037 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6038 ASE->getRBracketLoc());
6039 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6040 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6041 IndexExpr->getLocStart());
6042 if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
6043 return;
6044 }
6045 }
6046
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006047 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006048 if (ASE)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006049 DiagID = diag::warn_array_index_exceeds_bounds;
6050
6051 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6052 PDiag(DiagID) << index.toString(10, true)
6053 << size.toString(10, true)
6054 << (unsigned)size.getLimitedValue(~0U)
6055 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00006056 } else {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006057 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006058 if (!ASE) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006059 DiagID = diag::warn_ptr_arith_precedes_bounds;
6060 if (index.isNegative()) index = -index;
6061 }
6062
6063 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6064 PDiag(DiagID) << index.toString(10, true)
6065 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006066 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00006067
Matt Beaumont-Gaycfbc5b52011-11-29 19:27:11 +00006068 if (!ND) {
6069 // Try harder to find a NamedDecl to point at in the note.
6070 while (const ArraySubscriptExpr *ASE =
6071 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6072 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6073 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6074 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6075 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6076 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6077 }
6078
Chandler Carruth35001ca2011-02-17 21:10:52 +00006079 if (ND)
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006080 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6081 PDiag(diag::note_array_index_out_of_bounds)
6082 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00006083}
6084
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006085void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006086 int AllowOnePastEnd = 0;
6087 while (expr) {
6088 expr = expr->IgnoreParenImpCasts();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006089 switch (expr->getStmtClass()) {
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006090 case Stmt::ArraySubscriptExprClass: {
6091 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay80fb7dd2011-12-14 16:02:15 +00006092 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006093 AllowOnePastEnd > 0);
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006094 return;
Kaelyn Uhraind6c88652011-08-05 23:18:04 +00006095 }
6096 case Stmt::UnaryOperatorClass: {
6097 // Only unwrap the * and & unary operators
6098 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6099 expr = UO->getSubExpr();
6100 switch (UO->getOpcode()) {
6101 case UO_AddrOf:
6102 AllowOnePastEnd++;
6103 break;
6104 case UO_Deref:
6105 AllowOnePastEnd--;
6106 break;
6107 default:
6108 return;
6109 }
6110 break;
6111 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006112 case Stmt::ConditionalOperatorClass: {
6113 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6114 if (const Expr *lhs = cond->getLHS())
6115 CheckArrayAccess(lhs);
6116 if (const Expr *rhs = cond->getRHS())
6117 CheckArrayAccess(rhs);
6118 return;
6119 }
6120 default:
6121 return;
6122 }
Peter Collingbournef111d932011-04-15 00:35:48 +00006123 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00006124}
John McCallf85e1932011-06-15 23:02:42 +00006125
6126//===--- CHECK: Objective-C retain cycles ----------------------------------//
6127
6128namespace {
6129 struct RetainCycleOwner {
6130 RetainCycleOwner() : Variable(0), Indirect(false) {}
6131 VarDecl *Variable;
6132 SourceRange Range;
6133 SourceLocation Loc;
6134 bool Indirect;
6135
6136 void setLocsFrom(Expr *e) {
6137 Loc = e->getExprLoc();
6138 Range = e->getSourceRange();
6139 }
6140 };
6141}
6142
6143/// Consider whether capturing the given variable can possibly lead to
6144/// a retain cycle.
6145static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledruf3477c12012-09-27 10:16:10 +00006146 // In ARC, it's captured strongly iff the variable has __strong
John McCallf85e1932011-06-15 23:02:42 +00006147 // lifetime. In MRR, it's captured strongly if the variable is
6148 // __block and has an appropriate type.
6149 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6150 return false;
6151
6152 owner.Variable = var;
Jordan Rosee10f4d32012-09-15 02:48:31 +00006153 if (ref)
6154 owner.setLocsFrom(ref);
John McCallf85e1932011-06-15 23:02:42 +00006155 return true;
6156}
6157
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006158static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCallf85e1932011-06-15 23:02:42 +00006159 while (true) {
6160 e = e->IgnoreParens();
6161 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6162 switch (cast->getCastKind()) {
6163 case CK_BitCast:
6164 case CK_LValueBitCast:
6165 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00006166 case CK_ARCReclaimReturnedObject:
John McCallf85e1932011-06-15 23:02:42 +00006167 e = cast->getSubExpr();
6168 continue;
6169
John McCallf85e1932011-06-15 23:02:42 +00006170 default:
6171 return false;
6172 }
6173 }
6174
6175 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6176 ObjCIvarDecl *ivar = ref->getDecl();
6177 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6178 return false;
6179
6180 // Try to find a retain cycle in the base.
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006181 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006182 return false;
6183
6184 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6185 owner.Indirect = true;
6186 return true;
6187 }
6188
6189 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6190 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6191 if (!var) return false;
6192 return considerVariable(var, ref, owner);
6193 }
6194
John McCallf85e1932011-06-15 23:02:42 +00006195 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6196 if (member->isArrow()) return false;
6197
6198 // Don't count this as an indirect ownership.
6199 e = member->getBase();
6200 continue;
6201 }
6202
John McCall4b9c2d22011-11-06 09:01:30 +00006203 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6204 // Only pay attention to pseudo-objects on property references.
6205 ObjCPropertyRefExpr *pre
6206 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6207 ->IgnoreParens());
6208 if (!pre) return false;
6209 if (pre->isImplicitProperty()) return false;
6210 ObjCPropertyDecl *property = pre->getExplicitProperty();
6211 if (!property->isRetaining() &&
6212 !(property->getPropertyIvarDecl() &&
6213 property->getPropertyIvarDecl()->getType()
6214 .getObjCLifetime() == Qualifiers::OCL_Strong))
6215 return false;
6216
6217 owner.Indirect = true;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006218 if (pre->isSuperReceiver()) {
6219 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6220 if (!owner.Variable)
6221 return false;
6222 owner.Loc = pre->getLocation();
6223 owner.Range = pre->getSourceRange();
6224 return true;
6225 }
John McCall4b9c2d22011-11-06 09:01:30 +00006226 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6227 ->getSourceExpr());
6228 continue;
6229 }
6230
John McCallf85e1932011-06-15 23:02:42 +00006231 // Array ivars?
6232
6233 return false;
6234 }
6235}
6236
6237namespace {
6238 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6239 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6240 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6241 Variable(variable), Capturer(0) {}
6242
6243 VarDecl *Variable;
6244 Expr *Capturer;
6245
6246 void VisitDeclRefExpr(DeclRefExpr *ref) {
6247 if (ref->getDecl() == Variable && !Capturer)
6248 Capturer = ref;
6249 }
6250
John McCallf85e1932011-06-15 23:02:42 +00006251 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6252 if (Capturer) return;
6253 Visit(ref->getBase());
6254 if (Capturer && ref->isFreeIvar())
6255 Capturer = ref;
6256 }
6257
6258 void VisitBlockExpr(BlockExpr *block) {
6259 // Look inside nested blocks
6260 if (block->getBlockDecl()->capturesVariable(Variable))
6261 Visit(block->getBlockDecl()->getBody());
6262 }
Fariborz Jahanian7e2e4c32012-08-31 20:04:47 +00006263
6264 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6265 if (Capturer) return;
6266 if (OVE->getSourceExpr())
6267 Visit(OVE->getSourceExpr());
6268 }
John McCallf85e1932011-06-15 23:02:42 +00006269 };
6270}
6271
6272/// Check whether the given argument is a block which captures a
6273/// variable.
6274static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6275 assert(owner.Variable && owner.Loc.isValid());
6276
6277 e = e->IgnoreParenCasts();
Jordan Rose1fac58a2012-09-17 17:54:30 +00006278
6279 // Look through [^{...} copy] and Block_copy(^{...}).
6280 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6281 Selector Cmd = ME->getSelector();
6282 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6283 e = ME->getInstanceReceiver();
6284 if (!e)
6285 return 0;
6286 e = e->IgnoreParenCasts();
6287 }
6288 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6289 if (CE->getNumArgs() == 1) {
6290 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekd13eff62012-10-02 04:36:54 +00006291 if (Fn) {
6292 const IdentifierInfo *FnI = Fn->getIdentifier();
6293 if (FnI && FnI->isStr("_Block_copy")) {
6294 e = CE->getArg(0)->IgnoreParenCasts();
6295 }
6296 }
Jordan Rose1fac58a2012-09-17 17:54:30 +00006297 }
6298 }
6299
John McCallf85e1932011-06-15 23:02:42 +00006300 BlockExpr *block = dyn_cast<BlockExpr>(e);
6301 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6302 return 0;
6303
6304 FindCaptureVisitor visitor(S.Context, owner.Variable);
6305 visitor.Visit(block->getBlockDecl()->getBody());
6306 return visitor.Capturer;
6307}
6308
6309static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6310 RetainCycleOwner &owner) {
6311 assert(capturer);
6312 assert(owner.Variable && owner.Loc.isValid());
6313
6314 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6315 << owner.Variable << capturer->getSourceRange();
6316 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6317 << owner.Indirect << owner.Range;
6318}
6319
6320/// Check for a keyword selector that starts with the word 'add' or
6321/// 'set'.
6322static bool isSetterLikeSelector(Selector sel) {
6323 if (sel.isUnarySelector()) return false;
6324
Chris Lattner5f9e2722011-07-23 10:55:15 +00006325 StringRef str = sel.getNameForSlot(0);
John McCallf85e1932011-06-15 23:02:42 +00006326 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006327 if (str.startswith("set"))
John McCallf85e1932011-06-15 23:02:42 +00006328 str = str.substr(3);
Ted Kremenek968a0ee2011-12-01 00:59:21 +00006329 else if (str.startswith("add")) {
6330 // Specially whitelist 'addOperationWithBlock:'.
6331 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6332 return false;
6333 str = str.substr(3);
6334 }
John McCallf85e1932011-06-15 23:02:42 +00006335 else
6336 return false;
6337
6338 if (str.empty()) return true;
Jordan Rose3f6f51e2013-02-08 22:30:41 +00006339 return !isLowercase(str.front());
John McCallf85e1932011-06-15 23:02:42 +00006340}
6341
6342/// Check a message send to see if it's likely to cause a retain cycle.
6343void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6344 // Only check instance methods whose selector looks like a setter.
6345 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6346 return;
6347
6348 // Try to find a variable that the receiver is strongly owned by.
6349 RetainCycleOwner owner;
6350 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006351 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCallf85e1932011-06-15 23:02:42 +00006352 return;
6353 } else {
6354 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6355 owner.Variable = getCurMethodDecl()->getSelfDecl();
6356 owner.Loc = msg->getSuperLoc();
6357 owner.Range = msg->getSuperLoc();
6358 }
6359
6360 // Check whether the receiver is captured by any of the arguments.
6361 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6362 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6363 return diagnoseRetainCycle(*this, capturer, owner);
6364}
6365
6366/// Check a property assign to see if it's likely to cause a retain cycle.
6367void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6368 RetainCycleOwner owner;
Fariborz Jahanian6e6f93a2012-01-10 19:28:26 +00006369 if (!findRetainCycleOwner(*this, receiver, owner))
John McCallf85e1932011-06-15 23:02:42 +00006370 return;
6371
6372 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6373 diagnoseRetainCycle(*this, capturer, owner);
6374}
6375
Jordan Rosee10f4d32012-09-15 02:48:31 +00006376void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6377 RetainCycleOwner Owner;
6378 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6379 return;
6380
6381 // Because we don't have an expression for the variable, we have to set the
6382 // location explicitly here.
6383 Owner.Loc = Var->getLocation();
6384 Owner.Range = Var->getSourceRange();
6385
6386 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6387 diagnoseRetainCycle(*this, Capturer, Owner);
6388}
6389
Ted Kremenek9d084012012-12-21 08:04:28 +00006390static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6391 Expr *RHS, bool isProperty) {
6392 // Check if RHS is an Objective-C object literal, which also can get
6393 // immediately zapped in a weak reference. Note that we explicitly
6394 // allow ObjCStringLiterals, since those are designed to never really die.
6395 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006396
Ted Kremenekd3292c82012-12-21 22:46:35 +00006397 // This enum needs to match with the 'select' in
6398 // warn_objc_arc_literal_assign (off-by-1).
6399 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6400 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6401 return false;
Ted Kremenekf530ff72012-12-21 21:59:39 +00006402
6403 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenekd3292c82012-12-21 22:46:35 +00006404 << (unsigned) Kind
Ted Kremenek9d084012012-12-21 08:04:28 +00006405 << (isProperty ? 0 : 1)
6406 << RHS->getSourceRange();
Ted Kremenekf530ff72012-12-21 21:59:39 +00006407
6408 return true;
Ted Kremenek9d084012012-12-21 08:04:28 +00006409}
6410
Ted Kremenekb29b30f2012-12-21 19:45:30 +00006411static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6412 Qualifiers::ObjCLifetime LT,
6413 Expr *RHS, bool isProperty) {
6414 // Strip off any implicit cast added to get to the one ARC-specific.
6415 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6416 if (cast->getCastKind() == CK_ARCConsumeObject) {
6417 S.Diag(Loc, diag::warn_arc_retained_assign)
6418 << (LT == Qualifiers::OCL_ExplicitNone)
6419 << (isProperty ? 0 : 1)
6420 << RHS->getSourceRange();
6421 return true;
6422 }
6423 RHS = cast->getSubExpr();
6424 }
6425
6426 if (LT == Qualifiers::OCL_Weak &&
6427 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6428 return true;
6429
6430 return false;
6431}
6432
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006433bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6434 QualType LHS, Expr *RHS) {
6435 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6436
6437 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6438 return false;
6439
6440 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6441 return true;
6442
6443 return false;
6444}
6445
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006446void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6447 Expr *LHS, Expr *RHS) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006448 QualType LHSType;
6449 // PropertyRef on LHS type need be directly obtained from
6450 // its declaration as it has a PsuedoType.
6451 ObjCPropertyRefExpr *PRE
6452 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6453 if (PRE && !PRE->isImplicitProperty()) {
6454 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6455 if (PD)
6456 LHSType = PD->getType();
6457 }
6458
6459 if (LHSType.isNull())
6460 LHSType = LHS->getType();
Jordan Rose7a270482012-09-28 22:21:35 +00006461
6462 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6463
6464 if (LT == Qualifiers::OCL_Weak) {
6465 DiagnosticsEngine::Level Level =
6466 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6467 if (Level != DiagnosticsEngine::Ignored)
6468 getCurFunction()->markSafeWeakUse(LHS);
6469 }
6470
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006471 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6472 return;
Jordan Rose7a270482012-09-28 22:21:35 +00006473
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006474 // FIXME. Check for other life times.
6475 if (LT != Qualifiers::OCL_None)
6476 return;
6477
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006478 if (PRE) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006479 if (PRE->isImplicitProperty())
6480 return;
6481 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6482 if (!PD)
6483 return;
6484
Bill Wendlingad017fa2012-12-20 19:22:21 +00006485 unsigned Attributes = PD->getPropertyAttributes();
6486 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006487 // when 'assign' attribute was not explicitly specified
6488 // by user, ignore it and rely on property type itself
6489 // for lifetime info.
6490 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6491 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6492 LHSType->isObjCRetainableType())
6493 return;
6494
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006495 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall33e56f32011-09-10 06:18:15 +00006496 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006497 Diag(Loc, diag::warn_arc_retained_property_assign)
6498 << RHS->getSourceRange();
6499 return;
6500 }
6501 RHS = cast->getSubExpr();
6502 }
Fariborz Jahanian87eaf722012-01-17 22:58:16 +00006503 }
Bill Wendlingad017fa2012-12-20 19:22:21 +00006504 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb1ea5102012-12-21 08:04:20 +00006505 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6506 return;
Fariborz Jahanianbd2e27e2012-07-06 21:09:27 +00006507 }
Fariborz Jahanian921c1432011-06-24 18:25:34 +00006508 }
6509}
Dmitri Gribenko625bb562012-02-14 22:14:32 +00006510
6511//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6512
6513namespace {
6514bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6515 SourceLocation StmtLoc,
6516 const NullStmt *Body) {
6517 // Do not warn if the body is a macro that expands to nothing, e.g:
6518 //
6519 // #define CALL(x)
6520 // if (condition)
6521 // CALL(0);
6522 //
6523 if (Body->hasLeadingEmptyMacro())
6524 return false;
6525
6526 // Get line numbers of statement and body.
6527 bool StmtLineInvalid;
6528 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6529 &StmtLineInvalid);
6530 if (StmtLineInvalid)
6531 return false;
6532
6533 bool BodyLineInvalid;
6534 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6535 &BodyLineInvalid);
6536 if (BodyLineInvalid)
6537 return false;
6538
6539 // Warn if null statement and body are on the same line.
6540 if (StmtLine != BodyLine)
6541 return false;
6542
6543 return true;
6544}
6545} // Unnamed namespace
6546
6547void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6548 const Stmt *Body,
6549 unsigned DiagID) {
6550 // Since this is a syntactic check, don't emit diagnostic for template
6551 // instantiations, this just adds noise.
6552 if (CurrentInstantiationScope)
6553 return;
6554
6555 // The body should be a null statement.
6556 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6557 if (!NBody)
6558 return;
6559
6560 // Do the usual checks.
6561 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6562 return;
6563
6564 Diag(NBody->getSemiLoc(), DiagID);
6565 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6566}
6567
6568void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6569 const Stmt *PossibleBody) {
6570 assert(!CurrentInstantiationScope); // Ensured by caller
6571
6572 SourceLocation StmtLoc;
6573 const Stmt *Body;
6574 unsigned DiagID;
6575 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6576 StmtLoc = FS->getRParenLoc();
6577 Body = FS->getBody();
6578 DiagID = diag::warn_empty_for_body;
6579 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6580 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6581 Body = WS->getBody();
6582 DiagID = diag::warn_empty_while_body;
6583 } else
6584 return; // Neither `for' nor `while'.
6585
6586 // The body should be a null statement.
6587 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6588 if (!NBody)
6589 return;
6590
6591 // Skip expensive checks if diagnostic is disabled.
6592 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6593 DiagnosticsEngine::Ignored)
6594 return;
6595
6596 // Do the usual checks.
6597 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6598 return;
6599
6600 // `for(...);' and `while(...);' are popular idioms, so in order to keep
6601 // noise level low, emit diagnostics only if for/while is followed by a
6602 // CompoundStmt, e.g.:
6603 // for (int i = 0; i < n; i++);
6604 // {
6605 // a(i);
6606 // }
6607 // or if for/while is followed by a statement with more indentation
6608 // than for/while itself:
6609 // for (int i = 0; i < n; i++);
6610 // a(i);
6611 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6612 if (!ProbableTypo) {
6613 bool BodyColInvalid;
6614 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6615 PossibleBody->getLocStart(),
6616 &BodyColInvalid);
6617 if (BodyColInvalid)
6618 return;
6619
6620 bool StmtColInvalid;
6621 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6622 S->getLocStart(),
6623 &StmtColInvalid);
6624 if (StmtColInvalid)
6625 return;
6626
6627 if (BodyCol > StmtCol)
6628 ProbableTypo = true;
6629 }
6630
6631 if (ProbableTypo) {
6632 Diag(NBody->getSemiLoc(), DiagID);
6633 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6634 }
6635}
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006636
6637//===--- Layout compatibility ----------------------------------------------//
6638
6639namespace {
6640
6641bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6642
6643/// \brief Check if two enumeration types are layout-compatible.
6644bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6645 // C++11 [dcl.enum] p8:
6646 // Two enumeration types are layout-compatible if they have the same
6647 // underlying type.
6648 return ED1->isComplete() && ED2->isComplete() &&
6649 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6650}
6651
6652/// \brief Check if two fields are layout-compatible.
6653bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6654 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6655 return false;
6656
6657 if (Field1->isBitField() != Field2->isBitField())
6658 return false;
6659
6660 if (Field1->isBitField()) {
6661 // Make sure that the bit-fields are the same length.
6662 unsigned Bits1 = Field1->getBitWidthValue(C);
6663 unsigned Bits2 = Field2->getBitWidthValue(C);
6664
6665 if (Bits1 != Bits2)
6666 return false;
6667 }
6668
6669 return true;
6670}
6671
6672/// \brief Check if two standard-layout structs are layout-compatible.
6673/// (C++11 [class.mem] p17)
6674bool isLayoutCompatibleStruct(ASTContext &C,
6675 RecordDecl *RD1,
6676 RecordDecl *RD2) {
6677 // If both records are C++ classes, check that base classes match.
6678 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
6679 // If one of records is a CXXRecordDecl we are in C++ mode,
6680 // thus the other one is a CXXRecordDecl, too.
6681 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
6682 // Check number of base classes.
6683 if (D1CXX->getNumBases() != D2CXX->getNumBases())
6684 return false;
6685
6686 // Check the base classes.
6687 for (CXXRecordDecl::base_class_const_iterator
6688 Base1 = D1CXX->bases_begin(),
6689 BaseEnd1 = D1CXX->bases_end(),
6690 Base2 = D2CXX->bases_begin();
6691 Base1 != BaseEnd1;
6692 ++Base1, ++Base2) {
6693 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
6694 return false;
6695 }
6696 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
6697 // If only RD2 is a C++ class, it should have zero base classes.
6698 if (D2CXX->getNumBases() > 0)
6699 return false;
6700 }
6701
6702 // Check the fields.
6703 RecordDecl::field_iterator Field2 = RD2->field_begin(),
6704 Field2End = RD2->field_end(),
6705 Field1 = RD1->field_begin(),
6706 Field1End = RD1->field_end();
6707 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
6708 if (!isLayoutCompatible(C, *Field1, *Field2))
6709 return false;
6710 }
6711 if (Field1 != Field1End || Field2 != Field2End)
6712 return false;
6713
6714 return true;
6715}
6716
6717/// \brief Check if two standard-layout unions are layout-compatible.
6718/// (C++11 [class.mem] p18)
6719bool isLayoutCompatibleUnion(ASTContext &C,
6720 RecordDecl *RD1,
6721 RecordDecl *RD2) {
6722 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
6723 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
6724 Field2End = RD2->field_end();
6725 Field2 != Field2End; ++Field2) {
6726 UnmatchedFields.insert(*Field2);
6727 }
6728
6729 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
6730 Field1End = RD1->field_end();
6731 Field1 != Field1End; ++Field1) {
6732 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
6733 I = UnmatchedFields.begin(),
6734 E = UnmatchedFields.end();
6735
6736 for ( ; I != E; ++I) {
6737 if (isLayoutCompatible(C, *Field1, *I)) {
6738 bool Result = UnmatchedFields.erase(*I);
6739 (void) Result;
6740 assert(Result);
6741 break;
6742 }
6743 }
6744 if (I == E)
6745 return false;
6746 }
6747
6748 return UnmatchedFields.empty();
6749}
6750
6751bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
6752 if (RD1->isUnion() != RD2->isUnion())
6753 return false;
6754
6755 if (RD1->isUnion())
6756 return isLayoutCompatibleUnion(C, RD1, RD2);
6757 else
6758 return isLayoutCompatibleStruct(C, RD1, RD2);
6759}
6760
6761/// \brief Check if two types are layout-compatible in C++11 sense.
6762bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
6763 if (T1.isNull() || T2.isNull())
6764 return false;
6765
6766 // C++11 [basic.types] p11:
6767 // If two types T1 and T2 are the same type, then T1 and T2 are
6768 // layout-compatible types.
6769 if (C.hasSameType(T1, T2))
6770 return true;
6771
6772 T1 = T1.getCanonicalType().getUnqualifiedType();
6773 T2 = T2.getCanonicalType().getUnqualifiedType();
6774
6775 const Type::TypeClass TC1 = T1->getTypeClass();
6776 const Type::TypeClass TC2 = T2->getTypeClass();
6777
6778 if (TC1 != TC2)
6779 return false;
6780
6781 if (TC1 == Type::Enum) {
6782 return isLayoutCompatible(C,
6783 cast<EnumType>(T1)->getDecl(),
6784 cast<EnumType>(T2)->getDecl());
6785 } else if (TC1 == Type::Record) {
6786 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
6787 return false;
6788
6789 return isLayoutCompatible(C,
6790 cast<RecordType>(T1)->getDecl(),
6791 cast<RecordType>(T2)->getDecl());
6792 }
6793
6794 return false;
6795}
6796}
6797
6798//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
6799
6800namespace {
6801/// \brief Given a type tag expression find the type tag itself.
6802///
6803/// \param TypeExpr Type tag expression, as it appears in user's code.
6804///
6805/// \param VD Declaration of an identifier that appears in a type tag.
6806///
6807/// \param MagicValue Type tag magic value.
6808bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
6809 const ValueDecl **VD, uint64_t *MagicValue) {
6810 while(true) {
6811 if (!TypeExpr)
6812 return false;
6813
6814 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
6815
6816 switch (TypeExpr->getStmtClass()) {
6817 case Stmt::UnaryOperatorClass: {
6818 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
6819 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
6820 TypeExpr = UO->getSubExpr();
6821 continue;
6822 }
6823 return false;
6824 }
6825
6826 case Stmt::DeclRefExprClass: {
6827 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
6828 *VD = DRE->getDecl();
6829 return true;
6830 }
6831
6832 case Stmt::IntegerLiteralClass: {
6833 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
6834 llvm::APInt MagicValueAPInt = IL->getValue();
6835 if (MagicValueAPInt.getActiveBits() <= 64) {
6836 *MagicValue = MagicValueAPInt.getZExtValue();
6837 return true;
6838 } else
6839 return false;
6840 }
6841
6842 case Stmt::BinaryConditionalOperatorClass:
6843 case Stmt::ConditionalOperatorClass: {
6844 const AbstractConditionalOperator *ACO =
6845 cast<AbstractConditionalOperator>(TypeExpr);
6846 bool Result;
6847 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
6848 if (Result)
6849 TypeExpr = ACO->getTrueExpr();
6850 else
6851 TypeExpr = ACO->getFalseExpr();
6852 continue;
6853 }
6854 return false;
6855 }
6856
6857 case Stmt::BinaryOperatorClass: {
6858 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
6859 if (BO->getOpcode() == BO_Comma) {
6860 TypeExpr = BO->getRHS();
6861 continue;
6862 }
6863 return false;
6864 }
6865
6866 default:
6867 return false;
6868 }
6869 }
6870}
6871
6872/// \brief Retrieve the C type corresponding to type tag TypeExpr.
6873///
6874/// \param TypeExpr Expression that specifies a type tag.
6875///
6876/// \param MagicValues Registered magic values.
6877///
6878/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
6879/// kind.
6880///
6881/// \param TypeInfo Information about the corresponding C type.
6882///
6883/// \returns true if the corresponding C type was found.
6884bool GetMatchingCType(
6885 const IdentifierInfo *ArgumentKind,
6886 const Expr *TypeExpr, const ASTContext &Ctx,
6887 const llvm::DenseMap<Sema::TypeTagMagicValue,
6888 Sema::TypeTagData> *MagicValues,
6889 bool &FoundWrongKind,
6890 Sema::TypeTagData &TypeInfo) {
6891 FoundWrongKind = false;
6892
6893 // Variable declaration that has type_tag_for_datatype attribute.
6894 const ValueDecl *VD = NULL;
6895
6896 uint64_t MagicValue;
6897
6898 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
6899 return false;
6900
6901 if (VD) {
6902 for (specific_attr_iterator<TypeTagForDatatypeAttr>
6903 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
6904 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
6905 I != E; ++I) {
6906 if (I->getArgumentKind() != ArgumentKind) {
6907 FoundWrongKind = true;
6908 return false;
6909 }
6910 TypeInfo.Type = I->getMatchingCType();
6911 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
6912 TypeInfo.MustBeNull = I->getMustBeNull();
6913 return true;
6914 }
6915 return false;
6916 }
6917
6918 if (!MagicValues)
6919 return false;
6920
6921 llvm::DenseMap<Sema::TypeTagMagicValue,
6922 Sema::TypeTagData>::const_iterator I =
6923 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
6924 if (I == MagicValues->end())
6925 return false;
6926
6927 TypeInfo = I->second;
6928 return true;
6929}
6930} // unnamed namespace
6931
6932void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
6933 uint64_t MagicValue, QualType Type,
6934 bool LayoutCompatible,
6935 bool MustBeNull) {
6936 if (!TypeTagForDatatypeMagicValues)
6937 TypeTagForDatatypeMagicValues.reset(
6938 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
6939
6940 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
6941 (*TypeTagForDatatypeMagicValues)[Magic] =
6942 TypeTagData(Type, LayoutCompatible, MustBeNull);
6943}
6944
6945namespace {
6946bool IsSameCharType(QualType T1, QualType T2) {
6947 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
6948 if (!BT1)
6949 return false;
6950
6951 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
6952 if (!BT2)
6953 return false;
6954
6955 BuiltinType::Kind T1Kind = BT1->getKind();
6956 BuiltinType::Kind T2Kind = BT2->getKind();
6957
6958 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
6959 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
6960 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
6961 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
6962}
6963} // unnamed namespace
6964
6965void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
6966 const Expr * const *ExprArgs) {
6967 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
6968 bool IsPointerAttr = Attr->getIsPointer();
6969
6970 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
6971 bool FoundWrongKind;
6972 TypeTagData TypeInfo;
6973 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
6974 TypeTagForDatatypeMagicValues.get(),
6975 FoundWrongKind, TypeInfo)) {
6976 if (FoundWrongKind)
6977 Diag(TypeTagExpr->getExprLoc(),
6978 diag::warn_type_tag_for_datatype_wrong_kind)
6979 << TypeTagExpr->getSourceRange();
6980 return;
6981 }
6982
6983 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
6984 if (IsPointerAttr) {
6985 // Skip implicit cast of pointer to `void *' (as a function argument).
6986 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5a249802012-11-03 16:07:49 +00006987 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkob57ce4e2012-11-03 22:10:18 +00006988 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenko0d5a0692012-08-17 00:08:38 +00006989 ArgumentExpr = ICE->getSubExpr();
6990 }
6991 QualType ArgumentType = ArgumentExpr->getType();
6992
6993 // Passing a `void*' pointer shouldn't trigger a warning.
6994 if (IsPointerAttr && ArgumentType->isVoidPointerType())
6995 return;
6996
6997 if (TypeInfo.MustBeNull) {
6998 // Type tag with matching void type requires a null pointer.
6999 if (!ArgumentExpr->isNullPointerConstant(Context,
7000 Expr::NPC_ValueDependentIsNotNull)) {
7001 Diag(ArgumentExpr->getExprLoc(),
7002 diag::warn_type_safety_null_pointer_required)
7003 << ArgumentKind->getName()
7004 << ArgumentExpr->getSourceRange()
7005 << TypeTagExpr->getSourceRange();
7006 }
7007 return;
7008 }
7009
7010 QualType RequiredType = TypeInfo.Type;
7011 if (IsPointerAttr)
7012 RequiredType = Context.getPointerType(RequiredType);
7013
7014 bool mismatch = false;
7015 if (!TypeInfo.LayoutCompatible) {
7016 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7017
7018 // C++11 [basic.fundamental] p1:
7019 // Plain char, signed char, and unsigned char are three distinct types.
7020 //
7021 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7022 // char' depending on the current char signedness mode.
7023 if (mismatch)
7024 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7025 RequiredType->getPointeeType())) ||
7026 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7027 mismatch = false;
7028 } else
7029 if (IsPointerAttr)
7030 mismatch = !isLayoutCompatible(Context,
7031 ArgumentType->getPointeeType(),
7032 RequiredType->getPointeeType());
7033 else
7034 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7035
7036 if (mismatch)
7037 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7038 << ArgumentType << ArgumentKind->getName()
7039 << TypeInfo.LayoutCompatible << RequiredType
7040 << ArgumentExpr->getSourceRange()
7041 << TypeTagExpr->getSourceRange();
7042}