blob: f0e93a78f7581dcef30fb5e74fb37b54f2a7fdfd [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-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 Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-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 Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-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 McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-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 Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Reid Kleckner597e81d2014-03-26 15:38:33 +0000145 case Builtin::BI__va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000146 if (SemaBuiltinVAStart(TheCall))
147 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000148 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000149 case Builtin::BI__builtin_isgreater:
150 case Builtin::BI__builtin_isgreaterequal:
151 case Builtin::BI__builtin_isless:
152 case Builtin::BI__builtin_islessequal:
153 case Builtin::BI__builtin_islessgreater:
154 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000155 if (SemaBuiltinUnorderedCompare(TheCall))
156 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000157 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000158 case Builtin::BI__builtin_fpclassify:
159 if (SemaBuiltinFPClassification(TheCall, 6))
160 return ExprError();
161 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000162 case Builtin::BI__builtin_isfinite:
163 case Builtin::BI__builtin_isinf:
164 case Builtin::BI__builtin_isinf_sign:
165 case Builtin::BI__builtin_isnan:
166 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000167 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000168 return ExprError();
169 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000170 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000171 return SemaBuiltinShuffleVector(TheCall);
172 // TheCall will be freed by the smart pointer here, but that's fine, since
173 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000174 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000175 if (SemaBuiltinPrefetch(TheCall))
176 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000177 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000179 if (SemaBuiltinObjectSize(TheCall))
180 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000181 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
John McCallbebede42011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000194 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000299 }
300
301 // Since the target specific builtins for each arch overlap, only check those
302 // of the arch we are compiling for.
303 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000304 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000305 case llvm::Triple::arm:
306 case llvm::Triple::thumb:
307 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
308 return ExprError();
309 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000310 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +0000311 case llvm::Triple::aarch64_be:
Tim Northover2fe823a2013-08-01 09:23:19 +0000312 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
313 return ExprError();
314 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000315 case llvm::Triple::mips:
316 case llvm::Triple::mipsel:
317 case llvm::Triple::mips64:
318 case llvm::Triple::mips64el:
319 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
320 return ExprError();
321 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000322 case llvm::Triple::x86:
323 case llvm::Triple::x86_64:
324 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
325 return ExprError();
326 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000327 default:
328 break;
329 }
330 }
331
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000332 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000333}
334
Nate Begeman91e1fea2010-06-14 05:21:25 +0000335// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000336static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000337 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000338 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000339 switch (Type.getEltType()) {
340 case NeonTypeFlags::Int8:
341 case NeonTypeFlags::Poly8:
342 return shift ? 7 : (8 << IsQuad) - 1;
343 case NeonTypeFlags::Int16:
344 case NeonTypeFlags::Poly16:
345 return shift ? 15 : (4 << IsQuad) - 1;
346 case NeonTypeFlags::Int32:
347 return shift ? 31 : (2 << IsQuad) - 1;
348 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000349 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000350 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000351 case NeonTypeFlags::Poly128:
352 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000353 case NeonTypeFlags::Float16:
354 assert(!shift && "cannot shift float types!");
355 return (4 << IsQuad) - 1;
356 case NeonTypeFlags::Float32:
357 assert(!shift && "cannot shift float types!");
358 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000359 case NeonTypeFlags::Float64:
360 assert(!shift && "cannot shift float types!");
361 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000362 }
David Blaikie8a40f702012-01-17 06:56:22 +0000363 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000364}
365
Bob Wilsone4d77232011-11-08 05:04:11 +0000366/// getNeonEltType - Return the QualType corresponding to the elements of
367/// the vector type specified by the NeonTypeFlags. This is used to check
368/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000369static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
370 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000371 switch (Flags.getEltType()) {
372 case NeonTypeFlags::Int8:
373 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
374 case NeonTypeFlags::Int16:
375 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
376 case NeonTypeFlags::Int32:
377 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
378 case NeonTypeFlags::Int64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000379 if (IsAArch64)
380 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
381 else
382 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
383 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000384 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000385 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000386 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000387 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
388 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000389 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000390 case NeonTypeFlags::Poly128:
391 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000392 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000393 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000394 case NeonTypeFlags::Float32:
395 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000396 case NeonTypeFlags::Float64:
397 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000398 }
David Blaikie8a40f702012-01-17 06:56:22 +0000399 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000400}
401
Tim Northover12670412014-02-19 10:37:05 +0000402bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000403 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000404 uint64_t mask = 0;
405 unsigned TV = 0;
406 int PtrArgNum = -1;
407 bool HasConstPtr = false;
408 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000409#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000410#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000411#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000412 }
413
414 // For NEON intrinsics which are overloaded on vector element type, validate
415 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000416 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000417 if (mask) {
418 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
419 return true;
420
421 TV = Result.getLimitedValue(64);
422 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
423 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000424 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000425 }
426
427 if (PtrArgNum >= 0) {
428 // Check that pointer arguments have the specified type.
429 Expr *Arg = TheCall->getArg(PtrArgNum);
430 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
431 Arg = ICE->getSubExpr();
432 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
433 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000434
435 bool IsAArch64 =
436 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
437 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
Tim Northover2fe823a2013-08-01 09:23:19 +0000438 if (HasConstPtr)
439 EltTy = EltTy.withConst();
440 QualType LHSTy = Context.getPointerType(EltTy);
441 AssignConvertType ConvTy;
442 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
443 if (RHS.isInvalid())
444 return true;
445 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
446 RHS.get(), AA_Assigning))
447 return true;
448 }
449
450 // For NEON intrinsics which take an immediate value as part of the
451 // instruction, range check them here.
452 unsigned i = 0, l = 0, u = 0;
453 switch (BuiltinID) {
454 default:
455 return false;
Tim Northover12670412014-02-19 10:37:05 +0000456#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000457#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000458#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000459 }
460 ;
461
462 // We can't check the value of a dependent argument.
463 if (TheCall->getArg(i)->isTypeDependent() ||
464 TheCall->getArg(i)->isValueDependent())
465 return false;
466
467 // Check that the immediate argument is actually a constant.
468 if (SemaBuiltinConstantArg(TheCall, i, Result))
469 return true;
470
471 // Range check against the upper/lower values for this isntruction.
472 unsigned Val = Result.getZExtValue();
473 if (Val < l || Val > (u + l))
474 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
475 << l << u + l << TheCall->getArg(i)->getSourceRange();
476
477 return false;
478}
479
Tim Northover12670412014-02-19 10:37:05 +0000480bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
481 CallExpr *TheCall) {
482 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
483 return true;
484
485 return false;
486}
487
Tim Northover6aacd492013-07-16 09:47:53 +0000488bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
489 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
490 BuiltinID == ARM::BI__builtin_arm_strex) &&
491 "unexpected ARM builtin");
492 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
493
494 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
495
496 // Ensure that we have the proper number of arguments.
497 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
498 return true;
499
500 // Inspect the pointer argument of the atomic builtin. This should always be
501 // a pointer type, whose element is an integral scalar or pointer type.
502 // Because it is a pointer type, we don't have to worry about any implicit
503 // casts here.
504 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
505 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
506 if (PointerArgRes.isInvalid())
507 return true;
508 PointerArg = PointerArgRes.take();
509
510 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
511 if (!pointerType) {
512 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
513 << PointerArg->getType() << PointerArg->getSourceRange();
514 return true;
515 }
516
517 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
518 // task is to insert the appropriate casts into the AST. First work out just
519 // what the appropriate type is.
520 QualType ValType = pointerType->getPointeeType();
521 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
522 if (IsLdrex)
523 AddrType.addConst();
524
525 // Issue a warning if the cast is dodgy.
526 CastKind CastNeeded = CK_NoOp;
527 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
528 CastNeeded = CK_BitCast;
529 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
530 << PointerArg->getType()
531 << Context.getPointerType(AddrType)
532 << AA_Passing << PointerArg->getSourceRange();
533 }
534
535 // Finally, do the cast and replace the argument with the corrected version.
536 AddrType = Context.getPointerType(AddrType);
537 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
538 if (PointerArgRes.isInvalid())
539 return true;
540 PointerArg = PointerArgRes.take();
541
542 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
543
544 // In general, we allow ints, floats and pointers to be loaded and stored.
545 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
546 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
547 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
548 << PointerArg->getType() << PointerArg->getSourceRange();
549 return true;
550 }
551
552 // But ARM doesn't have instructions to deal with 128-bit versions.
553 if (Context.getTypeSize(ValType) > 64) {
554 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
555 << PointerArg->getType() << PointerArg->getSourceRange();
556 return true;
557 }
558
559 switch (ValType.getObjCLifetime()) {
560 case Qualifiers::OCL_None:
561 case Qualifiers::OCL_ExplicitNone:
562 // okay
563 break;
564
565 case Qualifiers::OCL_Weak:
566 case Qualifiers::OCL_Strong:
567 case Qualifiers::OCL_Autoreleasing:
568 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
569 << ValType << PointerArg->getSourceRange();
570 return true;
571 }
572
573
574 if (IsLdrex) {
575 TheCall->setType(ValType);
576 return false;
577 }
578
579 // Initialize the argument to be stored.
580 ExprResult ValArg = TheCall->getArg(0);
581 InitializedEntity Entity = InitializedEntity::InitializeParameter(
582 Context, ValType, /*consume*/ false);
583 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
584 if (ValArg.isInvalid())
585 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000586 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000587
588 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
589 // but the custom checker bypasses all default analysis.
590 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000591 return false;
592}
593
Nate Begeman4904e322010-06-08 02:47:44 +0000594bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000595 llvm::APSInt Result;
596
Tim Northover6aacd492013-07-16 09:47:53 +0000597 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
598 BuiltinID == ARM::BI__builtin_arm_strex) {
599 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
600 }
601
Tim Northover12670412014-02-19 10:37:05 +0000602 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
603 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000604
Bob Wilsond836d3d2014-03-09 23:02:27 +0000605 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000606 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000607 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000608 switch (BuiltinID) {
609 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000610 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
611 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000612 case ARM::BI__builtin_arm_vcvtr_f:
613 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000614 case ARM::BI__builtin_arm_dmb:
615 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000616 };
617
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000618 // We can't check the value of a dependent argument.
619 if (TheCall->getArg(i)->isTypeDependent() ||
620 TheCall->getArg(i)->isValueDependent())
621 return false;
622
Nate Begeman91e1fea2010-06-14 05:21:25 +0000623 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000624 if (SemaBuiltinConstantArg(TheCall, i, Result))
625 return true;
626
Nate Begeman91e1fea2010-06-14 05:21:25 +0000627 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000628 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000629 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000630 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000631 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000632
Nate Begemanf568b072010-08-03 21:32:34 +0000633 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000634 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000635}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000636
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000637bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
638 unsigned i = 0, l = 0, u = 0;
639 switch (BuiltinID) {
640 default: return false;
641 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
642 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000643 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
644 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
645 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
646 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
647 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000648 };
649
650 // We can't check the value of a dependent argument.
651 if (TheCall->getArg(i)->isTypeDependent() ||
652 TheCall->getArg(i)->isValueDependent())
653 return false;
654
655 // Check that the immediate argument is actually a constant.
656 llvm::APSInt Result;
657 if (SemaBuiltinConstantArg(TheCall, i, Result))
658 return true;
659
660 // Range check against the upper/lower values for this instruction.
661 unsigned Val = Result.getZExtValue();
662 if (Val < l || Val > u)
663 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
664 << l << u << TheCall->getArg(i)->getSourceRange();
665
666 return false;
667}
668
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000669bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
670 switch (BuiltinID) {
671 case X86::BI_mm_prefetch:
672 return SemaBuiltinMMPrefetch(TheCall);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000673 }
674 return false;
675}
676
Richard Smith55ce3522012-06-25 20:30:08 +0000677/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
678/// parameter with the FormatAttr's correct format_idx and firstDataArg.
679/// Returns true when the format fits the function and the FormatStringInfo has
680/// been populated.
681bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
682 FormatStringInfo *FSI) {
683 FSI->HasVAListArg = Format->getFirstArg() == 0;
684 FSI->FormatIdx = Format->getFormatIdx() - 1;
685 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000686
Richard Smith55ce3522012-06-25 20:30:08 +0000687 // The way the format attribute works in GCC, the implicit this argument
688 // of member functions is counted. However, it doesn't appear in our own
689 // lists, so decrement format_idx in that case.
690 if (IsCXXMember) {
691 if(FSI->FormatIdx == 0)
692 return false;
693 --FSI->FormatIdx;
694 if (FSI->FirstDataArg != 0)
695 --FSI->FirstDataArg;
696 }
697 return true;
698}
Mike Stump11289f42009-09-09 15:08:12 +0000699
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000700/// Checks if a the given expression evaluates to null.
701///
702/// \brief Returns true if the value evaluates to null.
703static bool CheckNonNullExpr(Sema &S,
704 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000705 // As a special case, transparent unions initialized with zero are
706 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000707 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000708 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
709 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000710 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000711 if (const InitListExpr *ILE =
712 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000713 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000714 }
715
716 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000717 return (!Expr->isValueDependent() &&
718 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
719 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000720}
721
722static void CheckNonNullArgument(Sema &S,
723 const Expr *ArgExpr,
724 SourceLocation CallSiteLoc) {
725 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000726 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
727}
728
Ted Kremenek2bc73332014-01-17 06:24:43 +0000729static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000730 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000731 const Expr * const *ExprArgs,
732 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000733 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000734 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000735 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
736 e = NonNull->args_end();
737 i != e; ++i) {
738 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000739 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000740 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000741
742 // Check the attributes on the parameters.
743 ArrayRef<ParmVarDecl*> parms;
744 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
745 parms = FD->parameters();
746 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
747 parms = MD->parameters();
748
749 unsigned argIndex = 0;
750 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
751 I != E; ++I, ++argIndex) {
752 const ParmVarDecl *PVD = *I;
753 if (PVD->hasAttr<NonNullAttr>())
754 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
755 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000756}
757
Richard Smith55ce3522012-06-25 20:30:08 +0000758/// Handles the checks for format strings, non-POD arguments to vararg
759/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000760void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
761 unsigned NumParams, bool IsMemberFunction,
762 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000763 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000764 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000765 if (CurContext->isDependentContext())
766 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000767
Ted Kremenekb8176da2010-09-09 04:33:05 +0000768 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000769 llvm::SmallBitVector CheckedVarArgs;
770 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000771 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000772 // Only create vector if there are format attributes.
773 CheckedVarArgs.resize(Args.size());
774
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000775 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000776 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000777 }
Richard Smithd7293d72013-08-05 18:49:43 +0000778 }
Richard Smith55ce3522012-06-25 20:30:08 +0000779
780 // Refuse POD arguments that weren't caught by the format string
781 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000782 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000783 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000784 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000785 if (const Expr *Arg = Args[ArgIdx]) {
786 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
787 checkVariadicArgument(Arg, CallType);
788 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000789 }
Richard Smithd7293d72013-08-05 18:49:43 +0000790 }
Mike Stump11289f42009-09-09 15:08:12 +0000791
Richard Trieu41bc0992013-06-22 00:20:41 +0000792 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000793 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000794
Richard Trieu41bc0992013-06-22 00:20:41 +0000795 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000796 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
797 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000798 }
Richard Smith55ce3522012-06-25 20:30:08 +0000799}
800
801/// CheckConstructorCall - Check a constructor call for correctness and safety
802/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000803void Sema::CheckConstructorCall(FunctionDecl *FDecl,
804 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000805 const FunctionProtoType *Proto,
806 SourceLocation Loc) {
807 VariadicCallType CallType =
808 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000809 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000810 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
811}
812
813/// CheckFunctionCall - Check a direct function call for various correctness
814/// and safety properties not strictly enforced by the C type system.
815bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
816 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000817 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
818 isa<CXXMethodDecl>(FDecl);
819 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
820 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000821 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
822 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000823 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000824 Expr** Args = TheCall->getArgs();
825 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000826 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000827 // If this is a call to a member operator, hide the first argument
828 // from checkCall.
829 // FIXME: Our choice of AST representation here is less than ideal.
830 ++Args;
831 --NumArgs;
832 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000833 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000834 IsMemberFunction, TheCall->getRParenLoc(),
835 TheCall->getCallee()->getSourceRange(), CallType);
836
837 IdentifierInfo *FnInfo = FDecl->getIdentifier();
838 // None of the checks below are needed for functions that don't have
839 // simple names (e.g., C++ conversion functions).
840 if (!FnInfo)
841 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000842
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000843 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
844
Anna Zaks22122702012-01-17 00:37:07 +0000845 unsigned CMId = FDecl->getMemoryFunctionKind();
846 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000847 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000848
Anna Zaks201d4892012-01-13 21:52:01 +0000849 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000850 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000851 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000852 else if (CMId == Builtin::BIstrncat)
853 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000854 else
Anna Zaks22122702012-01-17 00:37:07 +0000855 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000856
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000857 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000858}
859
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000860bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000861 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000862 VariadicCallType CallType =
863 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000864
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000865 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000866 /*IsMemberFunction=*/false,
867 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000868
869 return false;
870}
871
Richard Trieu664c4c62013-06-20 21:03:13 +0000872bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
873 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000874 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
875 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000877
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000878 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000879 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000880 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000881
Richard Trieu664c4c62013-06-20 21:03:13 +0000882 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000883 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000884 CallType = VariadicDoesNotApply;
885 } else if (Ty->isBlockPointerType()) {
886 CallType = VariadicBlock;
887 } else { // Ty->isFunctionPointerType()
888 CallType = VariadicFunction;
889 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000890 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891
Alp Toker9cacbab2014-01-20 20:26:09 +0000892 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
893 TheCall->getNumArgs()),
894 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000895 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000896
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000897 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000898}
899
Richard Trieu41bc0992013-06-22 00:20:41 +0000900/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
901/// such as function pointers returned from functions.
902bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
903 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
904 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000905 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000906
Alp Toker9cacbab2014-01-20 20:26:09 +0000907 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
908 TheCall->getArgs(), TheCall->getNumArgs()),
909 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000910 TheCall->getCallee()->getSourceRange(), CallType);
911
912 return false;
913}
914
Tim Northovere94a34c2014-03-11 10:49:14 +0000915static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
916 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
917 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
918 return false;
919
920 switch (Op) {
921 case AtomicExpr::AO__c11_atomic_init:
922 llvm_unreachable("There is no ordering argument for an init");
923
924 case AtomicExpr::AO__c11_atomic_load:
925 case AtomicExpr::AO__atomic_load_n:
926 case AtomicExpr::AO__atomic_load:
927 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
928 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
929
930 case AtomicExpr::AO__c11_atomic_store:
931 case AtomicExpr::AO__atomic_store:
932 case AtomicExpr::AO__atomic_store_n:
933 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
934 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
935 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
936
937 default:
938 return true;
939 }
940}
941
Richard Smithfeea8832012-04-12 05:08:17 +0000942ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
943 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000944 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
945 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000946
Richard Smithfeea8832012-04-12 05:08:17 +0000947 // All these operations take one of the following forms:
948 enum {
949 // C __c11_atomic_init(A *, C)
950 Init,
951 // C __c11_atomic_load(A *, int)
952 Load,
953 // void __atomic_load(A *, CP, int)
954 Copy,
955 // C __c11_atomic_add(A *, M, int)
956 Arithmetic,
957 // C __atomic_exchange_n(A *, CP, int)
958 Xchg,
959 // void __atomic_exchange(A *, C *, CP, int)
960 GNUXchg,
961 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
962 C11CmpXchg,
963 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
964 GNUCmpXchg
965 } Form = Init;
966 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
967 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
968 // where:
969 // C is an appropriate type,
970 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
971 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
972 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
973 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000974
Richard Smithfeea8832012-04-12 05:08:17 +0000975 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
976 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
977 && "need to update code for modified C11 atomics");
978 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
979 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
980 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
981 Op == AtomicExpr::AO__atomic_store_n ||
982 Op == AtomicExpr::AO__atomic_exchange_n ||
983 Op == AtomicExpr::AO__atomic_compare_exchange_n;
984 bool IsAddSub = false;
985
986 switch (Op) {
987 case AtomicExpr::AO__c11_atomic_init:
988 Form = Init;
989 break;
990
991 case AtomicExpr::AO__c11_atomic_load:
992 case AtomicExpr::AO__atomic_load_n:
993 Form = Load;
994 break;
995
996 case AtomicExpr::AO__c11_atomic_store:
997 case AtomicExpr::AO__atomic_load:
998 case AtomicExpr::AO__atomic_store:
999 case AtomicExpr::AO__atomic_store_n:
1000 Form = Copy;
1001 break;
1002
1003 case AtomicExpr::AO__c11_atomic_fetch_add:
1004 case AtomicExpr::AO__c11_atomic_fetch_sub:
1005 case AtomicExpr::AO__atomic_fetch_add:
1006 case AtomicExpr::AO__atomic_fetch_sub:
1007 case AtomicExpr::AO__atomic_add_fetch:
1008 case AtomicExpr::AO__atomic_sub_fetch:
1009 IsAddSub = true;
1010 // Fall through.
1011 case AtomicExpr::AO__c11_atomic_fetch_and:
1012 case AtomicExpr::AO__c11_atomic_fetch_or:
1013 case AtomicExpr::AO__c11_atomic_fetch_xor:
1014 case AtomicExpr::AO__atomic_fetch_and:
1015 case AtomicExpr::AO__atomic_fetch_or:
1016 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001017 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001018 case AtomicExpr::AO__atomic_and_fetch:
1019 case AtomicExpr::AO__atomic_or_fetch:
1020 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001021 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001022 Form = Arithmetic;
1023 break;
1024
1025 case AtomicExpr::AO__c11_atomic_exchange:
1026 case AtomicExpr::AO__atomic_exchange_n:
1027 Form = Xchg;
1028 break;
1029
1030 case AtomicExpr::AO__atomic_exchange:
1031 Form = GNUXchg;
1032 break;
1033
1034 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1035 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1036 Form = C11CmpXchg;
1037 break;
1038
1039 case AtomicExpr::AO__atomic_compare_exchange:
1040 case AtomicExpr::AO__atomic_compare_exchange_n:
1041 Form = GNUCmpXchg;
1042 break;
1043 }
1044
1045 // Check we have the right number of arguments.
1046 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001048 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001049 << TheCall->getCallee()->getSourceRange();
1050 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001051 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1052 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001053 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001054 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001055 << TheCall->getCallee()->getSourceRange();
1056 return ExprError();
1057 }
1058
Richard Smithfeea8832012-04-12 05:08:17 +00001059 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001060 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001061 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1062 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1063 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001064 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001065 << Ptr->getType() << Ptr->getSourceRange();
1066 return ExprError();
1067 }
1068
Richard Smithfeea8832012-04-12 05:08:17 +00001069 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1070 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1071 QualType ValType = AtomTy; // 'C'
1072 if (IsC11) {
1073 if (!AtomTy->isAtomicType()) {
1074 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1075 << Ptr->getType() << Ptr->getSourceRange();
1076 return ExprError();
1077 }
Richard Smithe00921a2012-09-15 06:09:58 +00001078 if (AtomTy.isConstQualified()) {
1079 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1080 << Ptr->getType() << Ptr->getSourceRange();
1081 return ExprError();
1082 }
Richard Smithfeea8832012-04-12 05:08:17 +00001083 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001084 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001085
Richard Smithfeea8832012-04-12 05:08:17 +00001086 // For an arithmetic operation, the implied arithmetic must be well-formed.
1087 if (Form == Arithmetic) {
1088 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1089 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1090 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1091 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1092 return ExprError();
1093 }
1094 if (!IsAddSub && !ValType->isIntegerType()) {
1095 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1096 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1097 return ExprError();
1098 }
1099 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1100 // For __atomic_*_n operations, the value type must be a scalar integral or
1101 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001102 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001103 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1104 return ExprError();
1105 }
1106
Eli Friedmanaa769812013-09-11 03:49:34 +00001107 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1108 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001109 // For GNU atomics, require a trivially-copyable type. This is not part of
1110 // the GNU atomics specification, but we enforce it for sanity.
1111 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001112 << Ptr->getType() << Ptr->getSourceRange();
1113 return ExprError();
1114 }
1115
Richard Smithfeea8832012-04-12 05:08:17 +00001116 // FIXME: For any builtin other than a load, the ValType must not be
1117 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001118
1119 switch (ValType.getObjCLifetime()) {
1120 case Qualifiers::OCL_None:
1121 case Qualifiers::OCL_ExplicitNone:
1122 // okay
1123 break;
1124
1125 case Qualifiers::OCL_Weak:
1126 case Qualifiers::OCL_Strong:
1127 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001128 // FIXME: Can this happen? By this point, ValType should be known
1129 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001130 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1131 << ValType << Ptr->getSourceRange();
1132 return ExprError();
1133 }
1134
1135 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001136 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001138 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001139 ResultType = Context.BoolTy;
1140
Richard Smithfeea8832012-04-12 05:08:17 +00001141 // The type of a parameter passed 'by value'. In the GNU atomics, such
1142 // arguments are actually passed as pointers.
1143 QualType ByValType = ValType; // 'CP'
1144 if (!IsC11 && !IsN)
1145 ByValType = Ptr->getType();
1146
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001147 // The first argument --- the pointer --- has a fixed type; we
1148 // deduce the types of the rest of the arguments accordingly. Walk
1149 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001150 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001151 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001152 if (i < NumVals[Form] + 1) {
1153 switch (i) {
1154 case 1:
1155 // The second argument is the non-atomic operand. For arithmetic, this
1156 // is always passed by value, and for a compare_exchange it is always
1157 // passed by address. For the rest, GNU uses by-address and C11 uses
1158 // by-value.
1159 assert(Form != Load);
1160 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1161 Ty = ValType;
1162 else if (Form == Copy || Form == Xchg)
1163 Ty = ByValType;
1164 else if (Form == Arithmetic)
1165 Ty = Context.getPointerDiffType();
1166 else
1167 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1168 break;
1169 case 2:
1170 // The third argument to compare_exchange / GNU exchange is a
1171 // (pointer to a) desired value.
1172 Ty = ByValType;
1173 break;
1174 case 3:
1175 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1176 Ty = Context.BoolTy;
1177 break;
1178 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001179 } else {
1180 // The order(s) are always converted to int.
1181 Ty = Context.IntTy;
1182 }
Richard Smithfeea8832012-04-12 05:08:17 +00001183
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001184 InitializedEntity Entity =
1185 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001186 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001187 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1188 if (Arg.isInvalid())
1189 return true;
1190 TheCall->setArg(i, Arg.get());
1191 }
1192
Richard Smithfeea8832012-04-12 05:08:17 +00001193 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001194 SmallVector<Expr*, 5> SubExprs;
1195 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001196 switch (Form) {
1197 case Init:
1198 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001199 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001200 break;
1201 case Load:
1202 SubExprs.push_back(TheCall->getArg(1)); // Order
1203 break;
1204 case Copy:
1205 case Arithmetic:
1206 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001207 SubExprs.push_back(TheCall->getArg(2)); // Order
1208 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001209 break;
1210 case GNUXchg:
1211 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1212 SubExprs.push_back(TheCall->getArg(3)); // Order
1213 SubExprs.push_back(TheCall->getArg(1)); // Val1
1214 SubExprs.push_back(TheCall->getArg(2)); // Val2
1215 break;
1216 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001217 SubExprs.push_back(TheCall->getArg(3)); // Order
1218 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001219 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001220 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001221 break;
1222 case GNUCmpXchg:
1223 SubExprs.push_back(TheCall->getArg(4)); // Order
1224 SubExprs.push_back(TheCall->getArg(1)); // Val1
1225 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1226 SubExprs.push_back(TheCall->getArg(2)); // Val2
1227 SubExprs.push_back(TheCall->getArg(3)); // Weak
1228 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001229 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001230
1231 if (SubExprs.size() >= 2 && Form != Init) {
1232 llvm::APSInt Result(32);
1233 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1234 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001235 Diag(SubExprs[1]->getLocStart(),
1236 diag::warn_atomic_op_has_invalid_memory_order)
1237 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001238 }
1239
Fariborz Jahanian615de762013-05-28 17:37:39 +00001240 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1241 SubExprs, ResultType, Op,
1242 TheCall->getRParenLoc());
1243
1244 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1245 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1246 Context.AtomicUsesUnsupportedLibcall(AE))
1247 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1248 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001249
Fariborz Jahanian615de762013-05-28 17:37:39 +00001250 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001251}
1252
1253
John McCall29ad95b2011-08-27 01:09:30 +00001254/// checkBuiltinArgument - Given a call to a builtin function, perform
1255/// normal type-checking on the given argument, updating the call in
1256/// place. This is useful when a builtin function requires custom
1257/// type-checking for some of its arguments but not necessarily all of
1258/// them.
1259///
1260/// Returns true on error.
1261static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1262 FunctionDecl *Fn = E->getDirectCallee();
1263 assert(Fn && "builtin call without direct callee!");
1264
1265 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1266 InitializedEntity Entity =
1267 InitializedEntity::InitializeParameter(S.Context, Param);
1268
1269 ExprResult Arg = E->getArg(0);
1270 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1271 if (Arg.isInvalid())
1272 return true;
1273
1274 E->setArg(ArgIndex, Arg.take());
1275 return false;
1276}
1277
Chris Lattnerdc046542009-05-08 06:58:22 +00001278/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1279/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1280/// type of its first argument. The main ActOnCallExpr routines have already
1281/// promoted the types of arguments because all of these calls are prototyped as
1282/// void(...).
1283///
1284/// This function goes through and does final semantic checking for these
1285/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001286ExprResult
1287Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001288 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001289 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1290 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1291
1292 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001293 if (TheCall->getNumArgs() < 1) {
1294 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1295 << 0 << 1 << TheCall->getNumArgs()
1296 << TheCall->getCallee()->getSourceRange();
1297 return ExprError();
1298 }
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattnerdc046542009-05-08 06:58:22 +00001300 // Inspect the first argument of the atomic builtin. This should always be
1301 // a pointer type, whose element is an integral scalar or pointer type.
1302 // Because it is a pointer type, we don't have to worry about any implicit
1303 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001304 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001305 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001306 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1307 if (FirstArgResult.isInvalid())
1308 return ExprError();
1309 FirstArg = FirstArgResult.take();
1310 TheCall->setArg(0, FirstArg);
1311
John McCall31168b02011-06-15 23:02:42 +00001312 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1313 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001314 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1315 << FirstArg->getType() << FirstArg->getSourceRange();
1316 return ExprError();
1317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
John McCall31168b02011-06-15 23:02:42 +00001319 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001320 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001321 !ValType->isBlockPointerType()) {
1322 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1323 << FirstArg->getType() << FirstArg->getSourceRange();
1324 return ExprError();
1325 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001326
John McCall31168b02011-06-15 23:02:42 +00001327 switch (ValType.getObjCLifetime()) {
1328 case Qualifiers::OCL_None:
1329 case Qualifiers::OCL_ExplicitNone:
1330 // okay
1331 break;
1332
1333 case Qualifiers::OCL_Weak:
1334 case Qualifiers::OCL_Strong:
1335 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001336 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001337 << ValType << FirstArg->getSourceRange();
1338 return ExprError();
1339 }
1340
John McCallb50451a2011-10-05 07:41:44 +00001341 // Strip any qualifiers off ValType.
1342 ValType = ValType.getUnqualifiedType();
1343
Chandler Carruth3973af72010-07-18 20:54:12 +00001344 // The majority of builtins return a value, but a few have special return
1345 // types, so allow them to override appropriately below.
1346 QualType ResultType = ValType;
1347
Chris Lattnerdc046542009-05-08 06:58:22 +00001348 // We need to figure out which concrete builtin this maps onto. For example,
1349 // __sync_fetch_and_add with a 2 byte object turns into
1350 // __sync_fetch_and_add_2.
1351#define BUILTIN_ROW(x) \
1352 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1353 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Chris Lattnerdc046542009-05-08 06:58:22 +00001355 static const unsigned BuiltinIndices[][5] = {
1356 BUILTIN_ROW(__sync_fetch_and_add),
1357 BUILTIN_ROW(__sync_fetch_and_sub),
1358 BUILTIN_ROW(__sync_fetch_and_or),
1359 BUILTIN_ROW(__sync_fetch_and_and),
1360 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 BUILTIN_ROW(__sync_add_and_fetch),
1363 BUILTIN_ROW(__sync_sub_and_fetch),
1364 BUILTIN_ROW(__sync_and_and_fetch),
1365 BUILTIN_ROW(__sync_or_and_fetch),
1366 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001367
Chris Lattnerdc046542009-05-08 06:58:22 +00001368 BUILTIN_ROW(__sync_val_compare_and_swap),
1369 BUILTIN_ROW(__sync_bool_compare_and_swap),
1370 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001371 BUILTIN_ROW(__sync_lock_release),
1372 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001373 };
Mike Stump11289f42009-09-09 15:08:12 +00001374#undef BUILTIN_ROW
1375
Chris Lattnerdc046542009-05-08 06:58:22 +00001376 // Determine the index of the size.
1377 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001378 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001379 case 1: SizeIndex = 0; break;
1380 case 2: SizeIndex = 1; break;
1381 case 4: SizeIndex = 2; break;
1382 case 8: SizeIndex = 3; break;
1383 case 16: SizeIndex = 4; break;
1384 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001385 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1386 << FirstArg->getType() << FirstArg->getSourceRange();
1387 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
Chris Lattnerdc046542009-05-08 06:58:22 +00001390 // Each of these builtins has one pointer argument, followed by some number of
1391 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1392 // that we ignore. Find out which row of BuiltinIndices to read from as well
1393 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001394 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001395 unsigned BuiltinIndex, NumFixed = 1;
1396 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001397 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001398 case Builtin::BI__sync_fetch_and_add:
1399 case Builtin::BI__sync_fetch_and_add_1:
1400 case Builtin::BI__sync_fetch_and_add_2:
1401 case Builtin::BI__sync_fetch_and_add_4:
1402 case Builtin::BI__sync_fetch_and_add_8:
1403 case Builtin::BI__sync_fetch_and_add_16:
1404 BuiltinIndex = 0;
1405 break;
1406
1407 case Builtin::BI__sync_fetch_and_sub:
1408 case Builtin::BI__sync_fetch_and_sub_1:
1409 case Builtin::BI__sync_fetch_and_sub_2:
1410 case Builtin::BI__sync_fetch_and_sub_4:
1411 case Builtin::BI__sync_fetch_and_sub_8:
1412 case Builtin::BI__sync_fetch_and_sub_16:
1413 BuiltinIndex = 1;
1414 break;
1415
1416 case Builtin::BI__sync_fetch_and_or:
1417 case Builtin::BI__sync_fetch_and_or_1:
1418 case Builtin::BI__sync_fetch_and_or_2:
1419 case Builtin::BI__sync_fetch_and_or_4:
1420 case Builtin::BI__sync_fetch_and_or_8:
1421 case Builtin::BI__sync_fetch_and_or_16:
1422 BuiltinIndex = 2;
1423 break;
1424
1425 case Builtin::BI__sync_fetch_and_and:
1426 case Builtin::BI__sync_fetch_and_and_1:
1427 case Builtin::BI__sync_fetch_and_and_2:
1428 case Builtin::BI__sync_fetch_and_and_4:
1429 case Builtin::BI__sync_fetch_and_and_8:
1430 case Builtin::BI__sync_fetch_and_and_16:
1431 BuiltinIndex = 3;
1432 break;
Mike Stump11289f42009-09-09 15:08:12 +00001433
Douglas Gregor73722482011-11-28 16:30:08 +00001434 case Builtin::BI__sync_fetch_and_xor:
1435 case Builtin::BI__sync_fetch_and_xor_1:
1436 case Builtin::BI__sync_fetch_and_xor_2:
1437 case Builtin::BI__sync_fetch_and_xor_4:
1438 case Builtin::BI__sync_fetch_and_xor_8:
1439 case Builtin::BI__sync_fetch_and_xor_16:
1440 BuiltinIndex = 4;
1441 break;
1442
1443 case Builtin::BI__sync_add_and_fetch:
1444 case Builtin::BI__sync_add_and_fetch_1:
1445 case Builtin::BI__sync_add_and_fetch_2:
1446 case Builtin::BI__sync_add_and_fetch_4:
1447 case Builtin::BI__sync_add_and_fetch_8:
1448 case Builtin::BI__sync_add_and_fetch_16:
1449 BuiltinIndex = 5;
1450 break;
1451
1452 case Builtin::BI__sync_sub_and_fetch:
1453 case Builtin::BI__sync_sub_and_fetch_1:
1454 case Builtin::BI__sync_sub_and_fetch_2:
1455 case Builtin::BI__sync_sub_and_fetch_4:
1456 case Builtin::BI__sync_sub_and_fetch_8:
1457 case Builtin::BI__sync_sub_and_fetch_16:
1458 BuiltinIndex = 6;
1459 break;
1460
1461 case Builtin::BI__sync_and_and_fetch:
1462 case Builtin::BI__sync_and_and_fetch_1:
1463 case Builtin::BI__sync_and_and_fetch_2:
1464 case Builtin::BI__sync_and_and_fetch_4:
1465 case Builtin::BI__sync_and_and_fetch_8:
1466 case Builtin::BI__sync_and_and_fetch_16:
1467 BuiltinIndex = 7;
1468 break;
1469
1470 case Builtin::BI__sync_or_and_fetch:
1471 case Builtin::BI__sync_or_and_fetch_1:
1472 case Builtin::BI__sync_or_and_fetch_2:
1473 case Builtin::BI__sync_or_and_fetch_4:
1474 case Builtin::BI__sync_or_and_fetch_8:
1475 case Builtin::BI__sync_or_and_fetch_16:
1476 BuiltinIndex = 8;
1477 break;
1478
1479 case Builtin::BI__sync_xor_and_fetch:
1480 case Builtin::BI__sync_xor_and_fetch_1:
1481 case Builtin::BI__sync_xor_and_fetch_2:
1482 case Builtin::BI__sync_xor_and_fetch_4:
1483 case Builtin::BI__sync_xor_and_fetch_8:
1484 case Builtin::BI__sync_xor_and_fetch_16:
1485 BuiltinIndex = 9;
1486 break;
Mike Stump11289f42009-09-09 15:08:12 +00001487
Chris Lattnerdc046542009-05-08 06:58:22 +00001488 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001489 case Builtin::BI__sync_val_compare_and_swap_1:
1490 case Builtin::BI__sync_val_compare_and_swap_2:
1491 case Builtin::BI__sync_val_compare_and_swap_4:
1492 case Builtin::BI__sync_val_compare_and_swap_8:
1493 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001494 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001495 NumFixed = 2;
1496 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001497
Chris Lattnerdc046542009-05-08 06:58:22 +00001498 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001499 case Builtin::BI__sync_bool_compare_and_swap_1:
1500 case Builtin::BI__sync_bool_compare_and_swap_2:
1501 case Builtin::BI__sync_bool_compare_and_swap_4:
1502 case Builtin::BI__sync_bool_compare_and_swap_8:
1503 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001504 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001505 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001506 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001508
1509 case Builtin::BI__sync_lock_test_and_set:
1510 case Builtin::BI__sync_lock_test_and_set_1:
1511 case Builtin::BI__sync_lock_test_and_set_2:
1512 case Builtin::BI__sync_lock_test_and_set_4:
1513 case Builtin::BI__sync_lock_test_and_set_8:
1514 case Builtin::BI__sync_lock_test_and_set_16:
1515 BuiltinIndex = 12;
1516 break;
1517
Chris Lattnerdc046542009-05-08 06:58:22 +00001518 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001519 case Builtin::BI__sync_lock_release_1:
1520 case Builtin::BI__sync_lock_release_2:
1521 case Builtin::BI__sync_lock_release_4:
1522 case Builtin::BI__sync_lock_release_8:
1523 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001524 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001525 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001526 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001527 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001528
1529 case Builtin::BI__sync_swap:
1530 case Builtin::BI__sync_swap_1:
1531 case Builtin::BI__sync_swap_2:
1532 case Builtin::BI__sync_swap_4:
1533 case Builtin::BI__sync_swap_8:
1534 case Builtin::BI__sync_swap_16:
1535 BuiltinIndex = 14;
1536 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Chris Lattnerdc046542009-05-08 06:58:22 +00001539 // Now that we know how many fixed arguments we expect, first check that we
1540 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001541 if (TheCall->getNumArgs() < 1+NumFixed) {
1542 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1543 << 0 << 1+NumFixed << TheCall->getNumArgs()
1544 << TheCall->getCallee()->getSourceRange();
1545 return ExprError();
1546 }
Mike Stump11289f42009-09-09 15:08:12 +00001547
Chris Lattner5b9241b2009-05-08 15:36:58 +00001548 // Get the decl for the concrete builtin from this, we can tell what the
1549 // concrete integer type we should convert to is.
1550 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1551 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001552 FunctionDecl *NewBuiltinDecl;
1553 if (NewBuiltinID == BuiltinID)
1554 NewBuiltinDecl = FDecl;
1555 else {
1556 // Perform builtin lookup to avoid redeclaring it.
1557 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1558 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1559 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1560 assert(Res.getFoundDecl());
1561 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1562 if (NewBuiltinDecl == 0)
1563 return ExprError();
1564 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001565
John McCallcf142162010-08-07 06:22:56 +00001566 // The first argument --- the pointer --- has a fixed type; we
1567 // deduce the types of the rest of the arguments accordingly. Walk
1568 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001569 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001570 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Chris Lattnerdc046542009-05-08 06:58:22 +00001572 // GCC does an implicit conversion to the pointer or integer ValType. This
1573 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001574 // Initialize the argument.
1575 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1576 ValType, /*consume*/ false);
1577 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001578 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001579 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001580
Chris Lattnerdc046542009-05-08 06:58:22 +00001581 // Okay, we have something that *can* be converted to the right type. Check
1582 // to see if there is a potentially weird extension going on here. This can
1583 // happen when you do an atomic operation on something like an char* and
1584 // pass in 42. The 42 gets converted to char. This is even more strange
1585 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001586 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001587 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001588 }
Mike Stump11289f42009-09-09 15:08:12 +00001589
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001590 ASTContext& Context = this->getASTContext();
1591
1592 // Create a new DeclRefExpr to refer to the new decl.
1593 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1594 Context,
1595 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001596 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001597 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001598 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001599 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001600 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001601 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001602
Chris Lattnerdc046542009-05-08 06:58:22 +00001603 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001604 // FIXME: This loses syntactic information.
1605 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1606 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1607 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001608 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001609
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001610 // Change the result type of the call to match the original value type. This
1611 // is arbitrary, but the codegen for these builtins ins design to handle it
1612 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001613 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001614
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001615 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001616}
1617
Chris Lattner6436fb62009-02-18 06:01:06 +00001618/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001619/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001620/// Note: It might also make sense to do the UTF-16 conversion here (would
1621/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001622bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001623 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001624 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1625
Douglas Gregorfb65e592011-07-27 05:40:30 +00001626 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001627 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1628 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001629 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001630 }
Mike Stump11289f42009-09-09 15:08:12 +00001631
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001632 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001633 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001634 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001635 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001636 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001637 UTF16 *ToPtr = &ToBuf[0];
1638
1639 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1640 &ToPtr, ToPtr + NumBytes,
1641 strictConversion);
1642 // Check for conversion failure.
1643 if (Result != conversionOK)
1644 Diag(Arg->getLocStart(),
1645 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1646 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001647 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001648}
1649
Chris Lattnere202e6a2007-12-20 00:05:45 +00001650/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1651/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001652bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1653 Expr *Fn = TheCall->getCallee();
1654 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001655 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001656 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001657 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1658 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001659 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001660 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001661 return true;
1662 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001663
1664 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001665 return Diag(TheCall->getLocEnd(),
1666 diag::err_typecheck_call_too_few_args_at_least)
1667 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001668 }
1669
John McCall29ad95b2011-08-27 01:09:30 +00001670 // Type-check the first argument normally.
1671 if (checkBuiltinArgument(*this, TheCall, 0))
1672 return true;
1673
Chris Lattnere202e6a2007-12-20 00:05:45 +00001674 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001675 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001676 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001677 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001678 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001679 else if (FunctionDecl *FD = getCurFunctionDecl())
1680 isVariadic = FD->isVariadic();
1681 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001682 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001683
Chris Lattnere202e6a2007-12-20 00:05:45 +00001684 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001685 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1686 return true;
1687 }
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattner43be2e62007-12-19 23:59:04 +00001689 // Verify that the second argument to the builtin is the last argument of the
1690 // current function or method.
1691 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001692 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001693
Nico Weber9eea7642013-05-24 23:31:57 +00001694 // These are valid if SecondArgIsLastNamedArgument is false after the next
1695 // block.
1696 QualType Type;
1697 SourceLocation ParamLoc;
1698
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001699 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1700 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001701 // FIXME: This isn't correct for methods (results in bogus warning).
1702 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001703 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001704 if (CurBlock)
1705 LastArg = *(CurBlock->TheDecl->param_end()-1);
1706 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001707 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001708 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001709 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001710 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001711
1712 Type = PV->getType();
1713 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001714 }
1715 }
Mike Stump11289f42009-09-09 15:08:12 +00001716
Chris Lattner43be2e62007-12-19 23:59:04 +00001717 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001718 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001719 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001720 else if (Type->isReferenceType()) {
1721 Diag(Arg->getLocStart(),
1722 diag::warn_va_start_of_reference_type_is_undefined);
1723 Diag(ParamLoc, diag::note_parameter_type) << Type;
1724 }
1725
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001726 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001727 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001728}
Chris Lattner43be2e62007-12-19 23:59:04 +00001729
Chris Lattner2da14fb2007-12-20 00:26:33 +00001730/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1731/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001732bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1733 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001734 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001735 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001736 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001737 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001738 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001739 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001740 << SourceRange(TheCall->getArg(2)->getLocStart(),
1741 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001742
John Wiegley01296292011-04-08 18:41:53 +00001743 ExprResult OrigArg0 = TheCall->getArg(0);
1744 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001745
Chris Lattner2da14fb2007-12-20 00:26:33 +00001746 // Do standard promotions between the two arguments, returning their common
1747 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001748 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001749 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1750 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001751
1752 // Make sure any conversions are pushed back into the call; this is
1753 // type safe since unordered compare builtins are declared as "_Bool
1754 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001755 TheCall->setArg(0, OrigArg0.get());
1756 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001757
John Wiegley01296292011-04-08 18:41:53 +00001758 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001759 return false;
1760
Chris Lattner2da14fb2007-12-20 00:26:33 +00001761 // If the common type isn't a real floating type, then the arguments were
1762 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001763 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001764 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001765 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001766 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1767 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattner2da14fb2007-12-20 00:26:33 +00001769 return false;
1770}
1771
Benjamin Kramer634fc102010-02-15 22:42:31 +00001772/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1773/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001774/// to check everything. We expect the last argument to be a floating point
1775/// value.
1776bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1777 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001778 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001779 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001780 if (TheCall->getNumArgs() > NumArgs)
1781 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001782 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001783 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001784 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001785 (*(TheCall->arg_end()-1))->getLocEnd());
1786
Benjamin Kramer64aae502010-02-16 10:07:31 +00001787 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001788
Eli Friedman7e4faac2009-08-31 20:06:00 +00001789 if (OrigArg->isTypeDependent())
1790 return false;
1791
Chris Lattner68784ef2010-05-06 05:50:07 +00001792 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001793 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001794 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001795 diag::err_typecheck_call_invalid_unary_fp)
1796 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001797
Chris Lattner68784ef2010-05-06 05:50:07 +00001798 // If this is an implicit conversion from float -> double, remove it.
1799 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1800 Expr *CastArg = Cast->getSubExpr();
1801 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1802 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1803 "promotion from float to double is the only expected cast here");
1804 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001805 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001806 }
1807 }
1808
Eli Friedman7e4faac2009-08-31 20:06:00 +00001809 return false;
1810}
1811
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001812/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1813// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001814ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001815 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001816 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001817 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001818 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1819 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001820
Nate Begemana0110022010-06-08 00:16:34 +00001821 // Determine which of the following types of shufflevector we're checking:
1822 // 1) unary, vector mask: (lhs, mask)
1823 // 2) binary, vector mask: (lhs, rhs, mask)
1824 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1825 QualType resType = TheCall->getArg(0)->getType();
1826 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001827
Douglas Gregorc25f7662009-05-19 22:10:17 +00001828 if (!TheCall->getArg(0)->isTypeDependent() &&
1829 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001830 QualType LHSType = TheCall->getArg(0)->getType();
1831 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001832
Craig Topperbaca3892013-07-29 06:47:04 +00001833 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1834 return ExprError(Diag(TheCall->getLocStart(),
1835 diag::err_shufflevector_non_vector)
1836 << SourceRange(TheCall->getArg(0)->getLocStart(),
1837 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001838
Nate Begemana0110022010-06-08 00:16:34 +00001839 numElements = LHSType->getAs<VectorType>()->getNumElements();
1840 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001841
Nate Begemana0110022010-06-08 00:16:34 +00001842 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1843 // with mask. If so, verify that RHS is an integer vector type with the
1844 // same number of elts as lhs.
1845 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001846 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001847 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001848 return ExprError(Diag(TheCall->getLocStart(),
1849 diag::err_shufflevector_incompatible_vector)
1850 << SourceRange(TheCall->getArg(1)->getLocStart(),
1851 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001852 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001853 return ExprError(Diag(TheCall->getLocStart(),
1854 diag::err_shufflevector_incompatible_vector)
1855 << SourceRange(TheCall->getArg(0)->getLocStart(),
1856 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001857 } else if (numElements != numResElements) {
1858 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001859 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001860 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001861 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001862 }
1863
1864 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001865 if (TheCall->getArg(i)->isTypeDependent() ||
1866 TheCall->getArg(i)->isValueDependent())
1867 continue;
1868
Nate Begemana0110022010-06-08 00:16:34 +00001869 llvm::APSInt Result(32);
1870 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1871 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001872 diag::err_shufflevector_nonconstant_argument)
1873 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001874
Craig Topper50ad5b72013-08-03 17:40:38 +00001875 // Allow -1 which will be translated to undef in the IR.
1876 if (Result.isSigned() && Result.isAllOnesValue())
1877 continue;
1878
Chris Lattner7ab824e2008-08-10 02:05:13 +00001879 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001880 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001881 diag::err_shufflevector_argument_too_large)
1882 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001883 }
1884
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001885 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001886
Chris Lattner7ab824e2008-08-10 02:05:13 +00001887 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001888 exprs.push_back(TheCall->getArg(i));
1889 TheCall->setArg(i, 0);
1890 }
1891
Benjamin Kramerc215e762012-08-24 11:54:20 +00001892 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001893 TheCall->getCallee()->getLocStart(),
1894 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001895}
Chris Lattner43be2e62007-12-19 23:59:04 +00001896
Hal Finkelc4d7c822013-09-18 03:29:45 +00001897/// SemaConvertVectorExpr - Handle __builtin_convertvector
1898ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1899 SourceLocation BuiltinLoc,
1900 SourceLocation RParenLoc) {
1901 ExprValueKind VK = VK_RValue;
1902 ExprObjectKind OK = OK_Ordinary;
1903 QualType DstTy = TInfo->getType();
1904 QualType SrcTy = E->getType();
1905
1906 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1907 return ExprError(Diag(BuiltinLoc,
1908 diag::err_convertvector_non_vector)
1909 << E->getSourceRange());
1910 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1911 return ExprError(Diag(BuiltinLoc,
1912 diag::err_convertvector_non_vector_type));
1913
1914 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1915 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1916 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1917 if (SrcElts != DstElts)
1918 return ExprError(Diag(BuiltinLoc,
1919 diag::err_convertvector_incompatible_vector)
1920 << E->getSourceRange());
1921 }
1922
1923 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1924 BuiltinLoc, RParenLoc));
1925
1926}
1927
Daniel Dunbarb7257262008-07-21 22:59:13 +00001928/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1929// This is declared to take (const void*, ...) and can take two
1930// optional constant int args.
1931bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001932 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001933
Chris Lattner3b054132008-11-19 05:08:23 +00001934 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001935 return Diag(TheCall->getLocEnd(),
1936 diag::err_typecheck_call_too_many_args_at_most)
1937 << 0 /*function call*/ << 3 << NumArgs
1938 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001939
1940 // Argument 0 is checked for us and the remaining arguments must be
1941 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001942 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001943 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001944
1945 // We can't check the value of a dependent argument.
1946 if (Arg->isTypeDependent() || Arg->isValueDependent())
1947 continue;
1948
Eli Friedman5efba262009-12-04 00:30:06 +00001949 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001950 if (SemaBuiltinConstantArg(TheCall, i, Result))
1951 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001952
Daniel Dunbarb7257262008-07-21 22:59:13 +00001953 // FIXME: gcc issues a warning and rewrites these to 0. These
1954 // seems especially odd for the third argument since the default
1955 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001956 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001957 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001958 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001959 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001960 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001961 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001962 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001963 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001964 }
1965 }
1966
Chris Lattner3b054132008-11-19 05:08:23 +00001967 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001968}
1969
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001970/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1971// This is declared to take (const char*, int)
1972bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1973 Expr *Arg = TheCall->getArg(1);
1974
1975 // We can't check the value of a dependent argument.
1976 if (Arg->isTypeDependent() || Arg->isValueDependent())
1977 return false;
1978
1979 llvm::APSInt Result;
1980 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1981 return true;
1982
1983 if (Result.getLimitedValue() > 3)
1984 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1985 << "0" << "3" << Arg->getSourceRange();
1986
1987 return false;
1988}
1989
Eric Christopher8d0c6212010-04-17 02:26:23 +00001990/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1991/// TheCall is a constant expression.
1992bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1993 llvm::APSInt &Result) {
1994 Expr *Arg = TheCall->getArg(ArgNum);
1995 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1996 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1997
1998 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1999
2000 if (!Arg->isIntegerConstantExpr(Result, Context))
2001 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002002 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002003
Chris Lattnerd545ad12009-09-23 06:06:36 +00002004 return false;
2005}
2006
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002007/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
2008/// int type). This simply type checks that type is one of the defined
2009/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00002010// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002011bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002012 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002013
2014 // We can't check the value of a dependent argument.
2015 if (TheCall->getArg(1)->isTypeDependent() ||
2016 TheCall->getArg(1)->isValueDependent())
2017 return false;
2018
Eric Christopher8d0c6212010-04-17 02:26:23 +00002019 // Check constant-ness first.
2020 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2021 return true;
2022
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002023 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002024 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00002025 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2026 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002027 }
2028
2029 return false;
2030}
2031
Eli Friedmanc97d0142009-05-03 06:04:26 +00002032/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002033/// This checks that val is a constant 1.
2034bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2035 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002036 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002037
Eric Christopher8d0c6212010-04-17 02:26:23 +00002038 // TODO: This is less than ideal. Overload this to take a value.
2039 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2040 return true;
2041
2042 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002043 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2044 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2045
2046 return false;
2047}
2048
Richard Smithd7293d72013-08-05 18:49:43 +00002049namespace {
2050enum StringLiteralCheckType {
2051 SLCT_NotALiteral,
2052 SLCT_UncheckedLiteral,
2053 SLCT_CheckedLiteral
2054};
2055}
2056
Richard Smith55ce3522012-06-25 20:30:08 +00002057// Determine if an expression is a string literal or constant string.
2058// If this function returns false on the arguments to a function expecting a
2059// format string, we will usually need to emit a warning.
2060// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002061static StringLiteralCheckType
2062checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2063 bool HasVAListArg, unsigned format_idx,
2064 unsigned firstDataArg, Sema::FormatStringType Type,
2065 Sema::VariadicCallType CallType, bool InFunctionCall,
2066 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002067 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002068 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002069 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002070
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002071 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002072
Richard Smithd7293d72013-08-05 18:49:43 +00002073 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002074 // Technically -Wformat-nonliteral does not warn about this case.
2075 // The behavior of printf and friends in this case is implementation
2076 // dependent. Ideally if the format string cannot be null then
2077 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002078 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002079
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002080 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002081 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002082 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002083 // The expression is a literal if both sub-expressions were, and it was
2084 // completely checked only if both sub-expressions were checked.
2085 const AbstractConditionalOperator *C =
2086 cast<AbstractConditionalOperator>(E);
2087 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002088 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002089 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002090 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002091 if (Left == SLCT_NotALiteral)
2092 return SLCT_NotALiteral;
2093 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002094 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002095 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002096 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002097 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002098 }
2099
2100 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002101 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2102 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002103 }
2104
John McCallc07a0c72011-02-17 10:25:35 +00002105 case Stmt::OpaqueValueExprClass:
2106 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2107 E = src;
2108 goto tryAgain;
2109 }
Richard Smith55ce3522012-06-25 20:30:08 +00002110 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002111
Ted Kremeneka8890832011-02-24 23:03:04 +00002112 case Stmt::PredefinedExprClass:
2113 // While __func__, etc., are technically not string literals, they
2114 // cannot contain format specifiers and thus are not a security
2115 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002116 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002117
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002118 case Stmt::DeclRefExprClass: {
2119 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002120
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002121 // As an exception, do not flag errors for variables binding to
2122 // const string literals.
2123 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2124 bool isConstant = false;
2125 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002126
Richard Smithd7293d72013-08-05 18:49:43 +00002127 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2128 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002129 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002130 isConstant = T.isConstant(S.Context) &&
2131 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002132 } else if (T->isObjCObjectPointerType()) {
2133 // In ObjC, there is usually no "const ObjectPointer" type,
2134 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002135 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002136 }
Mike Stump11289f42009-09-09 15:08:12 +00002137
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002138 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002139 if (const Expr *Init = VD->getAnyInitializer()) {
2140 // Look through initializers like const char c[] = { "foo" }
2141 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2142 if (InitList->isStringLiteralInit())
2143 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2144 }
Richard Smithd7293d72013-08-05 18:49:43 +00002145 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002146 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002147 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002148 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002149 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002150 }
Mike Stump11289f42009-09-09 15:08:12 +00002151
Anders Carlssonb012ca92009-06-28 19:55:58 +00002152 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2153 // special check to see if the format string is a function parameter
2154 // of the function calling the printf function. If the function
2155 // has an attribute indicating it is a printf-like function, then we
2156 // should suppress warnings concerning non-literals being used in a call
2157 // to a vprintf function. For example:
2158 //
2159 // void
2160 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2161 // va_list ap;
2162 // va_start(ap, fmt);
2163 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2164 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002165 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002166 if (HasVAListArg) {
2167 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2168 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2169 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002170 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002171 // adjust for implicit parameter
2172 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2173 if (MD->isInstance())
2174 ++PVIndex;
2175 // We also check if the formats are compatible.
2176 // We can't pass a 'scanf' string to a 'printf' function.
2177 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002178 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002179 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002180 }
2181 }
2182 }
2183 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Richard Smith55ce3522012-06-25 20:30:08 +00002186 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002187 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002188
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002189 case Stmt::CallExprClass:
2190 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002191 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002192 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2193 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2194 unsigned ArgIndex = FA->getFormatIdx();
2195 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2196 if (MD->isInstance())
2197 --ArgIndex;
2198 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002199
Richard Smithd7293d72013-08-05 18:49:43 +00002200 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002201 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002202 Type, CallType, InFunctionCall,
2203 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002204 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2205 unsigned BuiltinID = FD->getBuiltinID();
2206 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2207 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2208 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002209 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002210 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002211 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002212 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002213 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002214 }
2215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Richard Smith55ce3522012-06-25 20:30:08 +00002217 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002218 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002219 case Stmt::ObjCStringLiteralClass:
2220 case Stmt::StringLiteralClass: {
2221 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002222
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002223 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002224 StrE = ObjCFExpr->getString();
2225 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002226 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002227
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002228 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002229 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2230 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002231 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002232 }
Mike Stump11289f42009-09-09 15:08:12 +00002233
Richard Smith55ce3522012-06-25 20:30:08 +00002234 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002235 }
Mike Stump11289f42009-09-09 15:08:12 +00002236
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002237 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002238 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002239 }
2240}
2241
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002242Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002243 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002244 .Case("scanf", FST_Scanf)
2245 .Cases("printf", "printf0", FST_Printf)
2246 .Cases("NSString", "CFString", FST_NSString)
2247 .Case("strftime", FST_Strftime)
2248 .Case("strfmon", FST_Strfmon)
2249 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2250 .Default(FST_Unknown);
2251}
2252
Jordan Rose3e0ec582012-07-19 18:10:23 +00002253/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002254/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002255/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002256bool Sema::CheckFormatArguments(const FormatAttr *Format,
2257 ArrayRef<const Expr *> Args,
2258 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002259 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002260 SourceLocation Loc, SourceRange Range,
2261 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002262 FormatStringInfo FSI;
2263 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002264 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002265 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002266 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002267 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002268}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002269
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002270bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002271 bool HasVAListArg, unsigned format_idx,
2272 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002273 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002274 SourceLocation Loc, SourceRange Range,
2275 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002276 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002277 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002278 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002279 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002280 }
Mike Stump11289f42009-09-09 15:08:12 +00002281
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002282 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002283
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002284 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002285 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002286 // Dynamically generated format strings are difficult to
2287 // automatically vet at compile time. Requiring that format strings
2288 // are string literals: (1) permits the checking of format strings by
2289 // the compiler and thereby (2) can practically remove the source of
2290 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002291
Mike Stump11289f42009-09-09 15:08:12 +00002292 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002293 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002294 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002295 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002296 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002297 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2298 format_idx, firstDataArg, Type, CallType,
2299 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002300 if (CT != SLCT_NotALiteral)
2301 // Literal format string found, check done!
2302 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002303
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002304 // Strftime is particular as it always uses a single 'time' argument,
2305 // so it is safe to pass a non-literal string.
2306 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002307 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002308
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002309 // Do not emit diag when the string param is a macro expansion and the
2310 // format is either NSString or CFString. This is a hack to prevent
2311 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2312 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002313 if (Type == FST_NSString &&
2314 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002315 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002316
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002317 // If there are no arguments specified, warn with -Wformat-security, otherwise
2318 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002319 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002320 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002321 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002322 << OrigFormatExpr->getSourceRange();
2323 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002324 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002325 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002326 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002327 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002328}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002329
Ted Kremenekab278de2010-01-28 23:39:18 +00002330namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002331class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2332protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002333 Sema &S;
2334 const StringLiteral *FExpr;
2335 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002336 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002337 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002338 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002339 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002340 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002341 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002342 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002343 bool usesPositionalArgs;
2344 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002345 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002346 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002347 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002348public:
Ted Kremenek02087932010-07-16 02:11:22 +00002349 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002350 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002351 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002352 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002353 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002354 Sema::VariadicCallType callType,
2355 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002356 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002357 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2358 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002359 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002360 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002361 inFunctionCall(inFunctionCall), CallType(callType),
2362 CheckedVarArgs(CheckedVarArgs) {
2363 CoveredArgs.resize(numDataArgs);
2364 CoveredArgs.reset();
2365 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002366
Ted Kremenek019d2242010-01-29 01:50:07 +00002367 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002368
Ted Kremenek02087932010-07-16 02:11:22 +00002369 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002370 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002371
Jordan Rose92303592012-09-08 04:00:03 +00002372 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002373 const analyze_format_string::FormatSpecifier &FS,
2374 const analyze_format_string::ConversionSpecifier &CS,
2375 const char *startSpecifier, unsigned specifierLen,
2376 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002377
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002378 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002379 const analyze_format_string::FormatSpecifier &FS,
2380 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002381
2382 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002383 const analyze_format_string::ConversionSpecifier &CS,
2384 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002385
Craig Toppere14c0f82014-03-12 04:55:44 +00002386 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002387
Craig Toppere14c0f82014-03-12 04:55:44 +00002388 void HandleInvalidPosition(const char *startSpecifier,
2389 unsigned specifierLen,
2390 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002391
Craig Toppere14c0f82014-03-12 04:55:44 +00002392 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002393
Craig Toppere14c0f82014-03-12 04:55:44 +00002394 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002395
Richard Trieu03cf7b72011-10-28 00:41:25 +00002396 template <typename Range>
2397 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2398 const Expr *ArgumentExpr,
2399 PartialDiagnostic PDiag,
2400 SourceLocation StringLoc,
2401 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002402 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002403
Ted Kremenek02087932010-07-16 02:11:22 +00002404protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002405 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2406 const char *startSpec,
2407 unsigned specifierLen,
2408 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002409
2410 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2411 const char *startSpec,
2412 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002413
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002414 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002415 CharSourceRange getSpecifierRange(const char *startSpecifier,
2416 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002417 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002418
Ted Kremenek5739de72010-01-29 01:06:55 +00002419 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002420
2421 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2422 const analyze_format_string::ConversionSpecifier &CS,
2423 const char *startSpecifier, unsigned specifierLen,
2424 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002425
2426 template <typename Range>
2427 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2428 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002429 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002430};
2431}
2432
Ted Kremenek02087932010-07-16 02:11:22 +00002433SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002434 return OrigFormatExpr->getSourceRange();
2435}
2436
Ted Kremenek02087932010-07-16 02:11:22 +00002437CharSourceRange CheckFormatHandler::
2438getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002439 SourceLocation Start = getLocationOfByte(startSpecifier);
2440 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2441
2442 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002443 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002444
2445 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002446}
2447
Ted Kremenek02087932010-07-16 02:11:22 +00002448SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002449 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002450}
2451
Ted Kremenek02087932010-07-16 02:11:22 +00002452void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2453 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002454 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2455 getLocationOfByte(startSpecifier),
2456 /*IsStringLocation*/true,
2457 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002458}
2459
Jordan Rose92303592012-09-08 04:00:03 +00002460void CheckFormatHandler::HandleInvalidLengthModifier(
2461 const analyze_format_string::FormatSpecifier &FS,
2462 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002463 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002464 using namespace analyze_format_string;
2465
2466 const LengthModifier &LM = FS.getLengthModifier();
2467 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2468
2469 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002470 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002471 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002472 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002473 getLocationOfByte(LM.getStart()),
2474 /*IsStringLocation*/true,
2475 getSpecifierRange(startSpecifier, specifierLen));
2476
2477 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478 << FixedLM->toString()
2479 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2480
2481 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002482 FixItHint Hint;
2483 if (DiagID == diag::warn_format_nonsensical_length)
2484 Hint = FixItHint::CreateRemoval(LMRange);
2485
2486 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002487 getLocationOfByte(LM.getStart()),
2488 /*IsStringLocation*/true,
2489 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002490 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002491 }
2492}
2493
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002494void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002495 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002496 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002497 using namespace analyze_format_string;
2498
2499 const LengthModifier &LM = FS.getLengthModifier();
2500 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2501
2502 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002503 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002504 if (FixedLM) {
2505 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2506 << LM.toString() << 0,
2507 getLocationOfByte(LM.getStart()),
2508 /*IsStringLocation*/true,
2509 getSpecifierRange(startSpecifier, specifierLen));
2510
2511 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2512 << FixedLM->toString()
2513 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2514
2515 } else {
2516 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2517 << LM.toString() << 0,
2518 getLocationOfByte(LM.getStart()),
2519 /*IsStringLocation*/true,
2520 getSpecifierRange(startSpecifier, specifierLen));
2521 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002522}
2523
2524void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2525 const analyze_format_string::ConversionSpecifier &CS,
2526 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002527 using namespace analyze_format_string;
2528
2529 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002530 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002531 if (FixedCS) {
2532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2533 << CS.toString() << /*conversion specifier*/1,
2534 getLocationOfByte(CS.getStart()),
2535 /*IsStringLocation*/true,
2536 getSpecifierRange(startSpecifier, specifierLen));
2537
2538 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2539 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2540 << FixedCS->toString()
2541 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2542 } else {
2543 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2544 << CS.toString() << /*conversion specifier*/1,
2545 getLocationOfByte(CS.getStart()),
2546 /*IsStringLocation*/true,
2547 getSpecifierRange(startSpecifier, specifierLen));
2548 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002549}
2550
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002551void CheckFormatHandler::HandlePosition(const char *startPos,
2552 unsigned posLen) {
2553 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2554 getLocationOfByte(startPos),
2555 /*IsStringLocation*/true,
2556 getSpecifierRange(startPos, posLen));
2557}
2558
Ted Kremenekd1668192010-02-27 01:41:03 +00002559void
Ted Kremenek02087932010-07-16 02:11:22 +00002560CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2561 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002562 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2563 << (unsigned) p,
2564 getLocationOfByte(startPos), /*IsStringLocation*/true,
2565 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002566}
2567
Ted Kremenek02087932010-07-16 02:11:22 +00002568void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002569 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002570 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2571 getLocationOfByte(startPos),
2572 /*IsStringLocation*/true,
2573 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002574}
2575
Ted Kremenek02087932010-07-16 02:11:22 +00002576void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002577 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002578 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002579 EmitFormatDiagnostic(
2580 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2581 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2582 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002583 }
Ted Kremenek02087932010-07-16 02:11:22 +00002584}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002585
Jordan Rose58bbe422012-07-19 18:10:08 +00002586// Note that this may return NULL if there was an error parsing or building
2587// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002588const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002589 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002590}
2591
2592void CheckFormatHandler::DoneProcessing() {
2593 // Does the number of data arguments exceed the number of
2594 // format conversions in the format string?
2595 if (!HasVAListArg) {
2596 // Find any arguments that weren't covered.
2597 CoveredArgs.flip();
2598 signed notCoveredArg = CoveredArgs.find_first();
2599 if (notCoveredArg >= 0) {
2600 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002601 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2602 SourceLocation Loc = E->getLocStart();
2603 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2604 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2605 Loc, /*IsStringLocation*/false,
2606 getFormatStringRange());
2607 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002608 }
Ted Kremenek02087932010-07-16 02:11:22 +00002609 }
2610 }
2611}
2612
Ted Kremenekce815422010-07-19 21:25:57 +00002613bool
2614CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2615 SourceLocation Loc,
2616 const char *startSpec,
2617 unsigned specifierLen,
2618 const char *csStart,
2619 unsigned csLen) {
2620
2621 bool keepGoing = true;
2622 if (argIndex < NumDataArgs) {
2623 // Consider the argument coverered, even though the specifier doesn't
2624 // make sense.
2625 CoveredArgs.set(argIndex);
2626 }
2627 else {
2628 // If argIndex exceeds the number of data arguments we
2629 // don't issue a warning because that is just a cascade of warnings (and
2630 // they may have intended '%%' anyway). We don't want to continue processing
2631 // the format string after this point, however, as we will like just get
2632 // gibberish when trying to match arguments.
2633 keepGoing = false;
2634 }
2635
Richard Trieu03cf7b72011-10-28 00:41:25 +00002636 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2637 << StringRef(csStart, csLen),
2638 Loc, /*IsStringLocation*/true,
2639 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002640
2641 return keepGoing;
2642}
2643
Richard Trieu03cf7b72011-10-28 00:41:25 +00002644void
2645CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2646 const char *startSpec,
2647 unsigned specifierLen) {
2648 EmitFormatDiagnostic(
2649 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2650 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2651}
2652
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002653bool
2654CheckFormatHandler::CheckNumArgs(
2655 const analyze_format_string::FormatSpecifier &FS,
2656 const analyze_format_string::ConversionSpecifier &CS,
2657 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2658
2659 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002660 PartialDiagnostic PDiag = FS.usesPositionalArg()
2661 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2662 << (argIndex+1) << NumDataArgs)
2663 : S.PDiag(diag::warn_printf_insufficient_data_args);
2664 EmitFormatDiagnostic(
2665 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2666 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002667 return false;
2668 }
2669 return true;
2670}
2671
Richard Trieu03cf7b72011-10-28 00:41:25 +00002672template<typename Range>
2673void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2674 SourceLocation Loc,
2675 bool IsStringLocation,
2676 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002677 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002678 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002679 Loc, IsStringLocation, StringRange, FixIt);
2680}
2681
2682/// \brief If the format string is not within the funcion call, emit a note
2683/// so that the function call and string are in diagnostic messages.
2684///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002685/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002686/// call and only one diagnostic message will be produced. Otherwise, an
2687/// extra note will be emitted pointing to location of the format string.
2688///
2689/// \param ArgumentExpr the expression that is passed as the format string
2690/// argument in the function call. Used for getting locations when two
2691/// diagnostics are emitted.
2692///
2693/// \param PDiag the callee should already have provided any strings for the
2694/// diagnostic message. This function only adds locations and fixits
2695/// to diagnostics.
2696///
2697/// \param Loc primary location for diagnostic. If two diagnostics are
2698/// required, one will be at Loc and a new SourceLocation will be created for
2699/// the other one.
2700///
2701/// \param IsStringLocation if true, Loc points to the format string should be
2702/// used for the note. Otherwise, Loc points to the argument list and will
2703/// be used with PDiag.
2704///
2705/// \param StringRange some or all of the string to highlight. This is
2706/// templated so it can accept either a CharSourceRange or a SourceRange.
2707///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002708/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002709template<typename Range>
2710void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2711 const Expr *ArgumentExpr,
2712 PartialDiagnostic PDiag,
2713 SourceLocation Loc,
2714 bool IsStringLocation,
2715 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002716 ArrayRef<FixItHint> FixIt) {
2717 if (InFunctionCall) {
2718 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2719 D << StringRange;
2720 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2721 I != E; ++I) {
2722 D << *I;
2723 }
2724 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002725 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2726 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002727
2728 const Sema::SemaDiagnosticBuilder &Note =
2729 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2730 diag::note_format_string_defined);
2731
2732 Note << StringRange;
2733 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2734 I != E; ++I) {
2735 Note << *I;
2736 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002737 }
2738}
2739
Ted Kremenek02087932010-07-16 02:11:22 +00002740//===--- CHECK: Printf format string checking ------------------------------===//
2741
2742namespace {
2743class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002744 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002745public:
2746 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2747 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002748 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002749 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002750 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002751 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002752 Sema::VariadicCallType CallType,
2753 llvm::SmallBitVector &CheckedVarArgs)
2754 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2755 numDataArgs, beg, hasVAListArg, Args,
2756 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2757 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002758 {}
2759
Craig Toppere14c0f82014-03-12 04:55:44 +00002760
Ted Kremenek02087932010-07-16 02:11:22 +00002761 bool HandleInvalidPrintfConversionSpecifier(
2762 const analyze_printf::PrintfSpecifier &FS,
2763 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002764 unsigned specifierLen) override;
2765
Ted Kremenek02087932010-07-16 02:11:22 +00002766 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2767 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002768 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002769 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2770 const char *StartSpecifier,
2771 unsigned SpecifierLen,
2772 const Expr *E);
2773
Ted Kremenek02087932010-07-16 02:11:22 +00002774 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2775 const char *startSpecifier, unsigned specifierLen);
2776 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2777 const analyze_printf::OptionalAmount &Amt,
2778 unsigned type,
2779 const char *startSpecifier, unsigned specifierLen);
2780 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2781 const analyze_printf::OptionalFlag &flag,
2782 const char *startSpecifier, unsigned specifierLen);
2783 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2784 const analyze_printf::OptionalFlag &ignoredFlag,
2785 const analyze_printf::OptionalFlag &flag,
2786 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002787 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002788 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002789
Ted Kremenek02087932010-07-16 02:11:22 +00002790};
2791}
2792
2793bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2794 const analyze_printf::PrintfSpecifier &FS,
2795 const char *startSpecifier,
2796 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002797 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002798 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002799
Ted Kremenekce815422010-07-19 21:25:57 +00002800 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2801 getLocationOfByte(CS.getStart()),
2802 startSpecifier, specifierLen,
2803 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002804}
2805
Ted Kremenek02087932010-07-16 02:11:22 +00002806bool CheckPrintfHandler::HandleAmount(
2807 const analyze_format_string::OptionalAmount &Amt,
2808 unsigned k, const char *startSpecifier,
2809 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002810
2811 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002812 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002813 unsigned argIndex = Amt.getArgIndex();
2814 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002815 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2816 << k,
2817 getLocationOfByte(Amt.getStart()),
2818 /*IsStringLocation*/true,
2819 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002820 // Don't do any more checking. We will just emit
2821 // spurious errors.
2822 return false;
2823 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002824
Ted Kremenek5739de72010-01-29 01:06:55 +00002825 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002826 // Although not in conformance with C99, we also allow the argument to be
2827 // an 'unsigned int' as that is a reasonably safe case. GCC also
2828 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002829 CoveredArgs.set(argIndex);
2830 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002831 if (!Arg)
2832 return false;
2833
Ted Kremenek5739de72010-01-29 01:06:55 +00002834 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002835
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002836 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2837 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002838
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002839 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002840 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002841 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 << T << Arg->getSourceRange(),
2843 getLocationOfByte(Amt.getStart()),
2844 /*IsStringLocation*/true,
2845 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002846 // Don't do any more checking. We will just emit
2847 // spurious errors.
2848 return false;
2849 }
2850 }
2851 }
2852 return true;
2853}
Ted Kremenek5739de72010-01-29 01:06:55 +00002854
Tom Careb49ec692010-06-17 19:00:27 +00002855void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002856 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002857 const analyze_printf::OptionalAmount &Amt,
2858 unsigned type,
2859 const char *startSpecifier,
2860 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002861 const analyze_printf::PrintfConversionSpecifier &CS =
2862 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002863
Richard Trieu03cf7b72011-10-28 00:41:25 +00002864 FixItHint fixit =
2865 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2866 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2867 Amt.getConstantLength()))
2868 : FixItHint();
2869
2870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2871 << type << CS.toString(),
2872 getLocationOfByte(Amt.getStart()),
2873 /*IsStringLocation*/true,
2874 getSpecifierRange(startSpecifier, specifierLen),
2875 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002876}
2877
Ted Kremenek02087932010-07-16 02:11:22 +00002878void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002879 const analyze_printf::OptionalFlag &flag,
2880 const char *startSpecifier,
2881 unsigned specifierLen) {
2882 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002883 const analyze_printf::PrintfConversionSpecifier &CS =
2884 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002885 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2886 << flag.toString() << CS.toString(),
2887 getLocationOfByte(flag.getPosition()),
2888 /*IsStringLocation*/true,
2889 getSpecifierRange(startSpecifier, specifierLen),
2890 FixItHint::CreateRemoval(
2891 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002892}
2893
2894void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002895 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002896 const analyze_printf::OptionalFlag &ignoredFlag,
2897 const analyze_printf::OptionalFlag &flag,
2898 const char *startSpecifier,
2899 unsigned specifierLen) {
2900 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002901 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2902 << ignoredFlag.toString() << flag.toString(),
2903 getLocationOfByte(ignoredFlag.getPosition()),
2904 /*IsStringLocation*/true,
2905 getSpecifierRange(startSpecifier, specifierLen),
2906 FixItHint::CreateRemoval(
2907 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002908}
2909
Richard Smith55ce3522012-06-25 20:30:08 +00002910// Determines if the specified is a C++ class or struct containing
2911// a member with the specified name and kind (e.g. a CXXMethodDecl named
2912// "c_str()").
2913template<typename MemberKind>
2914static llvm::SmallPtrSet<MemberKind*, 1>
2915CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2916 const RecordType *RT = Ty->getAs<RecordType>();
2917 llvm::SmallPtrSet<MemberKind*, 1> Results;
2918
2919 if (!RT)
2920 return Results;
2921 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002922 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002923 return Results;
2924
2925 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2926 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002927 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002928
2929 // We just need to include all members of the right kind turned up by the
2930 // filter, at this point.
2931 if (S.LookupQualifiedName(R, RT->getDecl()))
2932 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2933 NamedDecl *decl = (*I)->getUnderlyingDecl();
2934 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2935 Results.insert(FK);
2936 }
2937 return Results;
2938}
2939
Richard Smith2868a732014-02-28 01:36:39 +00002940/// Check if we could call '.c_str()' on an object.
2941///
2942/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2943/// allow the call, or if it would be ambiguous).
2944bool Sema::hasCStrMethod(const Expr *E) {
2945 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2946 MethodSet Results =
2947 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2948 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2949 MI != ME; ++MI)
2950 if ((*MI)->getMinRequiredArguments() == 0)
2951 return true;
2952 return false;
2953}
2954
Richard Smith55ce3522012-06-25 20:30:08 +00002955// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002956// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002957// Returns true when a c_str() conversion method is found.
2958bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002959 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002960 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2961
2962 MethodSet Results =
2963 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2964
2965 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2966 MI != ME; ++MI) {
2967 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002968 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002969 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002970 // FIXME: Suggest parens if the expression needs them.
2971 SourceLocation EndLoc =
2972 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2973 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2974 << "c_str()"
2975 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2976 return true;
2977 }
2978 }
2979
2980 return false;
2981}
2982
Ted Kremenekab278de2010-01-28 23:39:18 +00002983bool
Ted Kremenek02087932010-07-16 02:11:22 +00002984CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002985 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002986 const char *startSpecifier,
2987 unsigned specifierLen) {
2988
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002989 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002990 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002991 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002992
Ted Kremenek6cd69422010-07-19 22:01:06 +00002993 if (FS.consumesDataArgument()) {
2994 if (atFirstArg) {
2995 atFirstArg = false;
2996 usesPositionalArgs = FS.usesPositionalArg();
2997 }
2998 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002999 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3000 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003001 return false;
3002 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003003 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003004
Ted Kremenekd1668192010-02-27 01:41:03 +00003005 // First check if the field width, precision, and conversion specifier
3006 // have matching data arguments.
3007 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3008 startSpecifier, specifierLen)) {
3009 return false;
3010 }
3011
3012 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3013 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003014 return false;
3015 }
3016
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003017 if (!CS.consumesDataArgument()) {
3018 // FIXME: Technically specifying a precision or field width here
3019 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003020 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003021 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003022
Ted Kremenek4a49d982010-02-26 19:18:41 +00003023 // Consume the argument.
3024 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003025 if (argIndex < NumDataArgs) {
3026 // The check to see if the argIndex is valid will come later.
3027 // We set the bit here because we may exit early from this
3028 // function if we encounter some other error.
3029 CoveredArgs.set(argIndex);
3030 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003031
3032 // Check for using an Objective-C specific conversion specifier
3033 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003034 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003035 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3036 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003037 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003038
Tom Careb49ec692010-06-17 19:00:27 +00003039 // Check for invalid use of field width
3040 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003041 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003042 startSpecifier, specifierLen);
3043 }
3044
3045 // Check for invalid use of precision
3046 if (!FS.hasValidPrecision()) {
3047 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3048 startSpecifier, specifierLen);
3049 }
3050
3051 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003052 if (!FS.hasValidThousandsGroupingPrefix())
3053 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003054 if (!FS.hasValidLeadingZeros())
3055 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3056 if (!FS.hasValidPlusPrefix())
3057 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003058 if (!FS.hasValidSpacePrefix())
3059 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003060 if (!FS.hasValidAlternativeForm())
3061 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3062 if (!FS.hasValidLeftJustified())
3063 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3064
3065 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003066 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3067 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3068 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003069 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3070 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3071 startSpecifier, specifierLen);
3072
3073 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003074 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003075 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3076 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003077 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003078 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003079 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003080 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3081 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003082
Jordan Rose92303592012-09-08 04:00:03 +00003083 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3084 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3085
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003086 // The remaining checks depend on the data arguments.
3087 if (HasVAListArg)
3088 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003089
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003090 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003091 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003092
Jordan Rose58bbe422012-07-19 18:10:08 +00003093 const Expr *Arg = getDataArg(argIndex);
3094 if (!Arg)
3095 return true;
3096
3097 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003098}
3099
Jordan Roseaee34382012-09-05 22:56:26 +00003100static bool requiresParensToAddCast(const Expr *E) {
3101 // FIXME: We should have a general way to reason about operator
3102 // precedence and whether parens are actually needed here.
3103 // Take care of a few common cases where they aren't.
3104 const Expr *Inside = E->IgnoreImpCasts();
3105 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3106 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3107
3108 switch (Inside->getStmtClass()) {
3109 case Stmt::ArraySubscriptExprClass:
3110 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003111 case Stmt::CharacterLiteralClass:
3112 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003113 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003114 case Stmt::FloatingLiteralClass:
3115 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003116 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003117 case Stmt::ObjCArrayLiteralClass:
3118 case Stmt::ObjCBoolLiteralExprClass:
3119 case Stmt::ObjCBoxedExprClass:
3120 case Stmt::ObjCDictionaryLiteralClass:
3121 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003122 case Stmt::ObjCIvarRefExprClass:
3123 case Stmt::ObjCMessageExprClass:
3124 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003125 case Stmt::ObjCStringLiteralClass:
3126 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003127 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003128 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003129 case Stmt::UnaryOperatorClass:
3130 return false;
3131 default:
3132 return true;
3133 }
3134}
3135
Richard Smith55ce3522012-06-25 20:30:08 +00003136bool
3137CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3138 const char *StartSpecifier,
3139 unsigned SpecifierLen,
3140 const Expr *E) {
3141 using namespace analyze_format_string;
3142 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003143 // Now type check the data expression that matches the
3144 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003145 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3146 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003147 if (!AT.isValid())
3148 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003149
Jordan Rose598ec092012-12-05 18:44:40 +00003150 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003151 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3152 ExprTy = TET->getUnderlyingExpr()->getType();
3153 }
3154
Jordan Rose598ec092012-12-05 18:44:40 +00003155 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003156 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003157
Jordan Rose22b74712012-09-05 22:56:19 +00003158 // Look through argument promotions for our error message's reported type.
3159 // This includes the integral and floating promotions, but excludes array
3160 // and function pointer decay; seeing that an argument intended to be a
3161 // string has type 'char [6]' is probably more confusing than 'char *'.
3162 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3163 if (ICE->getCastKind() == CK_IntegralCast ||
3164 ICE->getCastKind() == CK_FloatingCast) {
3165 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003166 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003167
3168 // Check if we didn't match because of an implicit cast from a 'char'
3169 // or 'short' to an 'int'. This is done because printf is a varargs
3170 // function.
3171 if (ICE->getType() == S.Context.IntTy ||
3172 ICE->getType() == S.Context.UnsignedIntTy) {
3173 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003174 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003175 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003176 }
Jordan Rose98709982012-06-04 22:48:57 +00003177 }
Jordan Rose598ec092012-12-05 18:44:40 +00003178 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3179 // Special case for 'a', which has type 'int' in C.
3180 // Note, however, that we do /not/ want to treat multibyte constants like
3181 // 'MooV' as characters! This form is deprecated but still exists.
3182 if (ExprTy == S.Context.IntTy)
3183 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3184 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003185 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003186
Jordan Rose0e5badd2012-12-05 18:44:49 +00003187 // %C in an Objective-C context prints a unichar, not a wchar_t.
3188 // If the argument is an integer of some kind, believe the %C and suggest
3189 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003190 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003191 if (ObjCContext &&
3192 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3193 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3194 !ExprTy->isCharType()) {
3195 // 'unichar' is defined as a typedef of unsigned short, but we should
3196 // prefer using the typedef if it is visible.
3197 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003198
3199 // While we are here, check if the value is an IntegerLiteral that happens
3200 // to be within the valid range.
3201 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3202 const llvm::APInt &V = IL->getValue();
3203 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3204 return true;
3205 }
3206
Jordan Rose0e5badd2012-12-05 18:44:49 +00003207 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3208 Sema::LookupOrdinaryName);
3209 if (S.LookupName(Result, S.getCurScope())) {
3210 NamedDecl *ND = Result.getFoundDecl();
3211 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3212 if (TD->getUnderlyingType() == IntendedTy)
3213 IntendedTy = S.Context.getTypedefType(TD);
3214 }
3215 }
3216 }
3217
3218 // Special-case some of Darwin's platform-independence types by suggesting
3219 // casts to primitive types that are known to be large enough.
3220 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003221 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003222 // Use a 'while' to peel off layers of typedefs.
3223 QualType TyTy = IntendedTy;
3224 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003225 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003226 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003227 .Case("NSInteger", S.Context.LongTy)
3228 .Case("NSUInteger", S.Context.UnsignedLongTy)
3229 .Case("SInt32", S.Context.IntTy)
3230 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003231 .Default(QualType());
3232
3233 if (!CastTy.isNull()) {
3234 ShouldNotPrintDirectly = true;
3235 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003236 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003237 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003238 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003239 }
3240 }
3241
Jordan Rose22b74712012-09-05 22:56:19 +00003242 // We may be able to offer a FixItHint if it is a supported type.
3243 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003244 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003245 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003246
Jordan Rose22b74712012-09-05 22:56:19 +00003247 if (success) {
3248 // Get the fix string from the fixed format specifier
3249 SmallString<16> buf;
3250 llvm::raw_svector_ostream os(buf);
3251 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003252
Jordan Roseaee34382012-09-05 22:56:26 +00003253 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3254
Jordan Rose0e5badd2012-12-05 18:44:49 +00003255 if (IntendedTy == ExprTy) {
3256 // In this case, the specifier is wrong and should be changed to match
3257 // the argument.
3258 EmitFormatDiagnostic(
3259 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3260 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3261 << E->getSourceRange(),
3262 E->getLocStart(),
3263 /*IsStringLocation*/false,
3264 SpecRange,
3265 FixItHint::CreateReplacement(SpecRange, os.str()));
3266
3267 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003268 // The canonical type for formatting this value is different from the
3269 // actual type of the expression. (This occurs, for example, with Darwin's
3270 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3271 // should be printed as 'long' for 64-bit compatibility.)
3272 // Rather than emitting a normal format/argument mismatch, we want to
3273 // add a cast to the recommended type (and correct the format string
3274 // if necessary).
3275 SmallString<16> CastBuf;
3276 llvm::raw_svector_ostream CastFix(CastBuf);
3277 CastFix << "(";
3278 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3279 CastFix << ")";
3280
3281 SmallVector<FixItHint,4> Hints;
3282 if (!AT.matchesType(S.Context, IntendedTy))
3283 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3284
3285 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3286 // If there's already a cast present, just replace it.
3287 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3288 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3289
3290 } else if (!requiresParensToAddCast(E)) {
3291 // If the expression has high enough precedence,
3292 // just write the C-style cast.
3293 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3294 CastFix.str()));
3295 } else {
3296 // Otherwise, add parens around the expression as well as the cast.
3297 CastFix << "(";
3298 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3299 CastFix.str()));
3300
3301 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3302 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3303 }
3304
Jordan Rose0e5badd2012-12-05 18:44:49 +00003305 if (ShouldNotPrintDirectly) {
3306 // The expression has a type that should not be printed directly.
3307 // We extract the name from the typedef because we don't want to show
3308 // the underlying type in the diagnostic.
3309 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003310
Jordan Rose0e5badd2012-12-05 18:44:49 +00003311 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3312 << Name << IntendedTy
3313 << E->getSourceRange(),
3314 E->getLocStart(), /*IsStringLocation=*/false,
3315 SpecRange, Hints);
3316 } else {
3317 // In this case, the expression could be printed using a different
3318 // specifier, but we've decided that the specifier is probably correct
3319 // and we should cast instead. Just use the normal warning message.
3320 EmitFormatDiagnostic(
3321 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3322 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3323 << E->getSourceRange(),
3324 E->getLocStart(), /*IsStringLocation*/false,
3325 SpecRange, Hints);
3326 }
Jordan Roseaee34382012-09-05 22:56:26 +00003327 }
Jordan Rose22b74712012-09-05 22:56:19 +00003328 } else {
3329 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3330 SpecifierLen);
3331 // Since the warning for passing non-POD types to variadic functions
3332 // was deferred until now, we emit a warning for non-POD
3333 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003334 switch (S.isValidVarArgType(ExprTy)) {
3335 case Sema::VAK_Valid:
3336 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003337 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003338 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3339 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3340 << CSR
3341 << E->getSourceRange(),
3342 E->getLocStart(), /*IsStringLocation*/false, CSR);
3343 break;
3344
3345 case Sema::VAK_Undefined:
3346 EmitFormatDiagnostic(
3347 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003348 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003349 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003350 << CallType
3351 << AT.getRepresentativeTypeName(S.Context)
3352 << CSR
3353 << E->getSourceRange(),
3354 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003355 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003356 break;
3357
3358 case Sema::VAK_Invalid:
3359 if (ExprTy->isObjCObjectType())
3360 EmitFormatDiagnostic(
3361 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3362 << S.getLangOpts().CPlusPlus11
3363 << ExprTy
3364 << CallType
3365 << AT.getRepresentativeTypeName(S.Context)
3366 << CSR
3367 << E->getSourceRange(),
3368 E->getLocStart(), /*IsStringLocation*/false, CSR);
3369 else
3370 // FIXME: If this is an initializer list, suggest removing the braces
3371 // or inserting a cast to the target type.
3372 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3373 << isa<InitListExpr>(E) << ExprTy << CallType
3374 << AT.getRepresentativeTypeName(S.Context)
3375 << E->getSourceRange();
3376 break;
3377 }
3378
3379 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3380 "format string specifier index out of range");
3381 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003382 }
3383
Ted Kremenekab278de2010-01-28 23:39:18 +00003384 return true;
3385}
3386
Ted Kremenek02087932010-07-16 02:11:22 +00003387//===--- CHECK: Scanf format string checking ------------------------------===//
3388
3389namespace {
3390class CheckScanfHandler : public CheckFormatHandler {
3391public:
3392 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3393 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003394 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003395 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003396 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003397 Sema::VariadicCallType CallType,
3398 llvm::SmallBitVector &CheckedVarArgs)
3399 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3400 numDataArgs, beg, hasVAListArg,
3401 Args, formatIdx, inFunctionCall, CallType,
3402 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003403 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003404
3405 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3406 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003407 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003408
3409 bool HandleInvalidScanfConversionSpecifier(
3410 const analyze_scanf::ScanfSpecifier &FS,
3411 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003412 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003413
Craig Toppere14c0f82014-03-12 04:55:44 +00003414 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003415};
Ted Kremenek019d2242010-01-29 01:50:07 +00003416}
Ted Kremenekab278de2010-01-28 23:39:18 +00003417
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003418void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3419 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003420 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3421 getLocationOfByte(end), /*IsStringLocation*/true,
3422 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003423}
3424
Ted Kremenekce815422010-07-19 21:25:57 +00003425bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3426 const analyze_scanf::ScanfSpecifier &FS,
3427 const char *startSpecifier,
3428 unsigned specifierLen) {
3429
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003430 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003431 FS.getConversionSpecifier();
3432
3433 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3434 getLocationOfByte(CS.getStart()),
3435 startSpecifier, specifierLen,
3436 CS.getStart(), CS.getLength());
3437}
3438
Ted Kremenek02087932010-07-16 02:11:22 +00003439bool CheckScanfHandler::HandleScanfSpecifier(
3440 const analyze_scanf::ScanfSpecifier &FS,
3441 const char *startSpecifier,
3442 unsigned specifierLen) {
3443
3444 using namespace analyze_scanf;
3445 using namespace analyze_format_string;
3446
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003447 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003448
Ted Kremenek6cd69422010-07-19 22:01:06 +00003449 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3450 // be used to decide if we are using positional arguments consistently.
3451 if (FS.consumesDataArgument()) {
3452 if (atFirstArg) {
3453 atFirstArg = false;
3454 usesPositionalArgs = FS.usesPositionalArg();
3455 }
3456 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003457 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3458 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003459 return false;
3460 }
Ted Kremenek02087932010-07-16 02:11:22 +00003461 }
3462
3463 // Check if the field with is non-zero.
3464 const OptionalAmount &Amt = FS.getFieldWidth();
3465 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3466 if (Amt.getConstantAmount() == 0) {
3467 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3468 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003469 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3470 getLocationOfByte(Amt.getStart()),
3471 /*IsStringLocation*/true, R,
3472 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003473 }
3474 }
3475
3476 if (!FS.consumesDataArgument()) {
3477 // FIXME: Technically specifying a precision or field width here
3478 // makes no sense. Worth issuing a warning at some point.
3479 return true;
3480 }
3481
3482 // Consume the argument.
3483 unsigned argIndex = FS.getArgIndex();
3484 if (argIndex < NumDataArgs) {
3485 // The check to see if the argIndex is valid will come later.
3486 // We set the bit here because we may exit early from this
3487 // function if we encounter some other error.
3488 CoveredArgs.set(argIndex);
3489 }
3490
Ted Kremenek4407ea42010-07-20 20:04:47 +00003491 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003492 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003493 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3494 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003495 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003496 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003497 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003498 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3499 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003500
Jordan Rose92303592012-09-08 04:00:03 +00003501 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3502 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3503
Ted Kremenek02087932010-07-16 02:11:22 +00003504 // The remaining checks depend on the data arguments.
3505 if (HasVAListArg)
3506 return true;
3507
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003508 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003509 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003510
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003511 // Check that the argument type matches the format specifier.
3512 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003513 if (!Ex)
3514 return true;
3515
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003516 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3517 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003518 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003519 bool success = fixedFS.fixType(Ex->getType(),
3520 Ex->IgnoreImpCasts()->getType(),
3521 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003522
3523 if (success) {
3524 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003525 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003526 llvm::raw_svector_ostream os(buf);
3527 fixedFS.toString(os);
3528
3529 EmitFormatDiagnostic(
3530 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003531 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003532 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003533 Ex->getLocStart(),
3534 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003535 getSpecifierRange(startSpecifier, specifierLen),
3536 FixItHint::CreateReplacement(
3537 getSpecifierRange(startSpecifier, specifierLen),
3538 os.str()));
3539 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003540 EmitFormatDiagnostic(
3541 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003542 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003543 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003544 Ex->getLocStart(),
3545 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003546 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003547 }
3548 }
3549
Ted Kremenek02087932010-07-16 02:11:22 +00003550 return true;
3551}
3552
3553void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003554 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003555 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003556 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003557 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003558 bool inFunctionCall, VariadicCallType CallType,
3559 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003560
Ted Kremenekab278de2010-01-28 23:39:18 +00003561 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003562 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003563 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003564 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003565 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3566 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003567 return;
3568 }
Ted Kremenek02087932010-07-16 02:11:22 +00003569
Ted Kremenekab278de2010-01-28 23:39:18 +00003570 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003571 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003572 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003573 // Account for cases where the string literal is truncated in a declaration.
3574 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3575 assert(T && "String literal not of constant array type!");
3576 size_t TypeSize = T->getSize().getZExtValue();
3577 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003578 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003579
3580 // Emit a warning if the string literal is truncated and does not contain an
3581 // embedded null character.
3582 if (TypeSize <= StrRef.size() &&
3583 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3584 CheckFormatHandler::EmitFormatDiagnostic(
3585 *this, inFunctionCall, Args[format_idx],
3586 PDiag(diag::warn_printf_format_string_not_null_terminated),
3587 FExpr->getLocStart(),
3588 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3589 return;
3590 }
3591
Ted Kremenekab278de2010-01-28 23:39:18 +00003592 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003593 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003594 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003595 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003596 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3597 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003598 return;
3599 }
Ted Kremenek02087932010-07-16 02:11:22 +00003600
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003601 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003602 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003603 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003604 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003605 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003606
Hans Wennborg23926bd2011-12-15 10:25:47 +00003607 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003608 getLangOpts(),
3609 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003610 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003611 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003612 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003613 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003614 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003615
Hans Wennborg23926bd2011-12-15 10:25:47 +00003616 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003617 getLangOpts(),
3618 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003619 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003620 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003621}
3622
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003623//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3624
3625// Returns the related absolute value function that is larger, of 0 if one
3626// does not exist.
3627static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3628 switch (AbsFunction) {
3629 default:
3630 return 0;
3631
3632 case Builtin::BI__builtin_abs:
3633 return Builtin::BI__builtin_labs;
3634 case Builtin::BI__builtin_labs:
3635 return Builtin::BI__builtin_llabs;
3636 case Builtin::BI__builtin_llabs:
3637 return 0;
3638
3639 case Builtin::BI__builtin_fabsf:
3640 return Builtin::BI__builtin_fabs;
3641 case Builtin::BI__builtin_fabs:
3642 return Builtin::BI__builtin_fabsl;
3643 case Builtin::BI__builtin_fabsl:
3644 return 0;
3645
3646 case Builtin::BI__builtin_cabsf:
3647 return Builtin::BI__builtin_cabs;
3648 case Builtin::BI__builtin_cabs:
3649 return Builtin::BI__builtin_cabsl;
3650 case Builtin::BI__builtin_cabsl:
3651 return 0;
3652
3653 case Builtin::BIabs:
3654 return Builtin::BIlabs;
3655 case Builtin::BIlabs:
3656 return Builtin::BIllabs;
3657 case Builtin::BIllabs:
3658 return 0;
3659
3660 case Builtin::BIfabsf:
3661 return Builtin::BIfabs;
3662 case Builtin::BIfabs:
3663 return Builtin::BIfabsl;
3664 case Builtin::BIfabsl:
3665 return 0;
3666
3667 case Builtin::BIcabsf:
3668 return Builtin::BIcabs;
3669 case Builtin::BIcabs:
3670 return Builtin::BIcabsl;
3671 case Builtin::BIcabsl:
3672 return 0;
3673 }
3674}
3675
3676// Returns the argument type of the absolute value function.
3677static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3678 unsigned AbsType) {
3679 if (AbsType == 0)
3680 return QualType();
3681
3682 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3683 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3684 if (Error != ASTContext::GE_None)
3685 return QualType();
3686
3687 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3688 if (!FT)
3689 return QualType();
3690
3691 if (FT->getNumParams() != 1)
3692 return QualType();
3693
3694 return FT->getParamType(0);
3695}
3696
3697// Returns the best absolute value function, or zero, based on type and
3698// current absolute value function.
3699static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3700 unsigned AbsFunctionKind) {
3701 unsigned BestKind = 0;
3702 uint64_t ArgSize = Context.getTypeSize(ArgType);
3703 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3704 Kind = getLargerAbsoluteValueFunction(Kind)) {
3705 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3706 if (Context.getTypeSize(ParamType) >= ArgSize) {
3707 if (BestKind == 0)
3708 BestKind = Kind;
3709 else if (Context.hasSameType(ParamType, ArgType)) {
3710 BestKind = Kind;
3711 break;
3712 }
3713 }
3714 }
3715 return BestKind;
3716}
3717
3718enum AbsoluteValueKind {
3719 AVK_Integer,
3720 AVK_Floating,
3721 AVK_Complex
3722};
3723
3724static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3725 if (T->isIntegralOrEnumerationType())
3726 return AVK_Integer;
3727 if (T->isRealFloatingType())
3728 return AVK_Floating;
3729 if (T->isAnyComplexType())
3730 return AVK_Complex;
3731
3732 llvm_unreachable("Type not integer, floating, or complex");
3733}
3734
3735// Changes the absolute value function to a different type. Preserves whether
3736// the function is a builtin.
3737static unsigned changeAbsFunction(unsigned AbsKind,
3738 AbsoluteValueKind ValueKind) {
3739 switch (ValueKind) {
3740 case AVK_Integer:
3741 switch (AbsKind) {
3742 default:
3743 return 0;
3744 case Builtin::BI__builtin_fabsf:
3745 case Builtin::BI__builtin_fabs:
3746 case Builtin::BI__builtin_fabsl:
3747 case Builtin::BI__builtin_cabsf:
3748 case Builtin::BI__builtin_cabs:
3749 case Builtin::BI__builtin_cabsl:
3750 return Builtin::BI__builtin_abs;
3751 case Builtin::BIfabsf:
3752 case Builtin::BIfabs:
3753 case Builtin::BIfabsl:
3754 case Builtin::BIcabsf:
3755 case Builtin::BIcabs:
3756 case Builtin::BIcabsl:
3757 return Builtin::BIabs;
3758 }
3759 case AVK_Floating:
3760 switch (AbsKind) {
3761 default:
3762 return 0;
3763 case Builtin::BI__builtin_abs:
3764 case Builtin::BI__builtin_labs:
3765 case Builtin::BI__builtin_llabs:
3766 case Builtin::BI__builtin_cabsf:
3767 case Builtin::BI__builtin_cabs:
3768 case Builtin::BI__builtin_cabsl:
3769 return Builtin::BI__builtin_fabsf;
3770 case Builtin::BIabs:
3771 case Builtin::BIlabs:
3772 case Builtin::BIllabs:
3773 case Builtin::BIcabsf:
3774 case Builtin::BIcabs:
3775 case Builtin::BIcabsl:
3776 return Builtin::BIfabsf;
3777 }
3778 case AVK_Complex:
3779 switch (AbsKind) {
3780 default:
3781 return 0;
3782 case Builtin::BI__builtin_abs:
3783 case Builtin::BI__builtin_labs:
3784 case Builtin::BI__builtin_llabs:
3785 case Builtin::BI__builtin_fabsf:
3786 case Builtin::BI__builtin_fabs:
3787 case Builtin::BI__builtin_fabsl:
3788 return Builtin::BI__builtin_cabsf;
3789 case Builtin::BIabs:
3790 case Builtin::BIlabs:
3791 case Builtin::BIllabs:
3792 case Builtin::BIfabsf:
3793 case Builtin::BIfabs:
3794 case Builtin::BIfabsl:
3795 return Builtin::BIcabsf;
3796 }
3797 }
3798 llvm_unreachable("Unable to convert function");
3799}
3800
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003801static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003802 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3803 if (!FnInfo)
3804 return 0;
3805
3806 switch (FDecl->getBuiltinID()) {
3807 default:
3808 return 0;
3809 case Builtin::BI__builtin_abs:
3810 case Builtin::BI__builtin_fabs:
3811 case Builtin::BI__builtin_fabsf:
3812 case Builtin::BI__builtin_fabsl:
3813 case Builtin::BI__builtin_labs:
3814 case Builtin::BI__builtin_llabs:
3815 case Builtin::BI__builtin_cabs:
3816 case Builtin::BI__builtin_cabsf:
3817 case Builtin::BI__builtin_cabsl:
3818 case Builtin::BIabs:
3819 case Builtin::BIlabs:
3820 case Builtin::BIllabs:
3821 case Builtin::BIfabs:
3822 case Builtin::BIfabsf:
3823 case Builtin::BIfabsl:
3824 case Builtin::BIcabs:
3825 case Builtin::BIcabsf:
3826 case Builtin::BIcabsl:
3827 return FDecl->getBuiltinID();
3828 }
3829 llvm_unreachable("Unknown Builtin type");
3830}
3831
3832// If the replacement is valid, emit a note with replacement function.
3833// Additionally, suggest including the proper header if not already included.
3834static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3835 unsigned AbsKind) {
3836 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3837
3838 // Look up absolute value function in TU scope.
3839 DeclarationName DN(&S.Context.Idents.get(AbsName));
3840 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
Richard Trieufe771c02014-03-06 02:25:04 +00003841 R.suppressDiagnostics();
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003842 S.LookupName(R, S.TUScope);
3843
3844 // Skip notes if multiple results found in lookup.
3845 if (!R.empty() && !R.isSingleResult())
3846 return;
3847
3848 FunctionDecl *FD = 0;
3849 bool FoundFunction = R.isSingleResult();
3850 // When one result is found, see if it is the correct function.
3851 if (R.isSingleResult()) {
3852 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3853 if (!FD || FD->getBuiltinID() != AbsKind)
3854 return;
3855 }
3856
3857 // Look for local name conflict, prepend "::" as necessary.
3858 R.clear();
3859 S.LookupName(R, S.getCurScope());
3860
3861 if (!FoundFunction) {
3862 if (!R.empty()) {
3863 AbsName = "::" + AbsName;
3864 }
3865 } else { // FoundFunction
3866 if (R.isSingleResult()) {
3867 if (R.getFoundDecl() != FD) {
3868 AbsName = "::" + AbsName;
3869 }
3870 } else if (!R.empty()) {
3871 AbsName = "::" + AbsName;
3872 }
3873 }
3874
3875 S.Diag(Loc, diag::note_replace_abs_function)
3876 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3877
3878 if (!FoundFunction) {
3879 S.Diag(Loc, diag::note_please_include_header)
3880 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3881 << S.Context.BuiltinInfo.GetName(AbsKind);
3882 }
3883}
3884
3885// Warn when using the wrong abs() function.
3886void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3887 const FunctionDecl *FDecl,
3888 IdentifierInfo *FnInfo) {
3889 if (Call->getNumArgs() != 1)
3890 return;
3891
3892 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3893 if (AbsKind == 0)
3894 return;
3895
3896 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3897 QualType ParamType = Call->getArg(0)->getType();
3898
3899 // Unsigned types can not be negative. Suggest to drop the absolute value
3900 // function.
3901 if (ArgType->isUnsignedIntegerType()) {
3902 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3903 Diag(Call->getExprLoc(), diag::note_remove_abs)
3904 << FDecl
3905 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3906 return;
3907 }
3908
3909 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3910 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3911
3912 // The argument and parameter are the same kind. Check if they are the right
3913 // size.
3914 if (ArgValueKind == ParamValueKind) {
3915 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3916 return;
3917
3918 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3919 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3920 << FDecl << ArgType << ParamType;
3921
3922 if (NewAbsKind == 0)
3923 return;
3924
3925 emitReplacement(*this, Call->getExprLoc(),
3926 Call->getCallee()->getSourceRange(), NewAbsKind);
3927 return;
3928 }
3929
3930 // ArgValueKind != ParamValueKind
3931 // The wrong type of absolute value function was used. Attempt to find the
3932 // proper one.
3933 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3934 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3935 if (NewAbsKind == 0)
3936 return;
3937
3938 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3939 << FDecl << ParamValueKind << ArgValueKind;
3940
3941 emitReplacement(*this, Call->getExprLoc(),
3942 Call->getCallee()->getSourceRange(), NewAbsKind);
3943 return;
3944}
3945
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003946//===--- CHECK: Standard memory functions ---------------------------------===//
3947
Nico Weber0e6daef2013-12-26 23:38:39 +00003948/// \brief Takes the expression passed to the size_t parameter of functions
3949/// such as memcmp, strncat, etc and warns if it's a comparison.
3950///
3951/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3952static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3953 IdentifierInfo *FnName,
3954 SourceLocation FnLoc,
3955 SourceLocation RParenLoc) {
3956 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3957 if (!Size)
3958 return false;
3959
3960 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3961 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3962 return false;
3963
3964 Preprocessor &PP = S.getPreprocessor();
3965 SourceRange SizeRange = Size->getSourceRange();
3966 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3967 << SizeRange << FnName;
3968 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3969 << FnName
3970 << FixItHint::CreateInsertion(
3971 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3972 ")")
3973 << FixItHint::CreateRemoval(RParenLoc);
3974 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3975 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3976 << FixItHint::CreateInsertion(
3977 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3978
3979 return true;
3980}
3981
Douglas Gregora74926b2011-05-03 20:05:22 +00003982/// \brief Determine whether the given type is a dynamic class type (e.g.,
3983/// whether it has a vtable).
3984static bool isDynamicClassType(QualType T) {
3985 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3986 if (CXXRecordDecl *Definition = Record->getDefinition())
3987 if (Definition->isDynamicClass())
3988 return true;
3989
3990 return false;
3991}
3992
Chandler Carruth889ed862011-06-21 23:04:20 +00003993/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003994/// otherwise returns NULL.
3995static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003996 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003997 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3998 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3999 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004000
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004001 return 0;
4002}
4003
Chandler Carruth889ed862011-06-21 23:04:20 +00004004/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004005static QualType getSizeOfArgType(const Expr* E) {
4006 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4007 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4008 if (SizeOf->getKind() == clang::UETT_SizeOf)
4009 return SizeOf->getTypeOfArgument();
4010
4011 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004012}
4013
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004014/// \brief Check for dangerous or invalid arguments to memset().
4015///
Chandler Carruthac687262011-06-03 06:23:57 +00004016/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004017/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4018/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004019///
4020/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004021void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004022 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004023 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004024 assert(BId != 0);
4025
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004026 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004027 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004028 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004029 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004030 return;
4031
Anna Zaks22122702012-01-17 00:37:07 +00004032 unsigned LastArg = (BId == Builtin::BImemset ||
4033 BId == Builtin::BIstrndup ? 1 : 2);
4034 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004035 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004036
Nico Weber0e6daef2013-12-26 23:38:39 +00004037 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4038 Call->getLocStart(), Call->getRParenLoc()))
4039 return;
4040
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004041 // We have special checking when the length is a sizeof expression.
4042 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4043 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4044 llvm::FoldingSetNodeID SizeOfArgID;
4045
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004046 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4047 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004048 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004049
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004050 QualType DestTy = Dest->getType();
4051 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4052 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004053
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004054 // Never warn about void type pointers. This can be used to suppress
4055 // false positives.
4056 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004057 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004058
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004059 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4060 // actually comparing the expressions for equality. Because computing the
4061 // expression IDs can be expensive, we only do this if the diagnostic is
4062 // enabled.
4063 if (SizeOfArg &&
4064 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4065 SizeOfArg->getExprLoc())) {
4066 // We only compute IDs for expressions if the warning is enabled, and
4067 // cache the sizeof arg's ID.
4068 if (SizeOfArgID == llvm::FoldingSetNodeID())
4069 SizeOfArg->Profile(SizeOfArgID, Context, true);
4070 llvm::FoldingSetNodeID DestID;
4071 Dest->Profile(DestID, Context, true);
4072 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004073 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4074 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004075 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004076 StringRef ReadableName = FnName->getName();
4077
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004078 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004079 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004080 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004081 if (!PointeeTy->isIncompleteType() &&
4082 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004083 ActionIdx = 2; // If the pointee's size is sizeof(char),
4084 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004085
4086 // If the function is defined as a builtin macro, do not show macro
4087 // expansion.
4088 SourceLocation SL = SizeOfArg->getExprLoc();
4089 SourceRange DSR = Dest->getSourceRange();
4090 SourceRange SSR = SizeOfArg->getSourceRange();
4091 SourceManager &SM = PP.getSourceManager();
4092
4093 if (SM.isMacroArgExpansion(SL)) {
4094 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4095 SL = SM.getSpellingLoc(SL);
4096 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4097 SM.getSpellingLoc(DSR.getEnd()));
4098 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4099 SM.getSpellingLoc(SSR.getEnd()));
4100 }
4101
Anna Zaksd08d9152012-05-30 23:14:52 +00004102 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004103 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004104 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004105 << PointeeTy
4106 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004107 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004108 << SSR);
4109 DiagRuntimeBehavior(SL, SizeOfArg,
4110 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4111 << ActionIdx
4112 << SSR);
4113
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004114 break;
4115 }
4116 }
4117
4118 // Also check for cases where the sizeof argument is the exact same
4119 // type as the memory argument, and where it points to a user-defined
4120 // record type.
4121 if (SizeOfArgTy != QualType()) {
4122 if (PointeeTy->isRecordType() &&
4123 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4124 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4125 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4126 << FnName << SizeOfArgTy << ArgIdx
4127 << PointeeTy << Dest->getSourceRange()
4128 << LenExpr->getSourceRange());
4129 break;
4130 }
Nico Weberc5e73862011-06-14 16:14:58 +00004131 }
4132
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004133 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004134 if (isDynamicClassType(PointeeTy)) {
4135
4136 unsigned OperationType = 0;
4137 // "overwritten" if we're warning about the destination for any call
4138 // but memcmp; otherwise a verb appropriate to the call.
4139 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4140 if (BId == Builtin::BImemcpy)
4141 OperationType = 1;
4142 else if(BId == Builtin::BImemmove)
4143 OperationType = 2;
4144 else if (BId == Builtin::BImemcmp)
4145 OperationType = 3;
4146 }
4147
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004148 DiagRuntimeBehavior(
4149 Dest->getExprLoc(), Dest,
4150 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004151 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004152 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004153 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004154 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004155 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4156 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004157 DiagRuntimeBehavior(
4158 Dest->getExprLoc(), Dest,
4159 PDiag(diag::warn_arc_object_memaccess)
4160 << ArgIdx << FnName << PointeeTy
4161 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004162 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004163 continue;
John McCall31168b02011-06-15 23:02:42 +00004164
4165 DiagRuntimeBehavior(
4166 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004167 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004168 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4169 break;
4170 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004171 }
4172}
4173
Ted Kremenek6865f772011-08-18 20:55:45 +00004174// A little helper routine: ignore addition and subtraction of integer literals.
4175// This intentionally does not ignore all integer constant expressions because
4176// we don't want to remove sizeof().
4177static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4178 Ex = Ex->IgnoreParenCasts();
4179
4180 for (;;) {
4181 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4182 if (!BO || !BO->isAdditiveOp())
4183 break;
4184
4185 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4186 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4187
4188 if (isa<IntegerLiteral>(RHS))
4189 Ex = LHS;
4190 else if (isa<IntegerLiteral>(LHS))
4191 Ex = RHS;
4192 else
4193 break;
4194 }
4195
4196 return Ex;
4197}
4198
Anna Zaks13b08572012-08-08 21:42:23 +00004199static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4200 ASTContext &Context) {
4201 // Only handle constant-sized or VLAs, but not flexible members.
4202 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4203 // Only issue the FIXIT for arrays of size > 1.
4204 if (CAT->getSize().getSExtValue() <= 1)
4205 return false;
4206 } else if (!Ty->isVariableArrayType()) {
4207 return false;
4208 }
4209 return true;
4210}
4211
Ted Kremenek6865f772011-08-18 20:55:45 +00004212// Warn if the user has made the 'size' argument to strlcpy or strlcat
4213// be the size of the source, instead of the destination.
4214void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4215 IdentifierInfo *FnName) {
4216
4217 // Don't crash if the user has the wrong number of arguments
4218 if (Call->getNumArgs() != 3)
4219 return;
4220
4221 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4222 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4223 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004224
4225 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4226 Call->getLocStart(), Call->getRParenLoc()))
4227 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004228
4229 // Look for 'strlcpy(dst, x, sizeof(x))'
4230 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4231 CompareWithSrc = Ex;
4232 else {
4233 // Look for 'strlcpy(dst, x, strlen(x))'
4234 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004235 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4236 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004237 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4238 }
4239 }
4240
4241 if (!CompareWithSrc)
4242 return;
4243
4244 // Determine if the argument to sizeof/strlen is equal to the source
4245 // argument. In principle there's all kinds of things you could do
4246 // here, for instance creating an == expression and evaluating it with
4247 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4248 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4249 if (!SrcArgDRE)
4250 return;
4251
4252 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4253 if (!CompareWithSrcDRE ||
4254 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4255 return;
4256
4257 const Expr *OriginalSizeArg = Call->getArg(2);
4258 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4259 << OriginalSizeArg->getSourceRange() << FnName;
4260
4261 // Output a FIXIT hint if the destination is an array (rather than a
4262 // pointer to an array). This could be enhanced to handle some
4263 // pointers if we know the actual size, like if DstArg is 'array+2'
4264 // we could say 'sizeof(array)-2'.
4265 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004266 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004267 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004268
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004269 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004270 llvm::raw_svector_ostream OS(sizeString);
4271 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004272 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004273 OS << ")";
4274
4275 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4276 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4277 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004278}
4279
Anna Zaks314cd092012-02-01 19:08:57 +00004280/// Check if two expressions refer to the same declaration.
4281static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4282 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4283 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4284 return D1->getDecl() == D2->getDecl();
4285 return false;
4286}
4287
4288static const Expr *getStrlenExprArg(const Expr *E) {
4289 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4290 const FunctionDecl *FD = CE->getDirectCallee();
4291 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4292 return 0;
4293 return CE->getArg(0)->IgnoreParenCasts();
4294 }
4295 return 0;
4296}
4297
4298// Warn on anti-patterns as the 'size' argument to strncat.
4299// The correct size argument should look like following:
4300// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4301void Sema::CheckStrncatArguments(const CallExpr *CE,
4302 IdentifierInfo *FnName) {
4303 // Don't crash if the user has the wrong number of arguments.
4304 if (CE->getNumArgs() < 3)
4305 return;
4306 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4307 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4308 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4309
Nico Weber0e6daef2013-12-26 23:38:39 +00004310 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4311 CE->getRParenLoc()))
4312 return;
4313
Anna Zaks314cd092012-02-01 19:08:57 +00004314 // Identify common expressions, which are wrongly used as the size argument
4315 // to strncat and may lead to buffer overflows.
4316 unsigned PatternType = 0;
4317 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4318 // - sizeof(dst)
4319 if (referToTheSameDecl(SizeOfArg, DstArg))
4320 PatternType = 1;
4321 // - sizeof(src)
4322 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4323 PatternType = 2;
4324 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4325 if (BE->getOpcode() == BO_Sub) {
4326 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4327 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4328 // - sizeof(dst) - strlen(dst)
4329 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4330 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4331 PatternType = 1;
4332 // - sizeof(src) - (anything)
4333 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4334 PatternType = 2;
4335 }
4336 }
4337
4338 if (PatternType == 0)
4339 return;
4340
Anna Zaks5069aa32012-02-03 01:27:37 +00004341 // Generate the diagnostic.
4342 SourceLocation SL = LenArg->getLocStart();
4343 SourceRange SR = LenArg->getSourceRange();
4344 SourceManager &SM = PP.getSourceManager();
4345
4346 // If the function is defined as a builtin macro, do not show macro expansion.
4347 if (SM.isMacroArgExpansion(SL)) {
4348 SL = SM.getSpellingLoc(SL);
4349 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4350 SM.getSpellingLoc(SR.getEnd()));
4351 }
4352
Anna Zaks13b08572012-08-08 21:42:23 +00004353 // Check if the destination is an array (rather than a pointer to an array).
4354 QualType DstTy = DstArg->getType();
4355 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4356 Context);
4357 if (!isKnownSizeArray) {
4358 if (PatternType == 1)
4359 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4360 else
4361 Diag(SL, diag::warn_strncat_src_size) << SR;
4362 return;
4363 }
4364
Anna Zaks314cd092012-02-01 19:08:57 +00004365 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004366 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004367 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004368 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004369
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004370 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004371 llvm::raw_svector_ostream OS(sizeString);
4372 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004373 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004374 OS << ") - ";
4375 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004376 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004377 OS << ") - 1";
4378
Anna Zaks5069aa32012-02-03 01:27:37 +00004379 Diag(SL, diag::note_strncat_wrong_size)
4380 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004381}
4382
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004383//===--- CHECK: Return Address of Stack Variable --------------------------===//
4384
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004385static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4386 Decl *ParentDecl);
4387static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4388 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004389
4390/// CheckReturnStackAddr - Check if a return statement returns the address
4391/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004392static void
4393CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4394 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004395
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004396 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004397 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004398
4399 // Perform checking for returned stack addresses, local blocks,
4400 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004401 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004402 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004403 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004404 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004405 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004406 }
4407
4408 if (stackE == 0)
4409 return; // Nothing suspicious was found.
4410
4411 SourceLocation diagLoc;
4412 SourceRange diagRange;
4413 if (refVars.empty()) {
4414 diagLoc = stackE->getLocStart();
4415 diagRange = stackE->getSourceRange();
4416 } else {
4417 // We followed through a reference variable. 'stackE' contains the
4418 // problematic expression but we will warn at the return statement pointing
4419 // at the reference variable. We will later display the "trail" of
4420 // reference variables using notes.
4421 diagLoc = refVars[0]->getLocStart();
4422 diagRange = refVars[0]->getSourceRange();
4423 }
4424
4425 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004426 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004427 : diag::warn_ret_stack_addr)
4428 << DR->getDecl()->getDeclName() << diagRange;
4429 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004430 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004431 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004432 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004433 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004434 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4435 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004436 << diagRange;
4437 }
4438
4439 // Display the "trail" of reference variables that we followed until we
4440 // found the problematic expression using notes.
4441 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4442 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4443 // If this var binds to another reference var, show the range of the next
4444 // var, otherwise the var binds to the problematic expression, in which case
4445 // show the range of the expression.
4446 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4447 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004448 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4449 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004450 }
4451}
4452
4453/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4454/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004455/// to a location on the stack, a local block, an address of a label, or a
4456/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004457/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004458/// encounter a subexpression that (1) clearly does not lead to one of the
4459/// above problematic expressions (2) is something we cannot determine leads to
4460/// a problematic expression based on such local checking.
4461///
4462/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4463/// the expression that they point to. Such variables are added to the
4464/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004465///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004466/// EvalAddr processes expressions that are pointers that are used as
4467/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004468/// At the base case of the recursion is a check for the above problematic
4469/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004470///
4471/// This implementation handles:
4472///
4473/// * pointer-to-pointer casts
4474/// * implicit conversions from array references to pointers
4475/// * taking the address of fields
4476/// * arbitrary interplay between "&" and "*" operators
4477/// * pointer arithmetic from an address of a stack variable
4478/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004479static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4480 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004481 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004482 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004483
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004484 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004485 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004486 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004487 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004488 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004489
Peter Collingbourne91147592011-04-15 00:35:48 +00004490 E = E->IgnoreParens();
4491
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004492 // Our "symbolic interpreter" is just a dispatch off the currently
4493 // viewed AST node. We then recursively traverse the AST by calling
4494 // EvalAddr and EvalVal appropriately.
4495 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004496 case Stmt::DeclRefExprClass: {
4497 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4498
Richard Smith40f08eb2014-01-30 22:05:38 +00004499 // If we leave the immediate function, the lifetime isn't about to end.
4500 if (DR->refersToEnclosingLocal())
4501 return 0;
4502
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004503 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4504 // If this is a reference variable, follow through to the expression that
4505 // it points to.
4506 if (V->hasLocalStorage() &&
4507 V->getType()->isReferenceType() && V->hasInit()) {
4508 // Add the reference variable to the "trail".
4509 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004510 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004511 }
4512
4513 return NULL;
4514 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004515
Chris Lattner934edb22007-12-28 05:31:15 +00004516 case Stmt::UnaryOperatorClass: {
4517 // The only unary operator that make sense to handle here
4518 // is AddrOf. All others don't make sense as pointers.
4519 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004520
John McCalle3027922010-08-25 11:45:40 +00004521 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004522 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004523 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004524 return NULL;
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Chris Lattner934edb22007-12-28 05:31:15 +00004527 case Stmt::BinaryOperatorClass: {
4528 // Handle pointer arithmetic. All other binary operators are not valid
4529 // in this context.
4530 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004531 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004532
John McCalle3027922010-08-25 11:45:40 +00004533 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004534 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004535
Chris Lattner934edb22007-12-28 05:31:15 +00004536 Expr *Base = B->getLHS();
4537
4538 // Determine which argument is the real pointer base. It could be
4539 // the RHS argument instead of the LHS.
4540 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004541
Chris Lattner934edb22007-12-28 05:31:15 +00004542 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004543 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004544 }
Steve Naroff2752a172008-09-10 19:17:48 +00004545
Chris Lattner934edb22007-12-28 05:31:15 +00004546 // For conditional operators we need to see if either the LHS or RHS are
4547 // valid DeclRefExpr*s. If one of them is valid, we return it.
4548 case Stmt::ConditionalOperatorClass: {
4549 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004550
Chris Lattner934edb22007-12-28 05:31:15 +00004551 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004552 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4553 if (Expr *LHSExpr = C->getLHS()) {
4554 // In C++, we can have a throw-expression, which has 'void' type.
4555 if (!LHSExpr->getType()->isVoidType())
4556 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004557 return LHS;
4558 }
Chris Lattner934edb22007-12-28 05:31:15 +00004559
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004560 // In C++, we can have a throw-expression, which has 'void' type.
4561 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004562 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004563
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004564 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004565 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004566
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004567 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004568 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004569 return E; // local block.
4570 return NULL;
4571
4572 case Stmt::AddrLabelExprClass:
4573 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004574
John McCall28fc7092011-11-10 05:35:25 +00004575 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004576 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4577 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004578
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004579 // For casts, we need to handle conversions from arrays to
4580 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004581 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004582 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004583 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004584 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004585 case Stmt::CXXStaticCastExprClass:
4586 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004587 case Stmt::CXXConstCastExprClass:
4588 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004589 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4590 switch (cast<CastExpr>(E)->getCastKind()) {
4591 case CK_BitCast:
4592 case CK_LValueToRValue:
4593 case CK_NoOp:
4594 case CK_BaseToDerived:
4595 case CK_DerivedToBase:
4596 case CK_UncheckedDerivedToBase:
4597 case CK_Dynamic:
4598 case CK_CPointerToObjCPointerCast:
4599 case CK_BlockPointerToObjCPointerCast:
4600 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004601 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004602
4603 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004604 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004605
4606 default:
4607 return 0;
4608 }
Chris Lattner934edb22007-12-28 05:31:15 +00004609 }
Mike Stump11289f42009-09-09 15:08:12 +00004610
Douglas Gregorfe314812011-06-21 17:03:29 +00004611 case Stmt::MaterializeTemporaryExprClass:
4612 if (Expr *Result = EvalAddr(
4613 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004614 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004615 return Result;
4616
4617 return E;
4618
Chris Lattner934edb22007-12-28 05:31:15 +00004619 // Everything else: we simply don't reason about them.
4620 default:
4621 return NULL;
4622 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004623}
Mike Stump11289f42009-09-09 15:08:12 +00004624
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004625
4626/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4627/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004628static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4629 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004630do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004631 // We should only be called for evaluating non-pointer expressions, or
4632 // expressions with a pointer type that are not used as references but instead
4633 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004634
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004635 // Our "symbolic interpreter" is just a dispatch off the currently
4636 // viewed AST node. We then recursively traverse the AST by calling
4637 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004638
4639 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004640 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004641 case Stmt::ImplicitCastExprClass: {
4642 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004643 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004644 E = IE->getSubExpr();
4645 continue;
4646 }
4647 return NULL;
4648 }
4649
John McCall28fc7092011-11-10 05:35:25 +00004650 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004651 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004652
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004653 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004654 // When we hit a DeclRefExpr we are looking at code that refers to a
4655 // variable's name. If it's not a reference variable we check if it has
4656 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004657 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004658
Richard Smith40f08eb2014-01-30 22:05:38 +00004659 // If we leave the immediate function, the lifetime isn't about to end.
4660 if (DR->refersToEnclosingLocal())
4661 return 0;
4662
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004663 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4664 // Check if it refers to itself, e.g. "int& i = i;".
4665 if (V == ParentDecl)
4666 return DR;
4667
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004668 if (V->hasLocalStorage()) {
4669 if (!V->getType()->isReferenceType())
4670 return DR;
4671
4672 // Reference variable, follow through to the expression that
4673 // it points to.
4674 if (V->hasInit()) {
4675 // Add the reference variable to the "trail".
4676 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004677 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004678 }
4679 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004680 }
Mike Stump11289f42009-09-09 15:08:12 +00004681
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004682 return NULL;
4683 }
Mike Stump11289f42009-09-09 15:08:12 +00004684
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004685 case Stmt::UnaryOperatorClass: {
4686 // The only unary operator that make sense to handle here
4687 // is Deref. All others don't resolve to a "name." This includes
4688 // handling all sorts of rvalues passed to a unary operator.
4689 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004690
John McCalle3027922010-08-25 11:45:40 +00004691 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004692 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004693
4694 return NULL;
4695 }
Mike Stump11289f42009-09-09 15:08:12 +00004696
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004697 case Stmt::ArraySubscriptExprClass: {
4698 // Array subscripts are potential references to data on the stack. We
4699 // retrieve the DeclRefExpr* for the array variable if it indeed
4700 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004701 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004702 }
Mike Stump11289f42009-09-09 15:08:12 +00004703
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004704 case Stmt::ConditionalOperatorClass: {
4705 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004706 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004707 ConditionalOperator *C = cast<ConditionalOperator>(E);
4708
Anders Carlsson801c5c72007-11-30 19:04:31 +00004709 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004710 if (Expr *LHSExpr = C->getLHS()) {
4711 // In C++, we can have a throw-expression, which has 'void' type.
4712 if (!LHSExpr->getType()->isVoidType())
4713 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4714 return LHS;
4715 }
4716
4717 // In C++, we can have a throw-expression, which has 'void' type.
4718 if (C->getRHS()->getType()->isVoidType())
4719 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004720
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004721 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004722 }
Mike Stump11289f42009-09-09 15:08:12 +00004723
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004724 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004725 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004726 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004727
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004728 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004729 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004730 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004731
4732 // Check whether the member type is itself a reference, in which case
4733 // we're not going to refer to the member, but to what the member refers to.
4734 if (M->getMemberDecl()->getType()->isReferenceType())
4735 return NULL;
4736
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004737 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004738 }
Mike Stump11289f42009-09-09 15:08:12 +00004739
Douglas Gregorfe314812011-06-21 17:03:29 +00004740 case Stmt::MaterializeTemporaryExprClass:
4741 if (Expr *Result = EvalVal(
4742 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004743 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004744 return Result;
4745
4746 return E;
4747
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004748 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004749 // Check that we don't return or take the address of a reference to a
4750 // temporary. This is only useful in C++.
4751 if (!E->isTypeDependent() && E->isRValue())
4752 return E;
4753
4754 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004755 return NULL;
4756 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004757} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004758}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004759
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004760void
4761Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4762 SourceLocation ReturnLoc,
4763 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004764 const AttrVec *Attrs,
4765 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004766 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4767
4768 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004769 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4770 CheckNonNullExpr(*this, RetValExp))
4771 Diag(ReturnLoc, diag::warn_null_ret)
4772 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004773
4774 // C++11 [basic.stc.dynamic.allocation]p4:
4775 // If an allocation function declared with a non-throwing
4776 // exception-specification fails to allocate storage, it shall return
4777 // a null pointer. Any other allocation function that fails to allocate
4778 // storage shall indicate failure only by throwing an exception [...]
4779 if (FD) {
4780 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4781 if (Op == OO_New || Op == OO_Array_New) {
4782 const FunctionProtoType *Proto
4783 = FD->getType()->castAs<FunctionProtoType>();
4784 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4785 CheckNonNullExpr(*this, RetValExp))
4786 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4787 << FD << getLangOpts().CPlusPlus11;
4788 }
4789 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004790}
4791
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004792//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4793
4794/// Check for comparisons of floating point operands using != and ==.
4795/// Issue a warning if these are no self-comparisons, as they are not likely
4796/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004797void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004798 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4799 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004800
4801 // Special case: check for x == x (which is OK).
4802 // Do not emit warnings for such cases.
4803 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4804 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4805 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004806 return;
Mike Stump11289f42009-09-09 15:08:12 +00004807
4808
Ted Kremenekeda40e22007-11-29 00:59:04 +00004809 // Special case: check for comparisons against literals that can be exactly
4810 // represented by APFloat. In such cases, do not emit a warning. This
4811 // is a heuristic: often comparison against such literals are used to
4812 // detect if a value in a variable has not changed. This clearly can
4813 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004814 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4815 if (FLL->isExact())
4816 return;
4817 } else
4818 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4819 if (FLR->isExact())
4820 return;
Mike Stump11289f42009-09-09 15:08:12 +00004821
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004822 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004823 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004824 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004825 return;
Mike Stump11289f42009-09-09 15:08:12 +00004826
David Blaikie1f4ff152012-07-16 20:47:22 +00004827 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004828 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004829 return;
Mike Stump11289f42009-09-09 15:08:12 +00004830
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004831 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004832 Diag(Loc, diag::warn_floatingpoint_eq)
4833 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004834}
John McCallca01b222010-01-04 23:21:16 +00004835
John McCall70aa5392010-01-06 05:24:50 +00004836//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4837//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004838
John McCall70aa5392010-01-06 05:24:50 +00004839namespace {
John McCallca01b222010-01-04 23:21:16 +00004840
John McCall70aa5392010-01-06 05:24:50 +00004841/// Structure recording the 'active' range of an integer-valued
4842/// expression.
4843struct IntRange {
4844 /// The number of bits active in the int.
4845 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004846
John McCall70aa5392010-01-06 05:24:50 +00004847 /// True if the int is known not to have negative values.
4848 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004849
John McCall70aa5392010-01-06 05:24:50 +00004850 IntRange(unsigned Width, bool NonNegative)
4851 : Width(Width), NonNegative(NonNegative)
4852 {}
John McCallca01b222010-01-04 23:21:16 +00004853
John McCall817d4af2010-11-10 23:38:19 +00004854 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004855 static IntRange forBoolType() {
4856 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004857 }
4858
John McCall817d4af2010-11-10 23:38:19 +00004859 /// Returns the range of an opaque value of the given integral type.
4860 static IntRange forValueOfType(ASTContext &C, QualType T) {
4861 return forValueOfCanonicalType(C,
4862 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004863 }
4864
John McCall817d4af2010-11-10 23:38:19 +00004865 /// Returns the range of an opaque value of a canonical integral type.
4866 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004867 assert(T->isCanonicalUnqualified());
4868
4869 if (const VectorType *VT = dyn_cast<VectorType>(T))
4870 T = VT->getElementType().getTypePtr();
4871 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4872 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004873
David Majnemer6a426652013-06-07 22:07:20 +00004874 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004875 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004876 EnumDecl *Enum = ET->getDecl();
4877 if (!Enum->isCompleteDefinition())
4878 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004879
David Majnemer6a426652013-06-07 22:07:20 +00004880 unsigned NumPositive = Enum->getNumPositiveBits();
4881 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004882
David Majnemer6a426652013-06-07 22:07:20 +00004883 if (NumNegative == 0)
4884 return IntRange(NumPositive, true/*NonNegative*/);
4885 else
4886 return IntRange(std::max(NumPositive + 1, NumNegative),
4887 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004888 }
John McCall70aa5392010-01-06 05:24:50 +00004889
4890 const BuiltinType *BT = cast<BuiltinType>(T);
4891 assert(BT->isInteger());
4892
4893 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4894 }
4895
John McCall817d4af2010-11-10 23:38:19 +00004896 /// Returns the "target" range of a canonical integral type, i.e.
4897 /// the range of values expressible in the type.
4898 ///
4899 /// This matches forValueOfCanonicalType except that enums have the
4900 /// full range of their type, not the range of their enumerators.
4901 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4902 assert(T->isCanonicalUnqualified());
4903
4904 if (const VectorType *VT = dyn_cast<VectorType>(T))
4905 T = VT->getElementType().getTypePtr();
4906 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4907 T = CT->getElementType().getTypePtr();
4908 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004909 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004910
4911 const BuiltinType *BT = cast<BuiltinType>(T);
4912 assert(BT->isInteger());
4913
4914 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4915 }
4916
4917 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004918 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004919 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004920 L.NonNegative && R.NonNegative);
4921 }
4922
John McCall817d4af2010-11-10 23:38:19 +00004923 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004924 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004925 return IntRange(std::min(L.Width, R.Width),
4926 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004927 }
4928};
4929
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004930static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4931 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004932 if (value.isSigned() && value.isNegative())
4933 return IntRange(value.getMinSignedBits(), false);
4934
4935 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004936 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004937
4938 // isNonNegative() just checks the sign bit without considering
4939 // signedness.
4940 return IntRange(value.getActiveBits(), true);
4941}
4942
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004943static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4944 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004945 if (result.isInt())
4946 return GetValueRange(C, result.getInt(), MaxWidth);
4947
4948 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004949 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4950 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4951 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4952 R = IntRange::join(R, El);
4953 }
John McCall70aa5392010-01-06 05:24:50 +00004954 return R;
4955 }
4956
4957 if (result.isComplexInt()) {
4958 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4959 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4960 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004961 }
4962
4963 // This can happen with lossless casts to intptr_t of "based" lvalues.
4964 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004965 // FIXME: The only reason we need to pass the type in here is to get
4966 // the sign right on this one case. It would be nice if APValue
4967 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004968 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004969 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004970}
John McCall70aa5392010-01-06 05:24:50 +00004971
Eli Friedmane6d33952013-07-08 20:20:06 +00004972static QualType GetExprType(Expr *E) {
4973 QualType Ty = E->getType();
4974 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4975 Ty = AtomicRHS->getValueType();
4976 return Ty;
4977}
4978
John McCall70aa5392010-01-06 05:24:50 +00004979/// Pseudo-evaluate the given integer expression, estimating the
4980/// range of values it might take.
4981///
4982/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004983static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004984 E = E->IgnoreParens();
4985
4986 // Try a full evaluation first.
4987 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004988 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004989 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004990
4991 // I think we only want to look through implicit casts here; if the
4992 // user has an explicit widening cast, we should treat the value as
4993 // being of the new, wider type.
4994 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004995 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004996 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4997
Eli Friedmane6d33952013-07-08 20:20:06 +00004998 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004999
John McCalle3027922010-08-25 11:45:40 +00005000 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005001
John McCall70aa5392010-01-06 05:24:50 +00005002 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005003 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005004 return OutputTypeRange;
5005
5006 IntRange SubRange
5007 = GetExprRange(C, CE->getSubExpr(),
5008 std::min(MaxWidth, OutputTypeRange.Width));
5009
5010 // Bail out if the subexpr's range is as wide as the cast type.
5011 if (SubRange.Width >= OutputTypeRange.Width)
5012 return OutputTypeRange;
5013
5014 // Otherwise, we take the smaller width, and we're non-negative if
5015 // either the output type or the subexpr is.
5016 return IntRange(SubRange.Width,
5017 SubRange.NonNegative || OutputTypeRange.NonNegative);
5018 }
5019
5020 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5021 // If we can fold the condition, just take that operand.
5022 bool CondResult;
5023 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5024 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5025 : CO->getFalseExpr(),
5026 MaxWidth);
5027
5028 // Otherwise, conservatively merge.
5029 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5030 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5031 return IntRange::join(L, R);
5032 }
5033
5034 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5035 switch (BO->getOpcode()) {
5036
5037 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005038 case BO_LAnd:
5039 case BO_LOr:
5040 case BO_LT:
5041 case BO_GT:
5042 case BO_LE:
5043 case BO_GE:
5044 case BO_EQ:
5045 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005046 return IntRange::forBoolType();
5047
John McCallc3688382011-07-13 06:35:24 +00005048 // The type of the assignments is the type of the LHS, so the RHS
5049 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005050 case BO_MulAssign:
5051 case BO_DivAssign:
5052 case BO_RemAssign:
5053 case BO_AddAssign:
5054 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005055 case BO_XorAssign:
5056 case BO_OrAssign:
5057 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005058 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005059
John McCallc3688382011-07-13 06:35:24 +00005060 // Simple assignments just pass through the RHS, which will have
5061 // been coerced to the LHS type.
5062 case BO_Assign:
5063 // TODO: bitfields?
5064 return GetExprRange(C, BO->getRHS(), MaxWidth);
5065
John McCall70aa5392010-01-06 05:24:50 +00005066 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005067 case BO_PtrMemD:
5068 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005069 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005070
John McCall2ce81ad2010-01-06 22:07:33 +00005071 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005072 case BO_And:
5073 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005074 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5075 GetExprRange(C, BO->getRHS(), MaxWidth));
5076
John McCall70aa5392010-01-06 05:24:50 +00005077 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005078 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005079 // ...except that we want to treat '1 << (blah)' as logically
5080 // positive. It's an important idiom.
5081 if (IntegerLiteral *I
5082 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5083 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005084 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005085 return IntRange(R.Width, /*NonNegative*/ true);
5086 }
5087 }
5088 // fallthrough
5089
John McCalle3027922010-08-25 11:45:40 +00005090 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005091 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005092
John McCall2ce81ad2010-01-06 22:07:33 +00005093 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005094 case BO_Shr:
5095 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005096 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5097
5098 // If the shift amount is a positive constant, drop the width by
5099 // that much.
5100 llvm::APSInt shift;
5101 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5102 shift.isNonNegative()) {
5103 unsigned zext = shift.getZExtValue();
5104 if (zext >= L.Width)
5105 L.Width = (L.NonNegative ? 0 : 1);
5106 else
5107 L.Width -= zext;
5108 }
5109
5110 return L;
5111 }
5112
5113 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005114 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005115 return GetExprRange(C, BO->getRHS(), MaxWidth);
5116
John McCall2ce81ad2010-01-06 22:07:33 +00005117 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005118 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005119 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005120 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005121 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005122
John McCall51431812011-07-14 22:39:48 +00005123 // The width of a division result is mostly determined by the size
5124 // of the LHS.
5125 case BO_Div: {
5126 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005127 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005128 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5129
5130 // If the divisor is constant, use that.
5131 llvm::APSInt divisor;
5132 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5133 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5134 if (log2 >= L.Width)
5135 L.Width = (L.NonNegative ? 0 : 1);
5136 else
5137 L.Width = std::min(L.Width - log2, MaxWidth);
5138 return L;
5139 }
5140
5141 // Otherwise, just use the LHS's width.
5142 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5143 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5144 }
5145
5146 // The result of a remainder can't be larger than the result of
5147 // either side.
5148 case BO_Rem: {
5149 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005150 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005151 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5152 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5153
5154 IntRange meet = IntRange::meet(L, R);
5155 meet.Width = std::min(meet.Width, MaxWidth);
5156 return meet;
5157 }
5158
5159 // The default behavior is okay for these.
5160 case BO_Mul:
5161 case BO_Add:
5162 case BO_Xor:
5163 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005164 break;
5165 }
5166
John McCall51431812011-07-14 22:39:48 +00005167 // The default case is to treat the operation as if it were closed
5168 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005169 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5170 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5171 return IntRange::join(L, R);
5172 }
5173
5174 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5175 switch (UO->getOpcode()) {
5176 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005177 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005178 return IntRange::forBoolType();
5179
5180 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005181 case UO_Deref:
5182 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005183 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005184
5185 default:
5186 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5187 }
5188 }
5189
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005190 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5191 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5192
John McCalld25db7e2013-05-06 21:39:12 +00005193 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005194 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005195 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005196
Eli Friedmane6d33952013-07-08 20:20:06 +00005197 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005198}
John McCall263a48b2010-01-04 23:31:57 +00005199
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005200static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005201 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005202}
5203
John McCall263a48b2010-01-04 23:31:57 +00005204/// Checks whether the given value, which currently has the given
5205/// source semantics, has the same value when coerced through the
5206/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005207static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5208 const llvm::fltSemantics &Src,
5209 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005210 llvm::APFloat truncated = value;
5211
5212 bool ignored;
5213 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5214 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5215
5216 return truncated.bitwiseIsEqual(value);
5217}
5218
5219/// Checks whether the given value, which currently has the given
5220/// source semantics, has the same value when coerced through the
5221/// target semantics.
5222///
5223/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005224static bool IsSameFloatAfterCast(const APValue &value,
5225 const llvm::fltSemantics &Src,
5226 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005227 if (value.isFloat())
5228 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5229
5230 if (value.isVector()) {
5231 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5232 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5233 return false;
5234 return true;
5235 }
5236
5237 assert(value.isComplexFloat());
5238 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5239 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5240}
5241
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005242static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005243
Ted Kremenek6274be42010-09-23 21:43:44 +00005244static bool IsZero(Sema &S, Expr *E) {
5245 // Suppress cases where we are comparing against an enum constant.
5246 if (const DeclRefExpr *DR =
5247 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5248 if (isa<EnumConstantDecl>(DR->getDecl()))
5249 return false;
5250
5251 // Suppress cases where the '0' value is expanded from a macro.
5252 if (E->getLocStart().isMacroID())
5253 return false;
5254
John McCallcc7e5bf2010-05-06 08:58:33 +00005255 llvm::APSInt Value;
5256 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5257}
5258
John McCall2551c1b2010-10-06 00:25:24 +00005259static bool HasEnumType(Expr *E) {
5260 // Strip off implicit integral promotions.
5261 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005262 if (ICE->getCastKind() != CK_IntegralCast &&
5263 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005264 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005265 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005266 }
5267
5268 return E->getType()->isEnumeralType();
5269}
5270
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005271static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005272 // Disable warning in template instantiations.
5273 if (!S.ActiveTemplateInstantiations.empty())
5274 return;
5275
John McCalle3027922010-08-25 11:45:40 +00005276 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005277 if (E->isValueDependent())
5278 return;
5279
John McCalle3027922010-08-25 11:45:40 +00005280 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005281 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005282 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005283 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005284 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005285 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005286 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005287 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005288 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005289 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005290 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005291 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005292 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005293 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005294 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005295 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5296 }
5297}
5298
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005299static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005300 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005301 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005302 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005303 // Disable warning in template instantiations.
5304 if (!S.ActiveTemplateInstantiations.empty())
5305 return;
5306
Richard Trieu560910c2012-11-14 22:50:24 +00005307 // 0 values are handled later by CheckTrivialUnsignedComparison().
5308 if (Value == 0)
5309 return;
5310
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005311 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005312 QualType OtherT = Other->getType();
5313 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005314 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005315 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005316 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005317 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005318 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00005319
5320 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00005321 bool CommonSigned = CommonT->isSignedIntegerType();
5322
5323 bool EqualityOnly = false;
5324
5325 // TODO: Investigate using GetExprRange() to get tighter bounds on
5326 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005327 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00005328 unsigned OtherWidth = OtherRange.Width;
5329
5330 if (CommonSigned) {
5331 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00005332 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005333 // Check that the constant is representable in type OtherT.
5334 if (ConstantSigned) {
5335 if (OtherWidth >= Value.getMinSignedBits())
5336 return;
5337 } else { // !ConstantSigned
5338 if (OtherWidth >= Value.getActiveBits() + 1)
5339 return;
5340 }
5341 } else { // !OtherSigned
5342 // Check that the constant is representable in type OtherT.
5343 // Negative values are out of range.
5344 if (ConstantSigned) {
5345 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5346 return;
5347 } else { // !ConstantSigned
5348 if (OtherWidth >= Value.getActiveBits())
5349 return;
5350 }
5351 }
5352 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00005353 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005354 if (OtherWidth >= Value.getActiveBits())
5355 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00005356 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00005357 // Check to see if the constant is representable in OtherT.
5358 if (OtherWidth > Value.getActiveBits())
5359 return;
5360 // Check to see if the constant is equivalent to a negative value
5361 // cast to CommonT.
5362 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005363 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005364 return;
5365 // The constant value rests between values that OtherT can represent after
5366 // conversion. Relational comparison still works, but equality
5367 // comparisons will be tautological.
5368 EqualityOnly = true;
5369 } else { // OtherSigned && ConstantSigned
5370 assert(0 && "Two signed types converted to unsigned types.");
5371 }
5372 }
5373
5374 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5375
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005376 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005377 if (op == BO_EQ || op == BO_NE) {
5378 IsTrue = op == BO_NE;
5379 } else if (EqualityOnly) {
5380 return;
5381 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005382 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005383 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005384 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005385 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005386 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005387 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005388 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005389 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005390 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005391 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005392
5393 // If this is a comparison to an enum constant, include that
5394 // constant in the diagnostic.
5395 const EnumConstantDecl *ED = 0;
5396 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5397 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5398
5399 SmallString<64> PrettySourceValue;
5400 llvm::raw_svector_ostream OS(PrettySourceValue);
5401 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005402 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005403 else
5404 OS << Value;
5405
Richard Trieuc38786b2014-01-10 04:38:09 +00005406 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5407 S.PDiag(diag::warn_out_of_range_compare)
5408 << OS.str() << OtherT << IsTrue
5409 << E->getLHS()->getSourceRange()
5410 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005411}
5412
John McCallcc7e5bf2010-05-06 08:58:33 +00005413/// Analyze the operands of the given comparison. Implements the
5414/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005415static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005416 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5417 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005418}
John McCall263a48b2010-01-04 23:31:57 +00005419
John McCallca01b222010-01-04 23:21:16 +00005420/// \brief Implements -Wsign-compare.
5421///
Richard Trieu82402a02011-09-15 21:56:47 +00005422/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005423static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005424 // The type the comparison is being performed in.
5425 QualType T = E->getLHS()->getType();
5426 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5427 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005428 if (E->isValueDependent())
5429 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005430
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005431 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5432 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005433
5434 bool IsComparisonConstant = false;
5435
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005436 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005437 // of 'true' or 'false'.
5438 if (T->isIntegralType(S.Context)) {
5439 llvm::APSInt RHSValue;
5440 bool IsRHSIntegralLiteral =
5441 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5442 llvm::APSInt LHSValue;
5443 bool IsLHSIntegralLiteral =
5444 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5445 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5446 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5447 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5448 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5449 else
5450 IsComparisonConstant =
5451 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005452 } else if (!T->hasUnsignedIntegerRepresentation())
5453 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005454
John McCallcc7e5bf2010-05-06 08:58:33 +00005455 // We don't do anything special if this isn't an unsigned integral
5456 // comparison: we're only interested in integral comparisons, and
5457 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005458 //
5459 // We also don't care about value-dependent expressions or expressions
5460 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005461 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005462 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005463
John McCallcc7e5bf2010-05-06 08:58:33 +00005464 // Check to see if one of the (unmodified) operands is of different
5465 // signedness.
5466 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005467 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5468 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005469 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005470 signedOperand = LHS;
5471 unsignedOperand = RHS;
5472 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5473 signedOperand = RHS;
5474 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005475 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005476 CheckTrivialUnsignedComparison(S, E);
5477 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005478 }
5479
John McCallcc7e5bf2010-05-06 08:58:33 +00005480 // Otherwise, calculate the effective range of the signed operand.
5481 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005482
John McCallcc7e5bf2010-05-06 08:58:33 +00005483 // Go ahead and analyze implicit conversions in the operands. Note
5484 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005485 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5486 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005487
John McCallcc7e5bf2010-05-06 08:58:33 +00005488 // If the signed range is non-negative, -Wsign-compare won't fire,
5489 // but we should still check for comparisons which are always true
5490 // or false.
5491 if (signedRange.NonNegative)
5492 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005493
5494 // For (in)equality comparisons, if the unsigned operand is a
5495 // constant which cannot collide with a overflowed signed operand,
5496 // then reinterpreting the signed operand as unsigned will not
5497 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005498 if (E->isEqualityOp()) {
5499 unsigned comparisonWidth = S.Context.getIntWidth(T);
5500 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005501
John McCallcc7e5bf2010-05-06 08:58:33 +00005502 // We should never be unable to prove that the unsigned operand is
5503 // non-negative.
5504 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5505
5506 if (unsignedRange.Width < comparisonWidth)
5507 return;
5508 }
5509
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005510 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5511 S.PDiag(diag::warn_mixed_sign_comparison)
5512 << LHS->getType() << RHS->getType()
5513 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005514}
5515
John McCall1f425642010-11-11 03:21:53 +00005516/// Analyzes an attempt to assign the given value to a bitfield.
5517///
5518/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005519static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5520 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005521 assert(Bitfield->isBitField());
5522 if (Bitfield->isInvalidDecl())
5523 return false;
5524
John McCalldeebbcf2010-11-11 05:33:51 +00005525 // White-list bool bitfields.
5526 if (Bitfield->getType()->isBooleanType())
5527 return false;
5528
Douglas Gregor789adec2011-02-04 13:09:01 +00005529 // Ignore value- or type-dependent expressions.
5530 if (Bitfield->getBitWidth()->isValueDependent() ||
5531 Bitfield->getBitWidth()->isTypeDependent() ||
5532 Init->isValueDependent() ||
5533 Init->isTypeDependent())
5534 return false;
5535
John McCall1f425642010-11-11 03:21:53 +00005536 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5537
Richard Smith5fab0c92011-12-28 19:48:30 +00005538 llvm::APSInt Value;
5539 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005540 return false;
5541
John McCall1f425642010-11-11 03:21:53 +00005542 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005543 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005544
5545 if (OriginalWidth <= FieldWidth)
5546 return false;
5547
Eli Friedmanc267a322012-01-26 23:11:39 +00005548 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005549 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005550 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005551
Eli Friedmanc267a322012-01-26 23:11:39 +00005552 // Check whether the stored value is equal to the original value.
5553 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005554 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005555 return false;
5556
Eli Friedmanc267a322012-01-26 23:11:39 +00005557 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005558 // therefore don't strictly fit into a signed bitfield of width 1.
5559 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005560 return false;
5561
John McCall1f425642010-11-11 03:21:53 +00005562 std::string PrettyValue = Value.toString(10);
5563 std::string PrettyTrunc = TruncatedValue.toString(10);
5564
5565 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5566 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5567 << Init->getSourceRange();
5568
5569 return true;
5570}
5571
John McCalld2a53122010-11-09 23:24:47 +00005572/// Analyze the given simple or compound assignment for warning-worthy
5573/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005574static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005575 // Just recurse on the LHS.
5576 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5577
5578 // We want to recurse on the RHS as normal unless we're assigning to
5579 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005580 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005581 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005582 E->getOperatorLoc())) {
5583 // Recurse, ignoring any implicit conversions on the RHS.
5584 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5585 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005586 }
5587 }
5588
5589 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5590}
5591
John McCall263a48b2010-01-04 23:31:57 +00005592/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005593static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005594 SourceLocation CContext, unsigned diag,
5595 bool pruneControlFlow = false) {
5596 if (pruneControlFlow) {
5597 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5598 S.PDiag(diag)
5599 << SourceType << T << E->getSourceRange()
5600 << SourceRange(CContext));
5601 return;
5602 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005603 S.Diag(E->getExprLoc(), diag)
5604 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5605}
5606
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005607/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005608static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005609 SourceLocation CContext, unsigned diag,
5610 bool pruneControlFlow = false) {
5611 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005612}
5613
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005614/// Diagnose an implicit cast from a literal expression. Does not warn when the
5615/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005616void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5617 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005618 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005619 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005620 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005621 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5622 T->hasUnsignedIntegerRepresentation());
5623 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005624 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005625 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005626 return;
5627
Eli Friedman07185912013-08-29 23:44:43 +00005628 // FIXME: Force the precision of the source value down so we don't print
5629 // digits which are usually useless (we don't really care here if we
5630 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5631 // would automatically print the shortest representation, but it's a bit
5632 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005633 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005634 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5635 precision = (precision * 59 + 195) / 196;
5636 Value.toString(PrettySourceValue, precision);
5637
David Blaikie9b88cc02012-05-15 17:18:27 +00005638 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005639 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5640 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5641 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005642 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005643
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005644 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005645 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5646 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005647}
5648
John McCall18a2c2c2010-11-09 22:22:12 +00005649std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5650 if (!Range.Width) return "0";
5651
5652 llvm::APSInt ValueInRange = Value;
5653 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005654 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005655 return ValueInRange.toString(10);
5656}
5657
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005658static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5659 if (!isa<ImplicitCastExpr>(Ex))
5660 return false;
5661
5662 Expr *InnerE = Ex->IgnoreParenImpCasts();
5663 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5664 const Type *Source =
5665 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5666 if (Target->isDependentType())
5667 return false;
5668
5669 const BuiltinType *FloatCandidateBT =
5670 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5671 const Type *BoolCandidateType = ToBool ? Target : Source;
5672
5673 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5674 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5675}
5676
5677void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5678 SourceLocation CC) {
5679 unsigned NumArgs = TheCall->getNumArgs();
5680 for (unsigned i = 0; i < NumArgs; ++i) {
5681 Expr *CurrA = TheCall->getArg(i);
5682 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5683 continue;
5684
5685 bool IsSwapped = ((i > 0) &&
5686 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5687 IsSwapped |= ((i < (NumArgs - 1)) &&
5688 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5689 if (IsSwapped) {
5690 // Warn on this floating-point to bool conversion.
5691 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5692 CurrA->getType(), CC,
5693 diag::warn_impcast_floating_point_to_bool);
5694 }
5695 }
5696}
5697
John McCallcc7e5bf2010-05-06 08:58:33 +00005698void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005699 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005700 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005701
John McCallcc7e5bf2010-05-06 08:58:33 +00005702 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5703 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5704 if (Source == Target) return;
5705 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005706
Chandler Carruthc22845a2011-07-26 05:40:03 +00005707 // If the conversion context location is invalid don't complain. We also
5708 // don't want to emit a warning if the issue occurs from the expansion of
5709 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5710 // delay this check as long as possible. Once we detect we are in that
5711 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005712 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005713 return;
5714
Richard Trieu021baa32011-09-23 20:10:00 +00005715 // Diagnose implicit casts to bool.
5716 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5717 if (isa<StringLiteral>(E))
5718 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005719 // and expressions, for instance, assert(0 && "error here"), are
5720 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005721 return DiagnoseImpCast(S, E, T, CC,
5722 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005723 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5724 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5725 // This covers the literal expressions that evaluate to Objective-C
5726 // objects.
5727 return DiagnoseImpCast(S, E, T, CC,
5728 diag::warn_impcast_objective_c_literal_to_bool);
5729 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005730 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5731 // Warn on pointer to bool conversion that is always true.
5732 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5733 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005734 }
Richard Trieu021baa32011-09-23 20:10:00 +00005735 }
John McCall263a48b2010-01-04 23:31:57 +00005736
5737 // Strip vector types.
5738 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005739 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005740 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005741 return;
John McCallacf0ee52010-10-08 02:01:28 +00005742 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005743 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005744
5745 // If the vector cast is cast between two vectors of the same size, it is
5746 // a bitcast, not a conversion.
5747 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5748 return;
John McCall263a48b2010-01-04 23:31:57 +00005749
5750 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5751 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5752 }
5753
5754 // Strip complex types.
5755 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005756 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005757 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005758 return;
5759
John McCallacf0ee52010-10-08 02:01:28 +00005760 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005761 }
John McCall263a48b2010-01-04 23:31:57 +00005762
5763 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5764 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5765 }
5766
5767 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5768 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5769
5770 // If the source is floating point...
5771 if (SourceBT && SourceBT->isFloatingPoint()) {
5772 // ...and the target is floating point...
5773 if (TargetBT && TargetBT->isFloatingPoint()) {
5774 // ...then warn if we're dropping FP rank.
5775
5776 // Builtin FP kinds are ordered by increasing FP rank.
5777 if (SourceBT->getKind() > TargetBT->getKind()) {
5778 // Don't warn about float constants that are precisely
5779 // representable in the target type.
5780 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005781 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005782 // Value might be a float, a float vector, or a float complex.
5783 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005784 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5785 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005786 return;
5787 }
5788
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005789 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005790 return;
5791
John McCallacf0ee52010-10-08 02:01:28 +00005792 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005793 }
5794 return;
5795 }
5796
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005797 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005798 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005799 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005800 return;
5801
Chandler Carruth22c7a792011-02-17 11:05:49 +00005802 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005803 // We also want to warn on, e.g., "int i = -1.234"
5804 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5805 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5806 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5807
Chandler Carruth016ef402011-04-10 08:36:24 +00005808 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5809 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005810 } else {
5811 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5812 }
5813 }
John McCall263a48b2010-01-04 23:31:57 +00005814
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005815 // If the target is bool, warn if expr is a function or method call.
5816 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5817 isa<CallExpr>(E)) {
5818 // Check last argument of function call to see if it is an
5819 // implicit cast from a type matching the type the result
5820 // is being cast to.
5821 CallExpr *CEx = cast<CallExpr>(E);
5822 unsigned NumArgs = CEx->getNumArgs();
5823 if (NumArgs > 0) {
5824 Expr *LastA = CEx->getArg(NumArgs - 1);
5825 Expr *InnerE = LastA->IgnoreParenImpCasts();
5826 const Type *InnerType =
5827 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5828 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5829 // Warn on this floating-point to bool conversion
5830 DiagnoseImpCast(S, E, T, CC,
5831 diag::warn_impcast_floating_point_to_bool);
5832 }
5833 }
5834 }
John McCall263a48b2010-01-04 23:31:57 +00005835 return;
5836 }
5837
Richard Trieubeaf3452011-05-29 19:59:02 +00005838 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005839 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005840 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005841 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005842 SourceLocation Loc = E->getSourceRange().getBegin();
5843 if (Loc.isMacroID())
5844 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005845 if (!Loc.isMacroID() || CC.isMacroID())
5846 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5847 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005848 << FixItHint::CreateReplacement(Loc,
5849 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005850 }
5851
David Blaikie9366d2b2012-06-19 21:19:06 +00005852 if (!Source->isIntegerType() || !Target->isIntegerType())
5853 return;
5854
David Blaikie7555b6a2012-05-15 16:56:36 +00005855 // TODO: remove this early return once the false positives for constant->bool
5856 // in templates, macros, etc, are reduced or removed.
5857 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5858 return;
5859
John McCallcc7e5bf2010-05-06 08:58:33 +00005860 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005861 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005862
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005863 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005864 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005865 // TODO: this should happen for bitfield stores, too.
5866 llvm::APSInt Value(32);
5867 if (E->isIntegerConstantExpr(Value, S.Context)) {
5868 if (S.SourceMgr.isInSystemMacro(CC))
5869 return;
5870
John McCall18a2c2c2010-11-09 22:22:12 +00005871 std::string PrettySourceValue = Value.toString(10);
5872 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005873
Ted Kremenek33ba9952011-10-22 02:37:33 +00005874 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5875 S.PDiag(diag::warn_impcast_integer_precision_constant)
5876 << PrettySourceValue << PrettyTargetValue
5877 << E->getType() << T << E->getSourceRange()
5878 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005879 return;
5880 }
5881
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005882 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5883 if (S.SourceMgr.isInSystemMacro(CC))
5884 return;
5885
David Blaikie9455da02012-04-12 22:40:54 +00005886 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005887 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5888 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005889 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005890 }
5891
5892 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5893 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5894 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005895
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005896 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005897 return;
5898
John McCallcc7e5bf2010-05-06 08:58:33 +00005899 unsigned DiagID = diag::warn_impcast_integer_sign;
5900
5901 // Traditionally, gcc has warned about this under -Wsign-compare.
5902 // We also want to warn about it in -Wconversion.
5903 // So if -Wconversion is off, use a completely identical diagnostic
5904 // in the sign-compare group.
5905 // The conditional-checking code will
5906 if (ICContext) {
5907 DiagID = diag::warn_impcast_integer_sign_conditional;
5908 *ICContext = true;
5909 }
5910
John McCallacf0ee52010-10-08 02:01:28 +00005911 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005912 }
5913
Douglas Gregora78f1932011-02-22 02:45:07 +00005914 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005915 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5916 // type, to give us better diagnostics.
5917 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005918 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005919 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5920 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5921 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5922 SourceType = S.Context.getTypeDeclType(Enum);
5923 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5924 }
5925 }
5926
Douglas Gregora78f1932011-02-22 02:45:07 +00005927 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5928 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005929 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5930 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005931 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005932 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005933 return;
5934
Douglas Gregor364f7db2011-03-12 00:14:31 +00005935 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005936 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005937 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005938
John McCall263a48b2010-01-04 23:31:57 +00005939 return;
5940}
5941
David Blaikie18e9ac72012-05-15 21:57:38 +00005942void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5943 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005944
5945void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005946 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005947 E = E->IgnoreParenImpCasts();
5948
5949 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005950 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005951
John McCallacf0ee52010-10-08 02:01:28 +00005952 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005953 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005954 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005955 return;
5956}
5957
David Blaikie18e9ac72012-05-15 21:57:38 +00005958void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5959 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005960 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005961
5962 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005963 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5964 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005965
5966 // If -Wconversion would have warned about either of the candidates
5967 // for a signedness conversion to the context type...
5968 if (!Suspicious) return;
5969
5970 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005971 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5972 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005973 return;
5974
John McCallcc7e5bf2010-05-06 08:58:33 +00005975 // ...then check whether it would have warned about either of the
5976 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005977 if (E->getType() == T) return;
5978
5979 Suspicious = false;
5980 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5981 E->getType(), CC, &Suspicious);
5982 if (!Suspicious)
5983 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005984 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005985}
5986
5987/// AnalyzeImplicitConversions - Find and report any interesting
5988/// implicit conversions in the given expression. There are a couple
5989/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005990void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005991 QualType T = OrigE->getType();
5992 Expr *E = OrigE->IgnoreParenImpCasts();
5993
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005994 if (E->isTypeDependent() || E->isValueDependent())
5995 return;
5996
John McCallcc7e5bf2010-05-06 08:58:33 +00005997 // For conditional operators, we analyze the arguments as if they
5998 // were being fed directly into the output.
5999 if (isa<ConditionalOperator>(E)) {
6000 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006001 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006002 return;
6003 }
6004
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006005 // Check implicit argument conversions for function calls.
6006 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6007 CheckImplicitArgumentConversions(S, Call, CC);
6008
John McCallcc7e5bf2010-05-06 08:58:33 +00006009 // Go ahead and check any implicit conversions we might have skipped.
6010 // The non-canonical typecheck is just an optimization;
6011 // CheckImplicitConversion will filter out dead implicit conversions.
6012 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006013 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006014
6015 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006016
6017 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006018 if (POE->getResultExpr())
6019 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006020 }
6021
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006022 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6023 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6024
John McCallcc7e5bf2010-05-06 08:58:33 +00006025 // Skip past explicit casts.
6026 if (isa<ExplicitCastExpr>(E)) {
6027 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006028 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006029 }
6030
John McCalld2a53122010-11-09 23:24:47 +00006031 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6032 // Do a somewhat different check with comparison operators.
6033 if (BO->isComparisonOp())
6034 return AnalyzeComparison(S, BO);
6035
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006036 // And with simple assignments.
6037 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006038 return AnalyzeAssignment(S, BO);
6039 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006040
6041 // These break the otherwise-useful invariant below. Fortunately,
6042 // we don't really need to recurse into them, because any internal
6043 // expressions should have been analyzed already when they were
6044 // built into statements.
6045 if (isa<StmtExpr>(E)) return;
6046
6047 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006048 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006049
6050 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006051 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006052 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006053 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006054 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006055 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006056 if (!ChildExpr)
6057 continue;
6058
Richard Trieu955231d2014-01-25 01:10:35 +00006059 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006060 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006061 // Ignore checking string literals that are in logical and operators.
6062 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006063 continue;
6064 AnalyzeImplicitConversions(S, ChildExpr, CC);
6065 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006066}
6067
6068} // end anonymous namespace
6069
Richard Trieu3bb8b562014-02-26 02:36:06 +00006070enum {
6071 AddressOf,
6072 FunctionPointer,
6073 ArrayPointer
6074};
6075
6076/// \brief Diagnose pointers that are always non-null.
6077/// \param E the expression containing the pointer
6078/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6079/// compared to a null pointer
6080/// \param IsEqual True when the comparison is equal to a null pointer
6081/// \param Range Extra SourceRange to highlight in the diagnostic
6082void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6083 Expr::NullPointerConstantKind NullKind,
6084 bool IsEqual, SourceRange Range) {
6085
6086 // Don't warn inside macros.
6087 if (E->getExprLoc().isMacroID())
6088 return;
6089 E = E->IgnoreImpCasts();
6090
6091 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6092
6093 bool IsAddressOf = false;
6094
6095 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6096 if (UO->getOpcode() != UO_AddrOf)
6097 return;
6098 IsAddressOf = true;
6099 E = UO->getSubExpr();
6100 }
6101
6102 // Expect to find a single Decl. Skip anything more complicated.
6103 ValueDecl *D = 0;
6104 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6105 D = R->getDecl();
6106 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6107 D = M->getMemberDecl();
6108 }
6109
6110 // Weak Decls can be null.
6111 if (!D || D->isWeak())
6112 return;
6113
6114 QualType T = D->getType();
6115 const bool IsArray = T->isArrayType();
6116 const bool IsFunction = T->isFunctionType();
6117
6118 if (IsAddressOf) {
6119 // Address of function is used to silence the function warning.
6120 if (IsFunction)
6121 return;
6122 // Address of reference can be null.
6123 if (T->isReferenceType())
6124 return;
6125 }
6126
6127 // Found nothing.
6128 if (!IsAddressOf && !IsFunction && !IsArray)
6129 return;
6130
6131 // Pretty print the expression for the diagnostic.
6132 std::string Str;
6133 llvm::raw_string_ostream S(Str);
6134 E->printPretty(S, 0, getPrintingPolicy());
6135
6136 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6137 : diag::warn_impcast_pointer_to_bool;
6138 unsigned DiagType;
6139 if (IsAddressOf)
6140 DiagType = AddressOf;
6141 else if (IsFunction)
6142 DiagType = FunctionPointer;
6143 else if (IsArray)
6144 DiagType = ArrayPointer;
6145 else
6146 llvm_unreachable("Could not determine diagnostic.");
6147 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6148 << Range << IsEqual;
6149
6150 if (!IsFunction)
6151 return;
6152
6153 // Suggest '&' to silence the function warning.
6154 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6155 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6156
6157 // Check to see if '()' fixit should be emitted.
6158 QualType ReturnType;
6159 UnresolvedSet<4> NonTemplateOverloads;
6160 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6161 if (ReturnType.isNull())
6162 return;
6163
6164 if (IsCompare) {
6165 // There are two cases here. If there is null constant, the only suggest
6166 // for a pointer return type. If the null is 0, then suggest if the return
6167 // type is a pointer or an integer type.
6168 if (!ReturnType->isPointerType()) {
6169 if (NullKind == Expr::NPCK_ZeroExpression ||
6170 NullKind == Expr::NPCK_ZeroLiteral) {
6171 if (!ReturnType->isIntegerType())
6172 return;
6173 } else {
6174 return;
6175 }
6176 }
6177 } else { // !IsCompare
6178 // For function to bool, only suggest if the function pointer has bool
6179 // return type.
6180 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6181 return;
6182 }
6183 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6184 << FixItHint::CreateInsertion(
6185 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6186}
6187
6188
John McCallcc7e5bf2010-05-06 08:58:33 +00006189/// Diagnoses "dangerous" implicit conversions within the given
6190/// expression (which is a full expression). Implements -Wconversion
6191/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006192///
6193/// \param CC the "context" location of the implicit conversion, i.e.
6194/// the most location of the syntactic entity requiring the implicit
6195/// conversion
6196void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006197 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006198 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006199 return;
6200
6201 // Don't diagnose for value- or type-dependent expressions.
6202 if (E->isTypeDependent() || E->isValueDependent())
6203 return;
6204
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006205 // Check for array bounds violations in cases where the check isn't triggered
6206 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6207 // ArraySubscriptExpr is on the RHS of a variable initialization.
6208 CheckArrayAccess(E);
6209
John McCallacf0ee52010-10-08 02:01:28 +00006210 // This is not the right CC for (e.g.) a variable initialization.
6211 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006212}
6213
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006214/// Diagnose when expression is an integer constant expression and its evaluation
6215/// results in integer overflow
6216void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006217 if (isa<BinaryOperator>(E->IgnoreParens()))
6218 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006219}
6220
Richard Smithc406cb72013-01-17 01:17:56 +00006221namespace {
6222/// \brief Visitor for expressions which looks for unsequenced operations on the
6223/// same object.
6224class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006225 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6226
Richard Smithc406cb72013-01-17 01:17:56 +00006227 /// \brief A tree of sequenced regions within an expression. Two regions are
6228 /// unsequenced if one is an ancestor or a descendent of the other. When we
6229 /// finish processing an expression with sequencing, such as a comma
6230 /// expression, we fold its tree nodes into its parent, since they are
6231 /// unsequenced with respect to nodes we will visit later.
6232 class SequenceTree {
6233 struct Value {
6234 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6235 unsigned Parent : 31;
6236 bool Merged : 1;
6237 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006238 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006239
6240 public:
6241 /// \brief A region within an expression which may be sequenced with respect
6242 /// to some other region.
6243 class Seq {
6244 explicit Seq(unsigned N) : Index(N) {}
6245 unsigned Index;
6246 friend class SequenceTree;
6247 public:
6248 Seq() : Index(0) {}
6249 };
6250
6251 SequenceTree() { Values.push_back(Value(0)); }
6252 Seq root() const { return Seq(0); }
6253
6254 /// \brief Create a new sequence of operations, which is an unsequenced
6255 /// subset of \p Parent. This sequence of operations is sequenced with
6256 /// respect to other children of \p Parent.
6257 Seq allocate(Seq Parent) {
6258 Values.push_back(Value(Parent.Index));
6259 return Seq(Values.size() - 1);
6260 }
6261
6262 /// \brief Merge a sequence of operations into its parent.
6263 void merge(Seq S) {
6264 Values[S.Index].Merged = true;
6265 }
6266
6267 /// \brief Determine whether two operations are unsequenced. This operation
6268 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6269 /// should have been merged into its parent as appropriate.
6270 bool isUnsequenced(Seq Cur, Seq Old) {
6271 unsigned C = representative(Cur.Index);
6272 unsigned Target = representative(Old.Index);
6273 while (C >= Target) {
6274 if (C == Target)
6275 return true;
6276 C = Values[C].Parent;
6277 }
6278 return false;
6279 }
6280
6281 private:
6282 /// \brief Pick a representative for a sequence.
6283 unsigned representative(unsigned K) {
6284 if (Values[K].Merged)
6285 // Perform path compression as we go.
6286 return Values[K].Parent = representative(Values[K].Parent);
6287 return K;
6288 }
6289 };
6290
6291 /// An object for which we can track unsequenced uses.
6292 typedef NamedDecl *Object;
6293
6294 /// Different flavors of object usage which we track. We only track the
6295 /// least-sequenced usage of each kind.
6296 enum UsageKind {
6297 /// A read of an object. Multiple unsequenced reads are OK.
6298 UK_Use,
6299 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006300 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006301 UK_ModAsValue,
6302 /// A modification of an object which is not sequenced before the value
6303 /// computation of the expression, such as n++.
6304 UK_ModAsSideEffect,
6305
6306 UK_Count = UK_ModAsSideEffect + 1
6307 };
6308
6309 struct Usage {
6310 Usage() : Use(0), Seq() {}
6311 Expr *Use;
6312 SequenceTree::Seq Seq;
6313 };
6314
6315 struct UsageInfo {
6316 UsageInfo() : Diagnosed(false) {}
6317 Usage Uses[UK_Count];
6318 /// Have we issued a diagnostic for this variable already?
6319 bool Diagnosed;
6320 };
6321 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6322
6323 Sema &SemaRef;
6324 /// Sequenced regions within the expression.
6325 SequenceTree Tree;
6326 /// Declaration modifications and references which we have seen.
6327 UsageInfoMap UsageMap;
6328 /// The region we are currently within.
6329 SequenceTree::Seq Region;
6330 /// Filled in with declarations which were modified as a side-effect
6331 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006332 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006333 /// Expressions to check later. We defer checking these to reduce
6334 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006335 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006336
6337 /// RAII object wrapping the visitation of a sequenced subexpression of an
6338 /// expression. At the end of this process, the side-effects of the evaluation
6339 /// become sequenced with respect to the value computation of the result, so
6340 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6341 /// UK_ModAsValue.
6342 struct SequencedSubexpression {
6343 SequencedSubexpression(SequenceChecker &Self)
6344 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6345 Self.ModAsSideEffect = &ModAsSideEffect;
6346 }
6347 ~SequencedSubexpression() {
6348 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6349 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6350 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6351 Self.addUsage(U, ModAsSideEffect[I].first,
6352 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6353 }
6354 Self.ModAsSideEffect = OldModAsSideEffect;
6355 }
6356
6357 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006358 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6359 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006360 };
6361
Richard Smith40238f02013-06-20 22:21:56 +00006362 /// RAII object wrapping the visitation of a subexpression which we might
6363 /// choose to evaluate as a constant. If any subexpression is evaluated and
6364 /// found to be non-constant, this allows us to suppress the evaluation of
6365 /// the outer expression.
6366 class EvaluationTracker {
6367 public:
6368 EvaluationTracker(SequenceChecker &Self)
6369 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6370 Self.EvalTracker = this;
6371 }
6372 ~EvaluationTracker() {
6373 Self.EvalTracker = Prev;
6374 if (Prev)
6375 Prev->EvalOK &= EvalOK;
6376 }
6377
6378 bool evaluate(const Expr *E, bool &Result) {
6379 if (!EvalOK || E->isValueDependent())
6380 return false;
6381 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6382 return EvalOK;
6383 }
6384
6385 private:
6386 SequenceChecker &Self;
6387 EvaluationTracker *Prev;
6388 bool EvalOK;
6389 } *EvalTracker;
6390
Richard Smithc406cb72013-01-17 01:17:56 +00006391 /// \brief Find the object which is produced by the specified expression,
6392 /// if any.
6393 Object getObject(Expr *E, bool Mod) const {
6394 E = E->IgnoreParenCasts();
6395 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6396 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6397 return getObject(UO->getSubExpr(), Mod);
6398 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6399 if (BO->getOpcode() == BO_Comma)
6400 return getObject(BO->getRHS(), Mod);
6401 if (Mod && BO->isAssignmentOp())
6402 return getObject(BO->getLHS(), Mod);
6403 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6404 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6405 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6406 return ME->getMemberDecl();
6407 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6408 // FIXME: If this is a reference, map through to its value.
6409 return DRE->getDecl();
6410 return 0;
6411 }
6412
6413 /// \brief Note that an object was modified or used by an expression.
6414 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6415 Usage &U = UI.Uses[UK];
6416 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6417 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6418 ModAsSideEffect->push_back(std::make_pair(O, U));
6419 U.Use = Ref;
6420 U.Seq = Region;
6421 }
6422 }
6423 /// \brief Check whether a modification or use conflicts with a prior usage.
6424 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6425 bool IsModMod) {
6426 if (UI.Diagnosed)
6427 return;
6428
6429 const Usage &U = UI.Uses[OtherKind];
6430 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6431 return;
6432
6433 Expr *Mod = U.Use;
6434 Expr *ModOrUse = Ref;
6435 if (OtherKind == UK_Use)
6436 std::swap(Mod, ModOrUse);
6437
6438 SemaRef.Diag(Mod->getExprLoc(),
6439 IsModMod ? diag::warn_unsequenced_mod_mod
6440 : diag::warn_unsequenced_mod_use)
6441 << O << SourceRange(ModOrUse->getExprLoc());
6442 UI.Diagnosed = true;
6443 }
6444
6445 void notePreUse(Object O, Expr *Use) {
6446 UsageInfo &U = UsageMap[O];
6447 // Uses conflict with other modifications.
6448 checkUsage(O, U, Use, UK_ModAsValue, false);
6449 }
6450 void notePostUse(Object O, Expr *Use) {
6451 UsageInfo &U = UsageMap[O];
6452 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6453 addUsage(U, O, Use, UK_Use);
6454 }
6455
6456 void notePreMod(Object O, Expr *Mod) {
6457 UsageInfo &U = UsageMap[O];
6458 // Modifications conflict with other modifications and with uses.
6459 checkUsage(O, U, Mod, UK_ModAsValue, true);
6460 checkUsage(O, U, Mod, UK_Use, false);
6461 }
6462 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6463 UsageInfo &U = UsageMap[O];
6464 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6465 addUsage(U, O, Use, UK);
6466 }
6467
6468public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006469 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6470 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6471 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006472 Visit(E);
6473 }
6474
6475 void VisitStmt(Stmt *S) {
6476 // Skip all statements which aren't expressions for now.
6477 }
6478
6479 void VisitExpr(Expr *E) {
6480 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006481 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006482 }
6483
6484 void VisitCastExpr(CastExpr *E) {
6485 Object O = Object();
6486 if (E->getCastKind() == CK_LValueToRValue)
6487 O = getObject(E->getSubExpr(), false);
6488
6489 if (O)
6490 notePreUse(O, E);
6491 VisitExpr(E);
6492 if (O)
6493 notePostUse(O, E);
6494 }
6495
6496 void VisitBinComma(BinaryOperator *BO) {
6497 // C++11 [expr.comma]p1:
6498 // Every value computation and side effect associated with the left
6499 // expression is sequenced before every value computation and side
6500 // effect associated with the right expression.
6501 SequenceTree::Seq LHS = Tree.allocate(Region);
6502 SequenceTree::Seq RHS = Tree.allocate(Region);
6503 SequenceTree::Seq OldRegion = Region;
6504
6505 {
6506 SequencedSubexpression SeqLHS(*this);
6507 Region = LHS;
6508 Visit(BO->getLHS());
6509 }
6510
6511 Region = RHS;
6512 Visit(BO->getRHS());
6513
6514 Region = OldRegion;
6515
6516 // Forget that LHS and RHS are sequenced. They are both unsequenced
6517 // with respect to other stuff.
6518 Tree.merge(LHS);
6519 Tree.merge(RHS);
6520 }
6521
6522 void VisitBinAssign(BinaryOperator *BO) {
6523 // The modification is sequenced after the value computation of the LHS
6524 // and RHS, so check it before inspecting the operands and update the
6525 // map afterwards.
6526 Object O = getObject(BO->getLHS(), true);
6527 if (!O)
6528 return VisitExpr(BO);
6529
6530 notePreMod(O, BO);
6531
6532 // C++11 [expr.ass]p7:
6533 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6534 // only once.
6535 //
6536 // Therefore, for a compound assignment operator, O is considered used
6537 // everywhere except within the evaluation of E1 itself.
6538 if (isa<CompoundAssignOperator>(BO))
6539 notePreUse(O, BO);
6540
6541 Visit(BO->getLHS());
6542
6543 if (isa<CompoundAssignOperator>(BO))
6544 notePostUse(O, BO);
6545
6546 Visit(BO->getRHS());
6547
Richard Smith83e37bee2013-06-26 23:16:51 +00006548 // C++11 [expr.ass]p1:
6549 // the assignment is sequenced [...] before the value computation of the
6550 // assignment expression.
6551 // C11 6.5.16/3 has no such rule.
6552 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6553 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006554 }
6555 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6556 VisitBinAssign(CAO);
6557 }
6558
6559 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6560 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6561 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6562 Object O = getObject(UO->getSubExpr(), true);
6563 if (!O)
6564 return VisitExpr(UO);
6565
6566 notePreMod(O, UO);
6567 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006568 // C++11 [expr.pre.incr]p1:
6569 // the expression ++x is equivalent to x+=1
6570 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6571 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006572 }
6573
6574 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6575 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6576 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6577 Object O = getObject(UO->getSubExpr(), true);
6578 if (!O)
6579 return VisitExpr(UO);
6580
6581 notePreMod(O, UO);
6582 Visit(UO->getSubExpr());
6583 notePostMod(O, UO, UK_ModAsSideEffect);
6584 }
6585
6586 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6587 void VisitBinLOr(BinaryOperator *BO) {
6588 // The side-effects of the LHS of an '&&' are sequenced before the
6589 // value computation of the RHS, and hence before the value computation
6590 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6591 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006592 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006593 {
6594 SequencedSubexpression Sequenced(*this);
6595 Visit(BO->getLHS());
6596 }
6597
6598 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006599 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006600 if (!Result)
6601 Visit(BO->getRHS());
6602 } else {
6603 // Check for unsequenced operations in the RHS, treating it as an
6604 // entirely separate evaluation.
6605 //
6606 // FIXME: If there are operations in the RHS which are unsequenced
6607 // with respect to operations outside the RHS, and those operations
6608 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006609 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006610 }
Richard Smithc406cb72013-01-17 01:17:56 +00006611 }
6612 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006613 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006614 {
6615 SequencedSubexpression Sequenced(*this);
6616 Visit(BO->getLHS());
6617 }
6618
6619 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006620 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006621 if (Result)
6622 Visit(BO->getRHS());
6623 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006624 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006625 }
Richard Smithc406cb72013-01-17 01:17:56 +00006626 }
6627
6628 // Only visit the condition, unless we can be sure which subexpression will
6629 // be chosen.
6630 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006631 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006632 {
6633 SequencedSubexpression Sequenced(*this);
6634 Visit(CO->getCond());
6635 }
Richard Smithc406cb72013-01-17 01:17:56 +00006636
6637 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006638 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006639 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006640 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006641 WorkList.push_back(CO->getTrueExpr());
6642 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006643 }
Richard Smithc406cb72013-01-17 01:17:56 +00006644 }
6645
Richard Smithe3dbfe02013-06-30 10:40:20 +00006646 void VisitCallExpr(CallExpr *CE) {
6647 // C++11 [intro.execution]p15:
6648 // When calling a function [...], every value computation and side effect
6649 // associated with any argument expression, or with the postfix expression
6650 // designating the called function, is sequenced before execution of every
6651 // expression or statement in the body of the function [and thus before
6652 // the value computation of its result].
6653 SequencedSubexpression Sequenced(*this);
6654 Base::VisitCallExpr(CE);
6655
6656 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6657 }
6658
Richard Smithc406cb72013-01-17 01:17:56 +00006659 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006660 // This is a call, so all subexpressions are sequenced before the result.
6661 SequencedSubexpression Sequenced(*this);
6662
Richard Smithc406cb72013-01-17 01:17:56 +00006663 if (!CCE->isListInitialization())
6664 return VisitExpr(CCE);
6665
6666 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006667 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006668 SequenceTree::Seq Parent = Region;
6669 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6670 E = CCE->arg_end();
6671 I != E; ++I) {
6672 Region = Tree.allocate(Parent);
6673 Elts.push_back(Region);
6674 Visit(*I);
6675 }
6676
6677 // Forget that the initializers are sequenced.
6678 Region = Parent;
6679 for (unsigned I = 0; I < Elts.size(); ++I)
6680 Tree.merge(Elts[I]);
6681 }
6682
6683 void VisitInitListExpr(InitListExpr *ILE) {
6684 if (!SemaRef.getLangOpts().CPlusPlus11)
6685 return VisitExpr(ILE);
6686
6687 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006688 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006689 SequenceTree::Seq Parent = Region;
6690 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6691 Expr *E = ILE->getInit(I);
6692 if (!E) continue;
6693 Region = Tree.allocate(Parent);
6694 Elts.push_back(Region);
6695 Visit(E);
6696 }
6697
6698 // Forget that the initializers are sequenced.
6699 Region = Parent;
6700 for (unsigned I = 0; I < Elts.size(); ++I)
6701 Tree.merge(Elts[I]);
6702 }
6703};
6704}
6705
6706void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006707 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006708 WorkList.push_back(E);
6709 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006710 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006711 SequenceChecker(*this, Item, WorkList);
6712 }
Richard Smithc406cb72013-01-17 01:17:56 +00006713}
6714
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006715void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6716 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006717 CheckImplicitConversions(E, CheckLoc);
6718 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006719 if (!IsConstexpr && !E->isValueDependent())
6720 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006721}
6722
John McCall1f425642010-11-11 03:21:53 +00006723void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6724 FieldDecl *BitField,
6725 Expr *Init) {
6726 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6727}
6728
Mike Stump0c2ec772010-01-21 03:59:47 +00006729/// CheckParmsForFunctionDef - Check that the parameters of the given
6730/// function are appropriate for the definition of a function. This
6731/// takes care of any checks that cannot be performed on the
6732/// declaration itself, e.g., that the types of each of the function
6733/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006734bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6735 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006736 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006737 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006738 for (; P != PEnd; ++P) {
6739 ParmVarDecl *Param = *P;
6740
Mike Stump0c2ec772010-01-21 03:59:47 +00006741 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6742 // function declarator that is part of a function definition of
6743 // that function shall not have incomplete type.
6744 //
6745 // This is also C++ [dcl.fct]p6.
6746 if (!Param->isInvalidDecl() &&
6747 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006748 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006749 Param->setInvalidDecl();
6750 HasInvalidParm = true;
6751 }
6752
6753 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6754 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006755 if (CheckParameterNames &&
6756 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006757 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006758 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006759 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006760
6761 // C99 6.7.5.3p12:
6762 // If the function declarator is not part of a definition of that
6763 // function, parameters may have incomplete type and may use the [*]
6764 // notation in their sequences of declarator specifiers to specify
6765 // variable length array types.
6766 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006767 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006768 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006769 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006770 // information is added for it.
6771 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006772 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006773 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006774 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006775 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006776
6777 // MSVC destroys objects passed by value in the callee. Therefore a
6778 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006779 // object's destructor. However, we don't perform any direct access check
6780 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006781 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6782 .getCXXABI()
6783 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006784 if (!Param->isInvalidDecl()) {
6785 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6786 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6787 if (!ClassDecl->isInvalidDecl() &&
6788 !ClassDecl->hasIrrelevantDestructor() &&
6789 !ClassDecl->isDependentContext()) {
6790 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6791 MarkFunctionReferenced(Param->getLocation(), Destructor);
6792 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6793 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006794 }
6795 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006796 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006797 }
6798
6799 return HasInvalidParm;
6800}
John McCall2b5c1b22010-08-12 21:44:57 +00006801
6802/// CheckCastAlign - Implements -Wcast-align, which warns when a
6803/// pointer cast increases the alignment requirements.
6804void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6805 // This is actually a lot of work to potentially be doing on every
6806 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006807 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6808 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006809 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006810 return;
6811
6812 // Ignore dependent types.
6813 if (T->isDependentType() || Op->getType()->isDependentType())
6814 return;
6815
6816 // Require that the destination be a pointer type.
6817 const PointerType *DestPtr = T->getAs<PointerType>();
6818 if (!DestPtr) return;
6819
6820 // If the destination has alignment 1, we're done.
6821 QualType DestPointee = DestPtr->getPointeeType();
6822 if (DestPointee->isIncompleteType()) return;
6823 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6824 if (DestAlign.isOne()) return;
6825
6826 // Require that the source be a pointer type.
6827 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6828 if (!SrcPtr) return;
6829 QualType SrcPointee = SrcPtr->getPointeeType();
6830
6831 // Whitelist casts from cv void*. We already implicitly
6832 // whitelisted casts to cv void*, since they have alignment 1.
6833 // Also whitelist casts involving incomplete types, which implicitly
6834 // includes 'void'.
6835 if (SrcPointee->isIncompleteType()) return;
6836
6837 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6838 if (SrcAlign >= DestAlign) return;
6839
6840 Diag(TRange.getBegin(), diag::warn_cast_align)
6841 << Op->getType() << T
6842 << static_cast<unsigned>(SrcAlign.getQuantity())
6843 << static_cast<unsigned>(DestAlign.getQuantity())
6844 << TRange << Op->getSourceRange();
6845}
6846
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006847static const Type* getElementType(const Expr *BaseExpr) {
6848 const Type* EltType = BaseExpr->getType().getTypePtr();
6849 if (EltType->isAnyPointerType())
6850 return EltType->getPointeeType().getTypePtr();
6851 else if (EltType->isArrayType())
6852 return EltType->getBaseElementTypeUnsafe();
6853 return EltType;
6854}
6855
Chandler Carruth28389f02011-08-05 09:10:50 +00006856/// \brief Check whether this array fits the idiom of a size-one tail padded
6857/// array member of a struct.
6858///
6859/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6860/// commonly used to emulate flexible arrays in C89 code.
6861static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6862 const NamedDecl *ND) {
6863 if (Size != 1 || !ND) return false;
6864
6865 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6866 if (!FD) return false;
6867
6868 // Don't consider sizes resulting from macro expansions or template argument
6869 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006870
6871 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006872 while (TInfo) {
6873 TypeLoc TL = TInfo->getTypeLoc();
6874 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006875 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6876 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006877 TInfo = TDL->getTypeSourceInfo();
6878 continue;
6879 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006880 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6881 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006882 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6883 return false;
6884 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006885 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006886 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006887
6888 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006889 if (!RD) return false;
6890 if (RD->isUnion()) return false;
6891 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6892 if (!CRD->isStandardLayout()) return false;
6893 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006894
Benjamin Kramer8c543672011-08-06 03:04:42 +00006895 // See if this is the last field decl in the record.
6896 const Decl *D = FD;
6897 while ((D = D->getNextDeclInContext()))
6898 if (isa<FieldDecl>(D))
6899 return false;
6900 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006901}
6902
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006903void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006904 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006905 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006906 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006907 if (IndexExpr->isValueDependent())
6908 return;
6909
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006910 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006911 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006912 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006913 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006914 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006915 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006916
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006917 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006918 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006919 return;
Richard Smith13f67182011-12-16 19:31:14 +00006920 if (IndexNegated)
6921 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006922
Chandler Carruth126b1552011-08-05 08:07:29 +00006923 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006924 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6925 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006926 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006927 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006928
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006929 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006930 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006931 if (!size.isStrictlyPositive())
6932 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006933
6934 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006935 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006936 // Make sure we're comparing apples to apples when comparing index to size
6937 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6938 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006939 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006940 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006941 if (ptrarith_typesize != array_typesize) {
6942 // There's a cast to a different size type involved
6943 uint64_t ratio = array_typesize / ptrarith_typesize;
6944 // TODO: Be smarter about handling cases where array_typesize is not a
6945 // multiple of ptrarith_typesize
6946 if (ptrarith_typesize * ratio == array_typesize)
6947 size *= llvm::APInt(size.getBitWidth(), ratio);
6948 }
6949 }
6950
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006951 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006952 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006953 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006954 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006955
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006956 // For array subscripting the index must be less than size, but for pointer
6957 // arithmetic also allow the index (offset) to be equal to size since
6958 // computing the next address after the end of the array is legal and
6959 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006960 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006961 return;
6962
6963 // Also don't warn for arrays of size 1 which are members of some
6964 // structure. These are often used to approximate flexible arrays in C89
6965 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006966 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006967 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006968
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006969 // Suppress the warning if the subscript expression (as identified by the
6970 // ']' location) and the index expression are both from macro expansions
6971 // within a system header.
6972 if (ASE) {
6973 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6974 ASE->getRBracketLoc());
6975 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6976 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6977 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006978 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006979 return;
6980 }
6981 }
6982
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006983 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006984 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006985 DiagID = diag::warn_array_index_exceeds_bounds;
6986
6987 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6988 PDiag(DiagID) << index.toString(10, true)
6989 << size.toString(10, true)
6990 << (unsigned)size.getLimitedValue(~0U)
6991 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006992 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006993 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006994 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006995 DiagID = diag::warn_ptr_arith_precedes_bounds;
6996 if (index.isNegative()) index = -index;
6997 }
6998
6999 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7000 PDiag(DiagID) << index.toString(10, true)
7001 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007002 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007003
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007004 if (!ND) {
7005 // Try harder to find a NamedDecl to point at in the note.
7006 while (const ArraySubscriptExpr *ASE =
7007 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7008 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7009 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7010 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7011 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7012 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7013 }
7014
Chandler Carruth1af88f12011-02-17 21:10:52 +00007015 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007016 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7017 PDiag(diag::note_array_index_out_of_bounds)
7018 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007019}
7020
Ted Kremenekdf26df72011-03-01 18:41:00 +00007021void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007022 int AllowOnePastEnd = 0;
7023 while (expr) {
7024 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007025 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007026 case Stmt::ArraySubscriptExprClass: {
7027 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007028 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007029 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007030 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007031 }
7032 case Stmt::UnaryOperatorClass: {
7033 // Only unwrap the * and & unary operators
7034 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7035 expr = UO->getSubExpr();
7036 switch (UO->getOpcode()) {
7037 case UO_AddrOf:
7038 AllowOnePastEnd++;
7039 break;
7040 case UO_Deref:
7041 AllowOnePastEnd--;
7042 break;
7043 default:
7044 return;
7045 }
7046 break;
7047 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007048 case Stmt::ConditionalOperatorClass: {
7049 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7050 if (const Expr *lhs = cond->getLHS())
7051 CheckArrayAccess(lhs);
7052 if (const Expr *rhs = cond->getRHS())
7053 CheckArrayAccess(rhs);
7054 return;
7055 }
7056 default:
7057 return;
7058 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007059 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007060}
John McCall31168b02011-06-15 23:02:42 +00007061
7062//===--- CHECK: Objective-C retain cycles ----------------------------------//
7063
7064namespace {
7065 struct RetainCycleOwner {
7066 RetainCycleOwner() : Variable(0), Indirect(false) {}
7067 VarDecl *Variable;
7068 SourceRange Range;
7069 SourceLocation Loc;
7070 bool Indirect;
7071
7072 void setLocsFrom(Expr *e) {
7073 Loc = e->getExprLoc();
7074 Range = e->getSourceRange();
7075 }
7076 };
7077}
7078
7079/// Consider whether capturing the given variable can possibly lead to
7080/// a retain cycle.
7081static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007082 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007083 // lifetime. In MRR, it's captured strongly if the variable is
7084 // __block and has an appropriate type.
7085 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7086 return false;
7087
7088 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007089 if (ref)
7090 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007091 return true;
7092}
7093
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007094static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007095 while (true) {
7096 e = e->IgnoreParens();
7097 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7098 switch (cast->getCastKind()) {
7099 case CK_BitCast:
7100 case CK_LValueBitCast:
7101 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007102 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007103 e = cast->getSubExpr();
7104 continue;
7105
John McCall31168b02011-06-15 23:02:42 +00007106 default:
7107 return false;
7108 }
7109 }
7110
7111 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7112 ObjCIvarDecl *ivar = ref->getDecl();
7113 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7114 return false;
7115
7116 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007117 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007118 return false;
7119
7120 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7121 owner.Indirect = true;
7122 return true;
7123 }
7124
7125 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7126 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7127 if (!var) return false;
7128 return considerVariable(var, ref, owner);
7129 }
7130
John McCall31168b02011-06-15 23:02:42 +00007131 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7132 if (member->isArrow()) return false;
7133
7134 // Don't count this as an indirect ownership.
7135 e = member->getBase();
7136 continue;
7137 }
7138
John McCallfe96e0b2011-11-06 09:01:30 +00007139 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7140 // Only pay attention to pseudo-objects on property references.
7141 ObjCPropertyRefExpr *pre
7142 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7143 ->IgnoreParens());
7144 if (!pre) return false;
7145 if (pre->isImplicitProperty()) return false;
7146 ObjCPropertyDecl *property = pre->getExplicitProperty();
7147 if (!property->isRetaining() &&
7148 !(property->getPropertyIvarDecl() &&
7149 property->getPropertyIvarDecl()->getType()
7150 .getObjCLifetime() == Qualifiers::OCL_Strong))
7151 return false;
7152
7153 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007154 if (pre->isSuperReceiver()) {
7155 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7156 if (!owner.Variable)
7157 return false;
7158 owner.Loc = pre->getLocation();
7159 owner.Range = pre->getSourceRange();
7160 return true;
7161 }
John McCallfe96e0b2011-11-06 09:01:30 +00007162 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7163 ->getSourceExpr());
7164 continue;
7165 }
7166
John McCall31168b02011-06-15 23:02:42 +00007167 // Array ivars?
7168
7169 return false;
7170 }
7171}
7172
7173namespace {
7174 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7175 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7176 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7177 Variable(variable), Capturer(0) {}
7178
7179 VarDecl *Variable;
7180 Expr *Capturer;
7181
7182 void VisitDeclRefExpr(DeclRefExpr *ref) {
7183 if (ref->getDecl() == Variable && !Capturer)
7184 Capturer = ref;
7185 }
7186
John McCall31168b02011-06-15 23:02:42 +00007187 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7188 if (Capturer) return;
7189 Visit(ref->getBase());
7190 if (Capturer && ref->isFreeIvar())
7191 Capturer = ref;
7192 }
7193
7194 void VisitBlockExpr(BlockExpr *block) {
7195 // Look inside nested blocks
7196 if (block->getBlockDecl()->capturesVariable(Variable))
7197 Visit(block->getBlockDecl()->getBody());
7198 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007199
7200 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7201 if (Capturer) return;
7202 if (OVE->getSourceExpr())
7203 Visit(OVE->getSourceExpr());
7204 }
John McCall31168b02011-06-15 23:02:42 +00007205 };
7206}
7207
7208/// Check whether the given argument is a block which captures a
7209/// variable.
7210static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7211 assert(owner.Variable && owner.Loc.isValid());
7212
7213 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007214
7215 // Look through [^{...} copy] and Block_copy(^{...}).
7216 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7217 Selector Cmd = ME->getSelector();
7218 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7219 e = ME->getInstanceReceiver();
7220 if (!e)
7221 return 0;
7222 e = e->IgnoreParenCasts();
7223 }
7224 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7225 if (CE->getNumArgs() == 1) {
7226 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007227 if (Fn) {
7228 const IdentifierInfo *FnI = Fn->getIdentifier();
7229 if (FnI && FnI->isStr("_Block_copy")) {
7230 e = CE->getArg(0)->IgnoreParenCasts();
7231 }
7232 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007233 }
7234 }
7235
John McCall31168b02011-06-15 23:02:42 +00007236 BlockExpr *block = dyn_cast<BlockExpr>(e);
7237 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7238 return 0;
7239
7240 FindCaptureVisitor visitor(S.Context, owner.Variable);
7241 visitor.Visit(block->getBlockDecl()->getBody());
7242 return visitor.Capturer;
7243}
7244
7245static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7246 RetainCycleOwner &owner) {
7247 assert(capturer);
7248 assert(owner.Variable && owner.Loc.isValid());
7249
7250 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7251 << owner.Variable << capturer->getSourceRange();
7252 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7253 << owner.Indirect << owner.Range;
7254}
7255
7256/// Check for a keyword selector that starts with the word 'add' or
7257/// 'set'.
7258static bool isSetterLikeSelector(Selector sel) {
7259 if (sel.isUnarySelector()) return false;
7260
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007261 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007262 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007263 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007264 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007265 else if (str.startswith("add")) {
7266 // Specially whitelist 'addOperationWithBlock:'.
7267 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7268 return false;
7269 str = str.substr(3);
7270 }
John McCall31168b02011-06-15 23:02:42 +00007271 else
7272 return false;
7273
7274 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007275 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007276}
7277
7278/// Check a message send to see if it's likely to cause a retain cycle.
7279void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7280 // Only check instance methods whose selector looks like a setter.
7281 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7282 return;
7283
7284 // Try to find a variable that the receiver is strongly owned by.
7285 RetainCycleOwner owner;
7286 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007287 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007288 return;
7289 } else {
7290 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7291 owner.Variable = getCurMethodDecl()->getSelfDecl();
7292 owner.Loc = msg->getSuperLoc();
7293 owner.Range = msg->getSuperLoc();
7294 }
7295
7296 // Check whether the receiver is captured by any of the arguments.
7297 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7298 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7299 return diagnoseRetainCycle(*this, capturer, owner);
7300}
7301
7302/// Check a property assign to see if it's likely to cause a retain cycle.
7303void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7304 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007305 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007306 return;
7307
7308 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7309 diagnoseRetainCycle(*this, capturer, owner);
7310}
7311
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007312void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7313 RetainCycleOwner Owner;
7314 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7315 return;
7316
7317 // Because we don't have an expression for the variable, we have to set the
7318 // location explicitly here.
7319 Owner.Loc = Var->getLocation();
7320 Owner.Range = Var->getSourceRange();
7321
7322 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7323 diagnoseRetainCycle(*this, Capturer, Owner);
7324}
7325
Ted Kremenek9304da92012-12-21 08:04:28 +00007326static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7327 Expr *RHS, bool isProperty) {
7328 // Check if RHS is an Objective-C object literal, which also can get
7329 // immediately zapped in a weak reference. Note that we explicitly
7330 // allow ObjCStringLiterals, since those are designed to never really die.
7331 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007332
Ted Kremenek64873352012-12-21 22:46:35 +00007333 // This enum needs to match with the 'select' in
7334 // warn_objc_arc_literal_assign (off-by-1).
7335 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7336 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7337 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007338
7339 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007340 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007341 << (isProperty ? 0 : 1)
7342 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007343
7344 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007345}
7346
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007347static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7348 Qualifiers::ObjCLifetime LT,
7349 Expr *RHS, bool isProperty) {
7350 // Strip off any implicit cast added to get to the one ARC-specific.
7351 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7352 if (cast->getCastKind() == CK_ARCConsumeObject) {
7353 S.Diag(Loc, diag::warn_arc_retained_assign)
7354 << (LT == Qualifiers::OCL_ExplicitNone)
7355 << (isProperty ? 0 : 1)
7356 << RHS->getSourceRange();
7357 return true;
7358 }
7359 RHS = cast->getSubExpr();
7360 }
7361
7362 if (LT == Qualifiers::OCL_Weak &&
7363 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7364 return true;
7365
7366 return false;
7367}
7368
Ted Kremenekb36234d2012-12-21 08:04:20 +00007369bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7370 QualType LHS, Expr *RHS) {
7371 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7372
7373 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7374 return false;
7375
7376 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7377 return true;
7378
7379 return false;
7380}
7381
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007382void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7383 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007384 QualType LHSType;
7385 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007386 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007387 ObjCPropertyRefExpr *PRE
7388 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7389 if (PRE && !PRE->isImplicitProperty()) {
7390 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7391 if (PD)
7392 LHSType = PD->getType();
7393 }
7394
7395 if (LHSType.isNull())
7396 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007397
7398 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7399
7400 if (LT == Qualifiers::OCL_Weak) {
7401 DiagnosticsEngine::Level Level =
7402 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7403 if (Level != DiagnosticsEngine::Ignored)
7404 getCurFunction()->markSafeWeakUse(LHS);
7405 }
7406
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007407 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7408 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007409
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007410 // FIXME. Check for other life times.
7411 if (LT != Qualifiers::OCL_None)
7412 return;
7413
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007414 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007415 if (PRE->isImplicitProperty())
7416 return;
7417 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7418 if (!PD)
7419 return;
7420
Bill Wendling44426052012-12-20 19:22:21 +00007421 unsigned Attributes = PD->getPropertyAttributes();
7422 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007423 // when 'assign' attribute was not explicitly specified
7424 // by user, ignore it and rely on property type itself
7425 // for lifetime info.
7426 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7427 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7428 LHSType->isObjCRetainableType())
7429 return;
7430
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007431 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007432 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007433 Diag(Loc, diag::warn_arc_retained_property_assign)
7434 << RHS->getSourceRange();
7435 return;
7436 }
7437 RHS = cast->getSubExpr();
7438 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007439 }
Bill Wendling44426052012-12-20 19:22:21 +00007440 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007441 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7442 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007443 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007444 }
7445}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007446
7447//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7448
7449namespace {
7450bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7451 SourceLocation StmtLoc,
7452 const NullStmt *Body) {
7453 // Do not warn if the body is a macro that expands to nothing, e.g:
7454 //
7455 // #define CALL(x)
7456 // if (condition)
7457 // CALL(0);
7458 //
7459 if (Body->hasLeadingEmptyMacro())
7460 return false;
7461
7462 // Get line numbers of statement and body.
7463 bool StmtLineInvalid;
7464 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7465 &StmtLineInvalid);
7466 if (StmtLineInvalid)
7467 return false;
7468
7469 bool BodyLineInvalid;
7470 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7471 &BodyLineInvalid);
7472 if (BodyLineInvalid)
7473 return false;
7474
7475 // Warn if null statement and body are on the same line.
7476 if (StmtLine != BodyLine)
7477 return false;
7478
7479 return true;
7480}
7481} // Unnamed namespace
7482
7483void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7484 const Stmt *Body,
7485 unsigned DiagID) {
7486 // Since this is a syntactic check, don't emit diagnostic for template
7487 // instantiations, this just adds noise.
7488 if (CurrentInstantiationScope)
7489 return;
7490
7491 // The body should be a null statement.
7492 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7493 if (!NBody)
7494 return;
7495
7496 // Do the usual checks.
7497 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7498 return;
7499
7500 Diag(NBody->getSemiLoc(), DiagID);
7501 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7502}
7503
7504void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7505 const Stmt *PossibleBody) {
7506 assert(!CurrentInstantiationScope); // Ensured by caller
7507
7508 SourceLocation StmtLoc;
7509 const Stmt *Body;
7510 unsigned DiagID;
7511 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7512 StmtLoc = FS->getRParenLoc();
7513 Body = FS->getBody();
7514 DiagID = diag::warn_empty_for_body;
7515 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7516 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7517 Body = WS->getBody();
7518 DiagID = diag::warn_empty_while_body;
7519 } else
7520 return; // Neither `for' nor `while'.
7521
7522 // The body should be a null statement.
7523 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7524 if (!NBody)
7525 return;
7526
7527 // Skip expensive checks if diagnostic is disabled.
7528 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7529 DiagnosticsEngine::Ignored)
7530 return;
7531
7532 // Do the usual checks.
7533 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7534 return;
7535
7536 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7537 // noise level low, emit diagnostics only if for/while is followed by a
7538 // CompoundStmt, e.g.:
7539 // for (int i = 0; i < n; i++);
7540 // {
7541 // a(i);
7542 // }
7543 // or if for/while is followed by a statement with more indentation
7544 // than for/while itself:
7545 // for (int i = 0; i < n; i++);
7546 // a(i);
7547 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7548 if (!ProbableTypo) {
7549 bool BodyColInvalid;
7550 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7551 PossibleBody->getLocStart(),
7552 &BodyColInvalid);
7553 if (BodyColInvalid)
7554 return;
7555
7556 bool StmtColInvalid;
7557 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7558 S->getLocStart(),
7559 &StmtColInvalid);
7560 if (StmtColInvalid)
7561 return;
7562
7563 if (BodyCol > StmtCol)
7564 ProbableTypo = true;
7565 }
7566
7567 if (ProbableTypo) {
7568 Diag(NBody->getSemiLoc(), DiagID);
7569 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7570 }
7571}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007572
7573//===--- Layout compatibility ----------------------------------------------//
7574
7575namespace {
7576
7577bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7578
7579/// \brief Check if two enumeration types are layout-compatible.
7580bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7581 // C++11 [dcl.enum] p8:
7582 // Two enumeration types are layout-compatible if they have the same
7583 // underlying type.
7584 return ED1->isComplete() && ED2->isComplete() &&
7585 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7586}
7587
7588/// \brief Check if two fields are layout-compatible.
7589bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7590 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7591 return false;
7592
7593 if (Field1->isBitField() != Field2->isBitField())
7594 return false;
7595
7596 if (Field1->isBitField()) {
7597 // Make sure that the bit-fields are the same length.
7598 unsigned Bits1 = Field1->getBitWidthValue(C);
7599 unsigned Bits2 = Field2->getBitWidthValue(C);
7600
7601 if (Bits1 != Bits2)
7602 return false;
7603 }
7604
7605 return true;
7606}
7607
7608/// \brief Check if two standard-layout structs are layout-compatible.
7609/// (C++11 [class.mem] p17)
7610bool isLayoutCompatibleStruct(ASTContext &C,
7611 RecordDecl *RD1,
7612 RecordDecl *RD2) {
7613 // If both records are C++ classes, check that base classes match.
7614 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7615 // If one of records is a CXXRecordDecl we are in C++ mode,
7616 // thus the other one is a CXXRecordDecl, too.
7617 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7618 // Check number of base classes.
7619 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7620 return false;
7621
7622 // Check the base classes.
7623 for (CXXRecordDecl::base_class_const_iterator
7624 Base1 = D1CXX->bases_begin(),
7625 BaseEnd1 = D1CXX->bases_end(),
7626 Base2 = D2CXX->bases_begin();
7627 Base1 != BaseEnd1;
7628 ++Base1, ++Base2) {
7629 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7630 return false;
7631 }
7632 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7633 // If only RD2 is a C++ class, it should have zero base classes.
7634 if (D2CXX->getNumBases() > 0)
7635 return false;
7636 }
7637
7638 // Check the fields.
7639 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7640 Field2End = RD2->field_end(),
7641 Field1 = RD1->field_begin(),
7642 Field1End = RD1->field_end();
7643 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7644 if (!isLayoutCompatible(C, *Field1, *Field2))
7645 return false;
7646 }
7647 if (Field1 != Field1End || Field2 != Field2End)
7648 return false;
7649
7650 return true;
7651}
7652
7653/// \brief Check if two standard-layout unions are layout-compatible.
7654/// (C++11 [class.mem] p18)
7655bool isLayoutCompatibleUnion(ASTContext &C,
7656 RecordDecl *RD1,
7657 RecordDecl *RD2) {
7658 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007659 for (auto *Field2 : RD2->fields())
7660 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007661
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007662 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007663 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7664 I = UnmatchedFields.begin(),
7665 E = UnmatchedFields.end();
7666
7667 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007668 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007669 bool Result = UnmatchedFields.erase(*I);
7670 (void) Result;
7671 assert(Result);
7672 break;
7673 }
7674 }
7675 if (I == E)
7676 return false;
7677 }
7678
7679 return UnmatchedFields.empty();
7680}
7681
7682bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7683 if (RD1->isUnion() != RD2->isUnion())
7684 return false;
7685
7686 if (RD1->isUnion())
7687 return isLayoutCompatibleUnion(C, RD1, RD2);
7688 else
7689 return isLayoutCompatibleStruct(C, RD1, RD2);
7690}
7691
7692/// \brief Check if two types are layout-compatible in C++11 sense.
7693bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7694 if (T1.isNull() || T2.isNull())
7695 return false;
7696
7697 // C++11 [basic.types] p11:
7698 // If two types T1 and T2 are the same type, then T1 and T2 are
7699 // layout-compatible types.
7700 if (C.hasSameType(T1, T2))
7701 return true;
7702
7703 T1 = T1.getCanonicalType().getUnqualifiedType();
7704 T2 = T2.getCanonicalType().getUnqualifiedType();
7705
7706 const Type::TypeClass TC1 = T1->getTypeClass();
7707 const Type::TypeClass TC2 = T2->getTypeClass();
7708
7709 if (TC1 != TC2)
7710 return false;
7711
7712 if (TC1 == Type::Enum) {
7713 return isLayoutCompatible(C,
7714 cast<EnumType>(T1)->getDecl(),
7715 cast<EnumType>(T2)->getDecl());
7716 } else if (TC1 == Type::Record) {
7717 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7718 return false;
7719
7720 return isLayoutCompatible(C,
7721 cast<RecordType>(T1)->getDecl(),
7722 cast<RecordType>(T2)->getDecl());
7723 }
7724
7725 return false;
7726}
7727}
7728
7729//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7730
7731namespace {
7732/// \brief Given a type tag expression find the type tag itself.
7733///
7734/// \param TypeExpr Type tag expression, as it appears in user's code.
7735///
7736/// \param VD Declaration of an identifier that appears in a type tag.
7737///
7738/// \param MagicValue Type tag magic value.
7739bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7740 const ValueDecl **VD, uint64_t *MagicValue) {
7741 while(true) {
7742 if (!TypeExpr)
7743 return false;
7744
7745 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7746
7747 switch (TypeExpr->getStmtClass()) {
7748 case Stmt::UnaryOperatorClass: {
7749 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7750 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7751 TypeExpr = UO->getSubExpr();
7752 continue;
7753 }
7754 return false;
7755 }
7756
7757 case Stmt::DeclRefExprClass: {
7758 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7759 *VD = DRE->getDecl();
7760 return true;
7761 }
7762
7763 case Stmt::IntegerLiteralClass: {
7764 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7765 llvm::APInt MagicValueAPInt = IL->getValue();
7766 if (MagicValueAPInt.getActiveBits() <= 64) {
7767 *MagicValue = MagicValueAPInt.getZExtValue();
7768 return true;
7769 } else
7770 return false;
7771 }
7772
7773 case Stmt::BinaryConditionalOperatorClass:
7774 case Stmt::ConditionalOperatorClass: {
7775 const AbstractConditionalOperator *ACO =
7776 cast<AbstractConditionalOperator>(TypeExpr);
7777 bool Result;
7778 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7779 if (Result)
7780 TypeExpr = ACO->getTrueExpr();
7781 else
7782 TypeExpr = ACO->getFalseExpr();
7783 continue;
7784 }
7785 return false;
7786 }
7787
7788 case Stmt::BinaryOperatorClass: {
7789 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7790 if (BO->getOpcode() == BO_Comma) {
7791 TypeExpr = BO->getRHS();
7792 continue;
7793 }
7794 return false;
7795 }
7796
7797 default:
7798 return false;
7799 }
7800 }
7801}
7802
7803/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7804///
7805/// \param TypeExpr Expression that specifies a type tag.
7806///
7807/// \param MagicValues Registered magic values.
7808///
7809/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7810/// kind.
7811///
7812/// \param TypeInfo Information about the corresponding C type.
7813///
7814/// \returns true if the corresponding C type was found.
7815bool GetMatchingCType(
7816 const IdentifierInfo *ArgumentKind,
7817 const Expr *TypeExpr, const ASTContext &Ctx,
7818 const llvm::DenseMap<Sema::TypeTagMagicValue,
7819 Sema::TypeTagData> *MagicValues,
7820 bool &FoundWrongKind,
7821 Sema::TypeTagData &TypeInfo) {
7822 FoundWrongKind = false;
7823
7824 // Variable declaration that has type_tag_for_datatype attribute.
7825 const ValueDecl *VD = NULL;
7826
7827 uint64_t MagicValue;
7828
7829 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7830 return false;
7831
7832 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007833 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007834 if (I->getArgumentKind() != ArgumentKind) {
7835 FoundWrongKind = true;
7836 return false;
7837 }
7838 TypeInfo.Type = I->getMatchingCType();
7839 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7840 TypeInfo.MustBeNull = I->getMustBeNull();
7841 return true;
7842 }
7843 return false;
7844 }
7845
7846 if (!MagicValues)
7847 return false;
7848
7849 llvm::DenseMap<Sema::TypeTagMagicValue,
7850 Sema::TypeTagData>::const_iterator I =
7851 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7852 if (I == MagicValues->end())
7853 return false;
7854
7855 TypeInfo = I->second;
7856 return true;
7857}
7858} // unnamed namespace
7859
7860void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7861 uint64_t MagicValue, QualType Type,
7862 bool LayoutCompatible,
7863 bool MustBeNull) {
7864 if (!TypeTagForDatatypeMagicValues)
7865 TypeTagForDatatypeMagicValues.reset(
7866 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7867
7868 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7869 (*TypeTagForDatatypeMagicValues)[Magic] =
7870 TypeTagData(Type, LayoutCompatible, MustBeNull);
7871}
7872
7873namespace {
7874bool IsSameCharType(QualType T1, QualType T2) {
7875 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7876 if (!BT1)
7877 return false;
7878
7879 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7880 if (!BT2)
7881 return false;
7882
7883 BuiltinType::Kind T1Kind = BT1->getKind();
7884 BuiltinType::Kind T2Kind = BT2->getKind();
7885
7886 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7887 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7888 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7889 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7890}
7891} // unnamed namespace
7892
7893void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7894 const Expr * const *ExprArgs) {
7895 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7896 bool IsPointerAttr = Attr->getIsPointer();
7897
7898 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7899 bool FoundWrongKind;
7900 TypeTagData TypeInfo;
7901 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7902 TypeTagForDatatypeMagicValues.get(),
7903 FoundWrongKind, TypeInfo)) {
7904 if (FoundWrongKind)
7905 Diag(TypeTagExpr->getExprLoc(),
7906 diag::warn_type_tag_for_datatype_wrong_kind)
7907 << TypeTagExpr->getSourceRange();
7908 return;
7909 }
7910
7911 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7912 if (IsPointerAttr) {
7913 // Skip implicit cast of pointer to `void *' (as a function argument).
7914 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007915 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007916 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007917 ArgumentExpr = ICE->getSubExpr();
7918 }
7919 QualType ArgumentType = ArgumentExpr->getType();
7920
7921 // Passing a `void*' pointer shouldn't trigger a warning.
7922 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7923 return;
7924
7925 if (TypeInfo.MustBeNull) {
7926 // Type tag with matching void type requires a null pointer.
7927 if (!ArgumentExpr->isNullPointerConstant(Context,
7928 Expr::NPC_ValueDependentIsNotNull)) {
7929 Diag(ArgumentExpr->getExprLoc(),
7930 diag::warn_type_safety_null_pointer_required)
7931 << ArgumentKind->getName()
7932 << ArgumentExpr->getSourceRange()
7933 << TypeTagExpr->getSourceRange();
7934 }
7935 return;
7936 }
7937
7938 QualType RequiredType = TypeInfo.Type;
7939 if (IsPointerAttr)
7940 RequiredType = Context.getPointerType(RequiredType);
7941
7942 bool mismatch = false;
7943 if (!TypeInfo.LayoutCompatible) {
7944 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7945
7946 // C++11 [basic.fundamental] p1:
7947 // Plain char, signed char, and unsigned char are three distinct types.
7948 //
7949 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7950 // char' depending on the current char signedness mode.
7951 if (mismatch)
7952 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7953 RequiredType->getPointeeType())) ||
7954 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7955 mismatch = false;
7956 } else
7957 if (IsPointerAttr)
7958 mismatch = !isLayoutCompatible(Context,
7959 ArgumentType->getPointeeType(),
7960 RequiredType->getPointeeType());
7961 else
7962 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7963
7964 if (mismatch)
7965 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007966 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007967 << TypeInfo.LayoutCompatible << RequiredType
7968 << ArgumentExpr->getSourceRange()
7969 << TypeTagExpr->getSourceRange();
7970}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007971