blob: 93c5cac6b0431dda97c5f8ac0fa94986b89ad7a6 [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:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000306 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000307 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000308 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000309 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
310 return ExprError();
311 break;
Tim Northovera2ee4332014-03-29 15:09:45 +0000312 case llvm::Triple::arm64:
313 if (CheckARM64BuiltinFunctionCall(BuiltinID, TheCall))
314 return ExprError();
315 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000316 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +0000317 case llvm::Triple::aarch64_be:
Tim Northover2fe823a2013-08-01 09:23:19 +0000318 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
319 return ExprError();
320 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000321 case llvm::Triple::mips:
322 case llvm::Triple::mipsel:
323 case llvm::Triple::mips64:
324 case llvm::Triple::mips64el:
325 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
326 return ExprError();
327 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000328 case llvm::Triple::x86:
329 case llvm::Triple::x86_64:
330 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
331 return ExprError();
332 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000333 default:
334 break;
335 }
336 }
337
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000338 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000339}
340
Nate Begeman91e1fea2010-06-14 05:21:25 +0000341// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000342static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000344 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000345 switch (Type.getEltType()) {
346 case NeonTypeFlags::Int8:
347 case NeonTypeFlags::Poly8:
348 return shift ? 7 : (8 << IsQuad) - 1;
349 case NeonTypeFlags::Int16:
350 case NeonTypeFlags::Poly16:
351 return shift ? 15 : (4 << IsQuad) - 1;
352 case NeonTypeFlags::Int32:
353 return shift ? 31 : (2 << IsQuad) - 1;
354 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000355 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000356 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000357 case NeonTypeFlags::Poly128:
358 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000359 case NeonTypeFlags::Float16:
360 assert(!shift && "cannot shift float types!");
361 return (4 << IsQuad) - 1;
362 case NeonTypeFlags::Float32:
363 assert(!shift && "cannot shift float types!");
364 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000365 case NeonTypeFlags::Float64:
366 assert(!shift && "cannot shift float types!");
367 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000368 }
David Blaikie8a40f702012-01-17 06:56:22 +0000369 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000370}
371
Bob Wilsone4d77232011-11-08 05:04:11 +0000372/// getNeonEltType - Return the QualType corresponding to the elements of
373/// the vector type specified by the NeonTypeFlags. This is used to check
374/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000375static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000376 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000377 switch (Flags.getEltType()) {
378 case NeonTypeFlags::Int8:
379 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
380 case NeonTypeFlags::Int16:
381 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
382 case NeonTypeFlags::Int32:
383 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
384 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000385 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000386 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
387 else
388 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
389 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000390 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000391 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000392 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000393 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000394 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000395 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000396 case NeonTypeFlags::Poly128:
397 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000398 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000399 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000400 case NeonTypeFlags::Float32:
401 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000402 case NeonTypeFlags::Float64:
403 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000404 }
David Blaikie8a40f702012-01-17 06:56:22 +0000405 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000406}
407
Tim Northover12670412014-02-19 10:37:05 +0000408bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000409 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000410 uint64_t mask = 0;
411 unsigned TV = 0;
412 int PtrArgNum = -1;
413 bool HasConstPtr = false;
414 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000415#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000416#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000417#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000418 }
419
420 // For NEON intrinsics which are overloaded on vector element type, validate
421 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000422 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000423 if (mask) {
424 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
425 return true;
426
427 TV = Result.getLimitedValue(64);
428 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
429 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000430 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000431 }
432
433 if (PtrArgNum >= 0) {
434 // Check that pointer arguments have the specified type.
435 Expr *Arg = TheCall->getArg(PtrArgNum);
436 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
437 Arg = ICE->getSubExpr();
438 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
439 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000440
Tim Northovera2ee4332014-03-29 15:09:45 +0000441 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
442 bool IsPolyUnsigned =
443 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
444 bool IsInt64Long =
445 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
446 QualType EltTy =
447 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000448 if (HasConstPtr)
449 EltTy = EltTy.withConst();
450 QualType LHSTy = Context.getPointerType(EltTy);
451 AssignConvertType ConvTy;
452 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
453 if (RHS.isInvalid())
454 return true;
455 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
456 RHS.get(), AA_Assigning))
457 return true;
458 }
459
460 // For NEON intrinsics which take an immediate value as part of the
461 // instruction, range check them here.
462 unsigned i = 0, l = 0, u = 0;
463 switch (BuiltinID) {
464 default:
465 return false;
Tim Northover12670412014-02-19 10:37:05 +0000466#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000467#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000468#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000469 }
470 ;
471
472 // We can't check the value of a dependent argument.
473 if (TheCall->getArg(i)->isTypeDependent() ||
474 TheCall->getArg(i)->isValueDependent())
475 return false;
476
477 // Check that the immediate argument is actually a constant.
478 if (SemaBuiltinConstantArg(TheCall, i, Result))
479 return true;
480
481 // Range check against the upper/lower values for this isntruction.
482 unsigned Val = Result.getZExtValue();
483 if (Val < l || Val > (u + l))
484 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
485 << l << u + l << TheCall->getArg(i)->getSourceRange();
486
487 return false;
488}
489
Tim Northover12670412014-02-19 10:37:05 +0000490bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
491 CallExpr *TheCall) {
492 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
493 return true;
494
495 return false;
496}
497
Tim Northovera2ee4332014-03-29 15:09:45 +0000498bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
499 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000500 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000501 BuiltinID == ARM::BI__builtin_arm_strex ||
502 BuiltinID == ARM64::BI__builtin_arm_ldrex ||
503 BuiltinID == ARM64::BI__builtin_arm_strex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000504 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000505 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
506 BuiltinID == ARM64::BI__builtin_arm_ldrex;
Tim Northover6aacd492013-07-16 09:47:53 +0000507
508 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
509
510 // Ensure that we have the proper number of arguments.
511 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
512 return true;
513
514 // Inspect the pointer argument of the atomic builtin. This should always be
515 // a pointer type, whose element is an integral scalar or pointer type.
516 // Because it is a pointer type, we don't have to worry about any implicit
517 // casts here.
518 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
519 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
520 if (PointerArgRes.isInvalid())
521 return true;
522 PointerArg = PointerArgRes.take();
523
524 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
525 if (!pointerType) {
526 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
527 << PointerArg->getType() << PointerArg->getSourceRange();
528 return true;
529 }
530
531 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
532 // task is to insert the appropriate casts into the AST. First work out just
533 // what the appropriate type is.
534 QualType ValType = pointerType->getPointeeType();
535 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
536 if (IsLdrex)
537 AddrType.addConst();
538
539 // Issue a warning if the cast is dodgy.
540 CastKind CastNeeded = CK_NoOp;
541 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
542 CastNeeded = CK_BitCast;
543 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
544 << PointerArg->getType()
545 << Context.getPointerType(AddrType)
546 << AA_Passing << PointerArg->getSourceRange();
547 }
548
549 // Finally, do the cast and replace the argument with the corrected version.
550 AddrType = Context.getPointerType(AddrType);
551 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
552 if (PointerArgRes.isInvalid())
553 return true;
554 PointerArg = PointerArgRes.take();
555
556 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
557
558 // In general, we allow ints, floats and pointers to be loaded and stored.
559 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
560 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
561 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
562 << PointerArg->getType() << PointerArg->getSourceRange();
563 return true;
564 }
565
566 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000567 if (Context.getTypeSize(ValType) > MaxWidth) {
568 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000569 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
570 << PointerArg->getType() << PointerArg->getSourceRange();
571 return true;
572 }
573
574 switch (ValType.getObjCLifetime()) {
575 case Qualifiers::OCL_None:
576 case Qualifiers::OCL_ExplicitNone:
577 // okay
578 break;
579
580 case Qualifiers::OCL_Weak:
581 case Qualifiers::OCL_Strong:
582 case Qualifiers::OCL_Autoreleasing:
583 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
584 << ValType << PointerArg->getSourceRange();
585 return true;
586 }
587
588
589 if (IsLdrex) {
590 TheCall->setType(ValType);
591 return false;
592 }
593
594 // Initialize the argument to be stored.
595 ExprResult ValArg = TheCall->getArg(0);
596 InitializedEntity Entity = InitializedEntity::InitializeParameter(
597 Context, ValType, /*consume*/ false);
598 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
599 if (ValArg.isInvalid())
600 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000601 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000602
603 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
604 // but the custom checker bypasses all default analysis.
605 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000606 return false;
607}
608
Nate Begeman4904e322010-06-08 02:47:44 +0000609bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000610 llvm::APSInt Result;
611
Tim Northover6aacd492013-07-16 09:47:53 +0000612 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
613 BuiltinID == ARM::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000614 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000615 }
616
Tim Northover12670412014-02-19 10:37:05 +0000617 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
618 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000619
Bob Wilsond836d3d2014-03-09 23:02:27 +0000620 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000621 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000622 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000623 switch (BuiltinID) {
624 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000625 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
626 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000627 case ARM::BI__builtin_arm_vcvtr_f:
628 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000629 case ARM::BI__builtin_arm_dmb:
630 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000631 };
632
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000633 // We can't check the value of a dependent argument.
634 if (TheCall->getArg(i)->isTypeDependent() ||
635 TheCall->getArg(i)->isValueDependent())
636 return false;
637
Nate Begeman91e1fea2010-06-14 05:21:25 +0000638 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000639 if (SemaBuiltinConstantArg(TheCall, i, Result))
640 return true;
641
Nate Begeman91e1fea2010-06-14 05:21:25 +0000642 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000643 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000644 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000645 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000646 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000647
Nate Begemanf568b072010-08-03 21:32:34 +0000648 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000649 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000650}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000651
Tim Northovera2ee4332014-03-29 15:09:45 +0000652bool Sema::CheckARM64BuiltinFunctionCall(unsigned BuiltinID,
653 CallExpr *TheCall) {
654 llvm::APSInt Result;
655
656 if (BuiltinID == ARM64::BI__builtin_arm_ldrex ||
657 BuiltinID == ARM64::BI__builtin_arm_strex) {
658 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
659 }
660
661 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
662 return true;
663
664 return false;
665}
666
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000667bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
668 unsigned i = 0, l = 0, u = 0;
669 switch (BuiltinID) {
670 default: return false;
671 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
672 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000673 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
674 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
675 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
676 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
677 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000678 };
679
680 // We can't check the value of a dependent argument.
681 if (TheCall->getArg(i)->isTypeDependent() ||
682 TheCall->getArg(i)->isValueDependent())
683 return false;
684
685 // Check that the immediate argument is actually a constant.
686 llvm::APSInt Result;
687 if (SemaBuiltinConstantArg(TheCall, i, Result))
688 return true;
689
690 // Range check against the upper/lower values for this instruction.
691 unsigned Val = Result.getZExtValue();
692 if (Val < l || Val > u)
693 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
694 << l << u << TheCall->getArg(i)->getSourceRange();
695
696 return false;
697}
698
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000699bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
700 switch (BuiltinID) {
701 case X86::BI_mm_prefetch:
702 return SemaBuiltinMMPrefetch(TheCall);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000703 }
704 return false;
705}
706
Richard Smith55ce3522012-06-25 20:30:08 +0000707/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
708/// parameter with the FormatAttr's correct format_idx and firstDataArg.
709/// Returns true when the format fits the function and the FormatStringInfo has
710/// been populated.
711bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
712 FormatStringInfo *FSI) {
713 FSI->HasVAListArg = Format->getFirstArg() == 0;
714 FSI->FormatIdx = Format->getFormatIdx() - 1;
715 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000716
Richard Smith55ce3522012-06-25 20:30:08 +0000717 // The way the format attribute works in GCC, the implicit this argument
718 // of member functions is counted. However, it doesn't appear in our own
719 // lists, so decrement format_idx in that case.
720 if (IsCXXMember) {
721 if(FSI->FormatIdx == 0)
722 return false;
723 --FSI->FormatIdx;
724 if (FSI->FirstDataArg != 0)
725 --FSI->FirstDataArg;
726 }
727 return true;
728}
Mike Stump11289f42009-09-09 15:08:12 +0000729
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000730/// Checks if a the given expression evaluates to null.
731///
732/// \brief Returns true if the value evaluates to null.
733static bool CheckNonNullExpr(Sema &S,
734 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000735 // As a special case, transparent unions initialized with zero are
736 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000737 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000738 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
739 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000740 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000741 if (const InitListExpr *ILE =
742 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000743 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000744 }
745
746 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000747 return (!Expr->isValueDependent() &&
748 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
749 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000750}
751
752static void CheckNonNullArgument(Sema &S,
753 const Expr *ArgExpr,
754 SourceLocation CallSiteLoc) {
755 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000756 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
757}
758
Ted Kremenek2bc73332014-01-17 06:24:43 +0000759static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000760 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000761 const Expr * const *ExprArgs,
762 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000763 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000764 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000765 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
766 e = NonNull->args_end();
767 i != e; ++i) {
768 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000769 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000770 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000771
772 // Check the attributes on the parameters.
773 ArrayRef<ParmVarDecl*> parms;
774 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
775 parms = FD->parameters();
776 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
777 parms = MD->parameters();
778
779 unsigned argIndex = 0;
780 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
781 I != E; ++I, ++argIndex) {
782 const ParmVarDecl *PVD = *I;
783 if (PVD->hasAttr<NonNullAttr>())
784 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
785 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000786}
787
Richard Smith55ce3522012-06-25 20:30:08 +0000788/// Handles the checks for format strings, non-POD arguments to vararg
789/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000790void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
791 unsigned NumParams, bool IsMemberFunction,
792 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000793 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000794 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000795 if (CurContext->isDependentContext())
796 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000797
Ted Kremenekb8176da2010-09-09 04:33:05 +0000798 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000799 llvm::SmallBitVector CheckedVarArgs;
800 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000801 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000802 // Only create vector if there are format attributes.
803 CheckedVarArgs.resize(Args.size());
804
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000805 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000806 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000807 }
Richard Smithd7293d72013-08-05 18:49:43 +0000808 }
Richard Smith55ce3522012-06-25 20:30:08 +0000809
810 // Refuse POD arguments that weren't caught by the format string
811 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000812 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000813 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000814 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000815 if (const Expr *Arg = Args[ArgIdx]) {
816 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
817 checkVariadicArgument(Arg, CallType);
818 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000819 }
Richard Smithd7293d72013-08-05 18:49:43 +0000820 }
Mike Stump11289f42009-09-09 15:08:12 +0000821
Richard Trieu41bc0992013-06-22 00:20:41 +0000822 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000823 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000824
Richard Trieu41bc0992013-06-22 00:20:41 +0000825 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000826 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
827 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000828 }
Richard Smith55ce3522012-06-25 20:30:08 +0000829}
830
831/// CheckConstructorCall - Check a constructor call for correctness and safety
832/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000833void Sema::CheckConstructorCall(FunctionDecl *FDecl,
834 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000835 const FunctionProtoType *Proto,
836 SourceLocation Loc) {
837 VariadicCallType CallType =
838 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000839 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000840 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
841}
842
843/// CheckFunctionCall - Check a direct function call for various correctness
844/// and safety properties not strictly enforced by the C type system.
845bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
846 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000847 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
848 isa<CXXMethodDecl>(FDecl);
849 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
850 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000851 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
852 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000853 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000854 Expr** Args = TheCall->getArgs();
855 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000856 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000857 // If this is a call to a member operator, hide the first argument
858 // from checkCall.
859 // FIXME: Our choice of AST representation here is less than ideal.
860 ++Args;
861 --NumArgs;
862 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000863 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000864 IsMemberFunction, TheCall->getRParenLoc(),
865 TheCall->getCallee()->getSourceRange(), CallType);
866
867 IdentifierInfo *FnInfo = FDecl->getIdentifier();
868 // None of the checks below are needed for functions that don't have
869 // simple names (e.g., C++ conversion functions).
870 if (!FnInfo)
871 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000872
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000873 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
874
Anna Zaks22122702012-01-17 00:37:07 +0000875 unsigned CMId = FDecl->getMemoryFunctionKind();
876 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000877 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000878
Anna Zaks201d4892012-01-13 21:52:01 +0000879 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000880 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000881 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000882 else if (CMId == Builtin::BIstrncat)
883 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000884 else
Anna Zaks22122702012-01-17 00:37:07 +0000885 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000886
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000887 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000888}
889
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000890bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000891 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000892 VariadicCallType CallType =
893 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000894
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000895 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000896 /*IsMemberFunction=*/false,
897 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000898
899 return false;
900}
901
Richard Trieu664c4c62013-06-20 21:03:13 +0000902bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
903 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000904 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
905 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000906 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000908 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000909 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000910 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000911
Richard Trieu664c4c62013-06-20 21:03:13 +0000912 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000913 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000914 CallType = VariadicDoesNotApply;
915 } else if (Ty->isBlockPointerType()) {
916 CallType = VariadicBlock;
917 } else { // Ty->isFunctionPointerType()
918 CallType = VariadicFunction;
919 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000920 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000921
Alp Toker9cacbab2014-01-20 20:26:09 +0000922 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
923 TheCall->getNumArgs()),
924 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000925 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000926
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000927 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000928}
929
Richard Trieu41bc0992013-06-22 00:20:41 +0000930/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
931/// such as function pointers returned from functions.
932bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
933 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
934 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000935 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000936
Alp Toker9cacbab2014-01-20 20:26:09 +0000937 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
938 TheCall->getArgs(), TheCall->getNumArgs()),
939 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000940 TheCall->getCallee()->getSourceRange(), CallType);
941
942 return false;
943}
944
Tim Northovere94a34c2014-03-11 10:49:14 +0000945static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
946 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
947 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
948 return false;
949
950 switch (Op) {
951 case AtomicExpr::AO__c11_atomic_init:
952 llvm_unreachable("There is no ordering argument for an init");
953
954 case AtomicExpr::AO__c11_atomic_load:
955 case AtomicExpr::AO__atomic_load_n:
956 case AtomicExpr::AO__atomic_load:
957 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
958 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
959
960 case AtomicExpr::AO__c11_atomic_store:
961 case AtomicExpr::AO__atomic_store:
962 case AtomicExpr::AO__atomic_store_n:
963 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
964 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
965 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
966
967 default:
968 return true;
969 }
970}
971
Richard Smithfeea8832012-04-12 05:08:17 +0000972ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
973 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000974 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
975 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000976
Richard Smithfeea8832012-04-12 05:08:17 +0000977 // All these operations take one of the following forms:
978 enum {
979 // C __c11_atomic_init(A *, C)
980 Init,
981 // C __c11_atomic_load(A *, int)
982 Load,
983 // void __atomic_load(A *, CP, int)
984 Copy,
985 // C __c11_atomic_add(A *, M, int)
986 Arithmetic,
987 // C __atomic_exchange_n(A *, CP, int)
988 Xchg,
989 // void __atomic_exchange(A *, C *, CP, int)
990 GNUXchg,
991 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
992 C11CmpXchg,
993 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
994 GNUCmpXchg
995 } Form = Init;
996 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
997 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
998 // where:
999 // C is an appropriate type,
1000 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1001 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1002 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1003 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001004
Richard Smithfeea8832012-04-12 05:08:17 +00001005 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1006 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1007 && "need to update code for modified C11 atomics");
1008 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1009 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1010 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1011 Op == AtomicExpr::AO__atomic_store_n ||
1012 Op == AtomicExpr::AO__atomic_exchange_n ||
1013 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1014 bool IsAddSub = false;
1015
1016 switch (Op) {
1017 case AtomicExpr::AO__c11_atomic_init:
1018 Form = Init;
1019 break;
1020
1021 case AtomicExpr::AO__c11_atomic_load:
1022 case AtomicExpr::AO__atomic_load_n:
1023 Form = Load;
1024 break;
1025
1026 case AtomicExpr::AO__c11_atomic_store:
1027 case AtomicExpr::AO__atomic_load:
1028 case AtomicExpr::AO__atomic_store:
1029 case AtomicExpr::AO__atomic_store_n:
1030 Form = Copy;
1031 break;
1032
1033 case AtomicExpr::AO__c11_atomic_fetch_add:
1034 case AtomicExpr::AO__c11_atomic_fetch_sub:
1035 case AtomicExpr::AO__atomic_fetch_add:
1036 case AtomicExpr::AO__atomic_fetch_sub:
1037 case AtomicExpr::AO__atomic_add_fetch:
1038 case AtomicExpr::AO__atomic_sub_fetch:
1039 IsAddSub = true;
1040 // Fall through.
1041 case AtomicExpr::AO__c11_atomic_fetch_and:
1042 case AtomicExpr::AO__c11_atomic_fetch_or:
1043 case AtomicExpr::AO__c11_atomic_fetch_xor:
1044 case AtomicExpr::AO__atomic_fetch_and:
1045 case AtomicExpr::AO__atomic_fetch_or:
1046 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001047 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001048 case AtomicExpr::AO__atomic_and_fetch:
1049 case AtomicExpr::AO__atomic_or_fetch:
1050 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001051 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001052 Form = Arithmetic;
1053 break;
1054
1055 case AtomicExpr::AO__c11_atomic_exchange:
1056 case AtomicExpr::AO__atomic_exchange_n:
1057 Form = Xchg;
1058 break;
1059
1060 case AtomicExpr::AO__atomic_exchange:
1061 Form = GNUXchg;
1062 break;
1063
1064 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1065 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1066 Form = C11CmpXchg;
1067 break;
1068
1069 case AtomicExpr::AO__atomic_compare_exchange:
1070 case AtomicExpr::AO__atomic_compare_exchange_n:
1071 Form = GNUCmpXchg;
1072 break;
1073 }
1074
1075 // Check we have the right number of arguments.
1076 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001077 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001078 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001079 << TheCall->getCallee()->getSourceRange();
1080 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001081 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1082 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001083 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001084 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001085 << TheCall->getCallee()->getSourceRange();
1086 return ExprError();
1087 }
1088
Richard Smithfeea8832012-04-12 05:08:17 +00001089 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001090 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001091 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1092 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1093 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001094 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001095 << Ptr->getType() << Ptr->getSourceRange();
1096 return ExprError();
1097 }
1098
Richard Smithfeea8832012-04-12 05:08:17 +00001099 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1100 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1101 QualType ValType = AtomTy; // 'C'
1102 if (IsC11) {
1103 if (!AtomTy->isAtomicType()) {
1104 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1105 << Ptr->getType() << Ptr->getSourceRange();
1106 return ExprError();
1107 }
Richard Smithe00921a2012-09-15 06:09:58 +00001108 if (AtomTy.isConstQualified()) {
1109 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1110 << Ptr->getType() << Ptr->getSourceRange();
1111 return ExprError();
1112 }
Richard Smithfeea8832012-04-12 05:08:17 +00001113 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001115
Richard Smithfeea8832012-04-12 05:08:17 +00001116 // For an arithmetic operation, the implied arithmetic must be well-formed.
1117 if (Form == Arithmetic) {
1118 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1119 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1120 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1121 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1122 return ExprError();
1123 }
1124 if (!IsAddSub && !ValType->isIntegerType()) {
1125 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1126 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1127 return ExprError();
1128 }
1129 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1130 // For __atomic_*_n operations, the value type must be a scalar integral or
1131 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001132 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001133 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1134 return ExprError();
1135 }
1136
Eli Friedmanaa769812013-09-11 03:49:34 +00001137 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1138 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001139 // For GNU atomics, require a trivially-copyable type. This is not part of
1140 // the GNU atomics specification, but we enforce it for sanity.
1141 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001142 << Ptr->getType() << Ptr->getSourceRange();
1143 return ExprError();
1144 }
1145
Richard Smithfeea8832012-04-12 05:08:17 +00001146 // FIXME: For any builtin other than a load, the ValType must not be
1147 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001148
1149 switch (ValType.getObjCLifetime()) {
1150 case Qualifiers::OCL_None:
1151 case Qualifiers::OCL_ExplicitNone:
1152 // okay
1153 break;
1154
1155 case Qualifiers::OCL_Weak:
1156 case Qualifiers::OCL_Strong:
1157 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001158 // FIXME: Can this happen? By this point, ValType should be known
1159 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001160 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1161 << ValType << Ptr->getSourceRange();
1162 return ExprError();
1163 }
1164
1165 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001166 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001167 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001168 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001169 ResultType = Context.BoolTy;
1170
Richard Smithfeea8832012-04-12 05:08:17 +00001171 // The type of a parameter passed 'by value'. In the GNU atomics, such
1172 // arguments are actually passed as pointers.
1173 QualType ByValType = ValType; // 'CP'
1174 if (!IsC11 && !IsN)
1175 ByValType = Ptr->getType();
1176
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001177 // The first argument --- the pointer --- has a fixed type; we
1178 // deduce the types of the rest of the arguments accordingly. Walk
1179 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001180 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001181 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001182 if (i < NumVals[Form] + 1) {
1183 switch (i) {
1184 case 1:
1185 // The second argument is the non-atomic operand. For arithmetic, this
1186 // is always passed by value, and for a compare_exchange it is always
1187 // passed by address. For the rest, GNU uses by-address and C11 uses
1188 // by-value.
1189 assert(Form != Load);
1190 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1191 Ty = ValType;
1192 else if (Form == Copy || Form == Xchg)
1193 Ty = ByValType;
1194 else if (Form == Arithmetic)
1195 Ty = Context.getPointerDiffType();
1196 else
1197 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1198 break;
1199 case 2:
1200 // The third argument to compare_exchange / GNU exchange is a
1201 // (pointer to a) desired value.
1202 Ty = ByValType;
1203 break;
1204 case 3:
1205 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1206 Ty = Context.BoolTy;
1207 break;
1208 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001209 } else {
1210 // The order(s) are always converted to int.
1211 Ty = Context.IntTy;
1212 }
Richard Smithfeea8832012-04-12 05:08:17 +00001213
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001214 InitializedEntity Entity =
1215 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001216 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001217 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1218 if (Arg.isInvalid())
1219 return true;
1220 TheCall->setArg(i, Arg.get());
1221 }
1222
Richard Smithfeea8832012-04-12 05:08:17 +00001223 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001224 SmallVector<Expr*, 5> SubExprs;
1225 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001226 switch (Form) {
1227 case Init:
1228 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001229 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001230 break;
1231 case Load:
1232 SubExprs.push_back(TheCall->getArg(1)); // Order
1233 break;
1234 case Copy:
1235 case Arithmetic:
1236 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001237 SubExprs.push_back(TheCall->getArg(2)); // Order
1238 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001239 break;
1240 case GNUXchg:
1241 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1242 SubExprs.push_back(TheCall->getArg(3)); // Order
1243 SubExprs.push_back(TheCall->getArg(1)); // Val1
1244 SubExprs.push_back(TheCall->getArg(2)); // Val2
1245 break;
1246 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001247 SubExprs.push_back(TheCall->getArg(3)); // Order
1248 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001249 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001250 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001251 break;
1252 case GNUCmpXchg:
1253 SubExprs.push_back(TheCall->getArg(4)); // Order
1254 SubExprs.push_back(TheCall->getArg(1)); // Val1
1255 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1256 SubExprs.push_back(TheCall->getArg(2)); // Val2
1257 SubExprs.push_back(TheCall->getArg(3)); // Weak
1258 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001259 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001260
1261 if (SubExprs.size() >= 2 && Form != Init) {
1262 llvm::APSInt Result(32);
1263 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1264 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001265 Diag(SubExprs[1]->getLocStart(),
1266 diag::warn_atomic_op_has_invalid_memory_order)
1267 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001268 }
1269
Fariborz Jahanian615de762013-05-28 17:37:39 +00001270 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1271 SubExprs, ResultType, Op,
1272 TheCall->getRParenLoc());
1273
1274 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1275 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1276 Context.AtomicUsesUnsupportedLibcall(AE))
1277 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1278 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001279
Fariborz Jahanian615de762013-05-28 17:37:39 +00001280 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001281}
1282
1283
John McCall29ad95b2011-08-27 01:09:30 +00001284/// checkBuiltinArgument - Given a call to a builtin function, perform
1285/// normal type-checking on the given argument, updating the call in
1286/// place. This is useful when a builtin function requires custom
1287/// type-checking for some of its arguments but not necessarily all of
1288/// them.
1289///
1290/// Returns true on error.
1291static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1292 FunctionDecl *Fn = E->getDirectCallee();
1293 assert(Fn && "builtin call without direct callee!");
1294
1295 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1296 InitializedEntity Entity =
1297 InitializedEntity::InitializeParameter(S.Context, Param);
1298
1299 ExprResult Arg = E->getArg(0);
1300 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1301 if (Arg.isInvalid())
1302 return true;
1303
1304 E->setArg(ArgIndex, Arg.take());
1305 return false;
1306}
1307
Chris Lattnerdc046542009-05-08 06:58:22 +00001308/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1309/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1310/// type of its first argument. The main ActOnCallExpr routines have already
1311/// promoted the types of arguments because all of these calls are prototyped as
1312/// void(...).
1313///
1314/// This function goes through and does final semantic checking for these
1315/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001316ExprResult
1317Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001318 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001319 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1320 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1321
1322 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001323 if (TheCall->getNumArgs() < 1) {
1324 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1325 << 0 << 1 << TheCall->getNumArgs()
1326 << TheCall->getCallee()->getSourceRange();
1327 return ExprError();
1328 }
Mike Stump11289f42009-09-09 15:08:12 +00001329
Chris Lattnerdc046542009-05-08 06:58:22 +00001330 // Inspect the first argument of the atomic builtin. This should always be
1331 // a pointer type, whose element is an integral scalar or pointer type.
1332 // Because it is a pointer type, we don't have to worry about any implicit
1333 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001334 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001335 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001336 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1337 if (FirstArgResult.isInvalid())
1338 return ExprError();
1339 FirstArg = FirstArgResult.take();
1340 TheCall->setArg(0, FirstArg);
1341
John McCall31168b02011-06-15 23:02:42 +00001342 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1343 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001344 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1345 << FirstArg->getType() << FirstArg->getSourceRange();
1346 return ExprError();
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
John McCall31168b02011-06-15 23:02:42 +00001349 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001350 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001351 !ValType->isBlockPointerType()) {
1352 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1353 << FirstArg->getType() << FirstArg->getSourceRange();
1354 return ExprError();
1355 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001356
John McCall31168b02011-06-15 23:02:42 +00001357 switch (ValType.getObjCLifetime()) {
1358 case Qualifiers::OCL_None:
1359 case Qualifiers::OCL_ExplicitNone:
1360 // okay
1361 break;
1362
1363 case Qualifiers::OCL_Weak:
1364 case Qualifiers::OCL_Strong:
1365 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001366 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001367 << ValType << FirstArg->getSourceRange();
1368 return ExprError();
1369 }
1370
John McCallb50451a2011-10-05 07:41:44 +00001371 // Strip any qualifiers off ValType.
1372 ValType = ValType.getUnqualifiedType();
1373
Chandler Carruth3973af72010-07-18 20:54:12 +00001374 // The majority of builtins return a value, but a few have special return
1375 // types, so allow them to override appropriately below.
1376 QualType ResultType = ValType;
1377
Chris Lattnerdc046542009-05-08 06:58:22 +00001378 // We need to figure out which concrete builtin this maps onto. For example,
1379 // __sync_fetch_and_add with a 2 byte object turns into
1380 // __sync_fetch_and_add_2.
1381#define BUILTIN_ROW(x) \
1382 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1383 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001384
Chris Lattnerdc046542009-05-08 06:58:22 +00001385 static const unsigned BuiltinIndices[][5] = {
1386 BUILTIN_ROW(__sync_fetch_and_add),
1387 BUILTIN_ROW(__sync_fetch_and_sub),
1388 BUILTIN_ROW(__sync_fetch_and_or),
1389 BUILTIN_ROW(__sync_fetch_and_and),
1390 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001391
Chris Lattnerdc046542009-05-08 06:58:22 +00001392 BUILTIN_ROW(__sync_add_and_fetch),
1393 BUILTIN_ROW(__sync_sub_and_fetch),
1394 BUILTIN_ROW(__sync_and_and_fetch),
1395 BUILTIN_ROW(__sync_or_and_fetch),
1396 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001397
Chris Lattnerdc046542009-05-08 06:58:22 +00001398 BUILTIN_ROW(__sync_val_compare_and_swap),
1399 BUILTIN_ROW(__sync_bool_compare_and_swap),
1400 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001401 BUILTIN_ROW(__sync_lock_release),
1402 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001403 };
Mike Stump11289f42009-09-09 15:08:12 +00001404#undef BUILTIN_ROW
1405
Chris Lattnerdc046542009-05-08 06:58:22 +00001406 // Determine the index of the size.
1407 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001408 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001409 case 1: SizeIndex = 0; break;
1410 case 2: SizeIndex = 1; break;
1411 case 4: SizeIndex = 2; break;
1412 case 8: SizeIndex = 3; break;
1413 case 16: SizeIndex = 4; break;
1414 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001415 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1416 << FirstArg->getType() << FirstArg->getSourceRange();
1417 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001418 }
Mike Stump11289f42009-09-09 15:08:12 +00001419
Chris Lattnerdc046542009-05-08 06:58:22 +00001420 // Each of these builtins has one pointer argument, followed by some number of
1421 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1422 // that we ignore. Find out which row of BuiltinIndices to read from as well
1423 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001424 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001425 unsigned BuiltinIndex, NumFixed = 1;
1426 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001427 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001428 case Builtin::BI__sync_fetch_and_add:
1429 case Builtin::BI__sync_fetch_and_add_1:
1430 case Builtin::BI__sync_fetch_and_add_2:
1431 case Builtin::BI__sync_fetch_and_add_4:
1432 case Builtin::BI__sync_fetch_and_add_8:
1433 case Builtin::BI__sync_fetch_and_add_16:
1434 BuiltinIndex = 0;
1435 break;
1436
1437 case Builtin::BI__sync_fetch_and_sub:
1438 case Builtin::BI__sync_fetch_and_sub_1:
1439 case Builtin::BI__sync_fetch_and_sub_2:
1440 case Builtin::BI__sync_fetch_and_sub_4:
1441 case Builtin::BI__sync_fetch_and_sub_8:
1442 case Builtin::BI__sync_fetch_and_sub_16:
1443 BuiltinIndex = 1;
1444 break;
1445
1446 case Builtin::BI__sync_fetch_and_or:
1447 case Builtin::BI__sync_fetch_and_or_1:
1448 case Builtin::BI__sync_fetch_and_or_2:
1449 case Builtin::BI__sync_fetch_and_or_4:
1450 case Builtin::BI__sync_fetch_and_or_8:
1451 case Builtin::BI__sync_fetch_and_or_16:
1452 BuiltinIndex = 2;
1453 break;
1454
1455 case Builtin::BI__sync_fetch_and_and:
1456 case Builtin::BI__sync_fetch_and_and_1:
1457 case Builtin::BI__sync_fetch_and_and_2:
1458 case Builtin::BI__sync_fetch_and_and_4:
1459 case Builtin::BI__sync_fetch_and_and_8:
1460 case Builtin::BI__sync_fetch_and_and_16:
1461 BuiltinIndex = 3;
1462 break;
Mike Stump11289f42009-09-09 15:08:12 +00001463
Douglas Gregor73722482011-11-28 16:30:08 +00001464 case Builtin::BI__sync_fetch_and_xor:
1465 case Builtin::BI__sync_fetch_and_xor_1:
1466 case Builtin::BI__sync_fetch_and_xor_2:
1467 case Builtin::BI__sync_fetch_and_xor_4:
1468 case Builtin::BI__sync_fetch_and_xor_8:
1469 case Builtin::BI__sync_fetch_and_xor_16:
1470 BuiltinIndex = 4;
1471 break;
1472
1473 case Builtin::BI__sync_add_and_fetch:
1474 case Builtin::BI__sync_add_and_fetch_1:
1475 case Builtin::BI__sync_add_and_fetch_2:
1476 case Builtin::BI__sync_add_and_fetch_4:
1477 case Builtin::BI__sync_add_and_fetch_8:
1478 case Builtin::BI__sync_add_and_fetch_16:
1479 BuiltinIndex = 5;
1480 break;
1481
1482 case Builtin::BI__sync_sub_and_fetch:
1483 case Builtin::BI__sync_sub_and_fetch_1:
1484 case Builtin::BI__sync_sub_and_fetch_2:
1485 case Builtin::BI__sync_sub_and_fetch_4:
1486 case Builtin::BI__sync_sub_and_fetch_8:
1487 case Builtin::BI__sync_sub_and_fetch_16:
1488 BuiltinIndex = 6;
1489 break;
1490
1491 case Builtin::BI__sync_and_and_fetch:
1492 case Builtin::BI__sync_and_and_fetch_1:
1493 case Builtin::BI__sync_and_and_fetch_2:
1494 case Builtin::BI__sync_and_and_fetch_4:
1495 case Builtin::BI__sync_and_and_fetch_8:
1496 case Builtin::BI__sync_and_and_fetch_16:
1497 BuiltinIndex = 7;
1498 break;
1499
1500 case Builtin::BI__sync_or_and_fetch:
1501 case Builtin::BI__sync_or_and_fetch_1:
1502 case Builtin::BI__sync_or_and_fetch_2:
1503 case Builtin::BI__sync_or_and_fetch_4:
1504 case Builtin::BI__sync_or_and_fetch_8:
1505 case Builtin::BI__sync_or_and_fetch_16:
1506 BuiltinIndex = 8;
1507 break;
1508
1509 case Builtin::BI__sync_xor_and_fetch:
1510 case Builtin::BI__sync_xor_and_fetch_1:
1511 case Builtin::BI__sync_xor_and_fetch_2:
1512 case Builtin::BI__sync_xor_and_fetch_4:
1513 case Builtin::BI__sync_xor_and_fetch_8:
1514 case Builtin::BI__sync_xor_and_fetch_16:
1515 BuiltinIndex = 9;
1516 break;
Mike Stump11289f42009-09-09 15:08:12 +00001517
Chris Lattnerdc046542009-05-08 06:58:22 +00001518 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001519 case Builtin::BI__sync_val_compare_and_swap_1:
1520 case Builtin::BI__sync_val_compare_and_swap_2:
1521 case Builtin::BI__sync_val_compare_and_swap_4:
1522 case Builtin::BI__sync_val_compare_and_swap_8:
1523 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001524 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001525 NumFixed = 2;
1526 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001527
Chris Lattnerdc046542009-05-08 06:58:22 +00001528 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001529 case Builtin::BI__sync_bool_compare_and_swap_1:
1530 case Builtin::BI__sync_bool_compare_and_swap_2:
1531 case Builtin::BI__sync_bool_compare_and_swap_4:
1532 case Builtin::BI__sync_bool_compare_and_swap_8:
1533 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001534 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001535 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001536 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001537 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001538
1539 case Builtin::BI__sync_lock_test_and_set:
1540 case Builtin::BI__sync_lock_test_and_set_1:
1541 case Builtin::BI__sync_lock_test_and_set_2:
1542 case Builtin::BI__sync_lock_test_and_set_4:
1543 case Builtin::BI__sync_lock_test_and_set_8:
1544 case Builtin::BI__sync_lock_test_and_set_16:
1545 BuiltinIndex = 12;
1546 break;
1547
Chris Lattnerdc046542009-05-08 06:58:22 +00001548 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001549 case Builtin::BI__sync_lock_release_1:
1550 case Builtin::BI__sync_lock_release_2:
1551 case Builtin::BI__sync_lock_release_4:
1552 case Builtin::BI__sync_lock_release_8:
1553 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001554 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001555 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001556 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001557 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001558
1559 case Builtin::BI__sync_swap:
1560 case Builtin::BI__sync_swap_1:
1561 case Builtin::BI__sync_swap_2:
1562 case Builtin::BI__sync_swap_4:
1563 case Builtin::BI__sync_swap_8:
1564 case Builtin::BI__sync_swap_16:
1565 BuiltinIndex = 14;
1566 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Chris Lattnerdc046542009-05-08 06:58:22 +00001569 // Now that we know how many fixed arguments we expect, first check that we
1570 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001571 if (TheCall->getNumArgs() < 1+NumFixed) {
1572 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1573 << 0 << 1+NumFixed << TheCall->getNumArgs()
1574 << TheCall->getCallee()->getSourceRange();
1575 return ExprError();
1576 }
Mike Stump11289f42009-09-09 15:08:12 +00001577
Chris Lattner5b9241b2009-05-08 15:36:58 +00001578 // Get the decl for the concrete builtin from this, we can tell what the
1579 // concrete integer type we should convert to is.
1580 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1581 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001582 FunctionDecl *NewBuiltinDecl;
1583 if (NewBuiltinID == BuiltinID)
1584 NewBuiltinDecl = FDecl;
1585 else {
1586 // Perform builtin lookup to avoid redeclaring it.
1587 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1588 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1589 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1590 assert(Res.getFoundDecl());
1591 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1592 if (NewBuiltinDecl == 0)
1593 return ExprError();
1594 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001595
John McCallcf142162010-08-07 06:22:56 +00001596 // The first argument --- the pointer --- has a fixed type; we
1597 // deduce the types of the rest of the arguments accordingly. Walk
1598 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001599 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001600 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001601
Chris Lattnerdc046542009-05-08 06:58:22 +00001602 // GCC does an implicit conversion to the pointer or integer ValType. This
1603 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001604 // Initialize the argument.
1605 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1606 ValType, /*consume*/ false);
1607 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001608 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001609 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001610
Chris Lattnerdc046542009-05-08 06:58:22 +00001611 // Okay, we have something that *can* be converted to the right type. Check
1612 // to see if there is a potentially weird extension going on here. This can
1613 // happen when you do an atomic operation on something like an char* and
1614 // pass in 42. The 42 gets converted to char. This is even more strange
1615 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001616 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001617 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001618 }
Mike Stump11289f42009-09-09 15:08:12 +00001619
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001620 ASTContext& Context = this->getASTContext();
1621
1622 // Create a new DeclRefExpr to refer to the new decl.
1623 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1624 Context,
1625 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001626 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001627 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001628 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001629 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001630 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001631 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001632
Chris Lattnerdc046542009-05-08 06:58:22 +00001633 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001634 // FIXME: This loses syntactic information.
1635 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1636 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1637 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001638 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001639
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001640 // Change the result type of the call to match the original value type. This
1641 // is arbitrary, but the codegen for these builtins ins design to handle it
1642 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001643 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001644
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001645 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001646}
1647
Chris Lattner6436fb62009-02-18 06:01:06 +00001648/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001649/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001650/// Note: It might also make sense to do the UTF-16 conversion here (would
1651/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001652bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001653 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001654 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1655
Douglas Gregorfb65e592011-07-27 05:40:30 +00001656 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001657 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1658 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001659 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001662 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001663 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001664 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001665 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001666 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001667 UTF16 *ToPtr = &ToBuf[0];
1668
1669 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1670 &ToPtr, ToPtr + NumBytes,
1671 strictConversion);
1672 // Check for conversion failure.
1673 if (Result != conversionOK)
1674 Diag(Arg->getLocStart(),
1675 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1676 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001677 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001678}
1679
Chris Lattnere202e6a2007-12-20 00:05:45 +00001680/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1681/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001682bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1683 Expr *Fn = TheCall->getCallee();
1684 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001685 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001686 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001687 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1688 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001689 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001690 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001691 return true;
1692 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001693
1694 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001695 return Diag(TheCall->getLocEnd(),
1696 diag::err_typecheck_call_too_few_args_at_least)
1697 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001698 }
1699
John McCall29ad95b2011-08-27 01:09:30 +00001700 // Type-check the first argument normally.
1701 if (checkBuiltinArgument(*this, TheCall, 0))
1702 return true;
1703
Chris Lattnere202e6a2007-12-20 00:05:45 +00001704 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001705 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001706 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001707 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001708 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001709 else if (FunctionDecl *FD = getCurFunctionDecl())
1710 isVariadic = FD->isVariadic();
1711 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001712 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnere202e6a2007-12-20 00:05:45 +00001714 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001715 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1716 return true;
1717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Chris Lattner43be2e62007-12-19 23:59:04 +00001719 // Verify that the second argument to the builtin is the last argument of the
1720 // current function or method.
1721 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001722 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001723
Nico Weber9eea7642013-05-24 23:31:57 +00001724 // These are valid if SecondArgIsLastNamedArgument is false after the next
1725 // block.
1726 QualType Type;
1727 SourceLocation ParamLoc;
1728
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001729 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1730 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001731 // FIXME: This isn't correct for methods (results in bogus warning).
1732 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001733 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001734 if (CurBlock)
1735 LastArg = *(CurBlock->TheDecl->param_end()-1);
1736 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001737 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001738 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001739 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001740 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001741
1742 Type = PV->getType();
1743 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001744 }
1745 }
Mike Stump11289f42009-09-09 15:08:12 +00001746
Chris Lattner43be2e62007-12-19 23:59:04 +00001747 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001748 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001749 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001750 else if (Type->isReferenceType()) {
1751 Diag(Arg->getLocStart(),
1752 diag::warn_va_start_of_reference_type_is_undefined);
1753 Diag(ParamLoc, diag::note_parameter_type) << Type;
1754 }
1755
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001756 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001757 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001758}
Chris Lattner43be2e62007-12-19 23:59:04 +00001759
Chris Lattner2da14fb2007-12-20 00:26:33 +00001760/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1761/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001762bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1763 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001764 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001765 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001766 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001767 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001768 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001769 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001770 << SourceRange(TheCall->getArg(2)->getLocStart(),
1771 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001772
John Wiegley01296292011-04-08 18:41:53 +00001773 ExprResult OrigArg0 = TheCall->getArg(0);
1774 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001775
Chris Lattner2da14fb2007-12-20 00:26:33 +00001776 // Do standard promotions between the two arguments, returning their common
1777 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001778 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001779 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1780 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001781
1782 // Make sure any conversions are pushed back into the call; this is
1783 // type safe since unordered compare builtins are declared as "_Bool
1784 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001785 TheCall->setArg(0, OrigArg0.get());
1786 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001787
John Wiegley01296292011-04-08 18:41:53 +00001788 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001789 return false;
1790
Chris Lattner2da14fb2007-12-20 00:26:33 +00001791 // If the common type isn't a real floating type, then the arguments were
1792 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001793 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001794 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001795 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001796 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1797 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001798
Chris Lattner2da14fb2007-12-20 00:26:33 +00001799 return false;
1800}
1801
Benjamin Kramer634fc102010-02-15 22:42:31 +00001802/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1803/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001804/// to check everything. We expect the last argument to be a floating point
1805/// value.
1806bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1807 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001808 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001809 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001810 if (TheCall->getNumArgs() > NumArgs)
1811 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001812 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001813 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001814 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001815 (*(TheCall->arg_end()-1))->getLocEnd());
1816
Benjamin Kramer64aae502010-02-16 10:07:31 +00001817 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001818
Eli Friedman7e4faac2009-08-31 20:06:00 +00001819 if (OrigArg->isTypeDependent())
1820 return false;
1821
Chris Lattner68784ef2010-05-06 05:50:07 +00001822 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001823 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001824 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001825 diag::err_typecheck_call_invalid_unary_fp)
1826 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001827
Chris Lattner68784ef2010-05-06 05:50:07 +00001828 // If this is an implicit conversion from float -> double, remove it.
1829 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1830 Expr *CastArg = Cast->getSubExpr();
1831 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1832 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1833 "promotion from float to double is the only expected cast here");
1834 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001835 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001836 }
1837 }
1838
Eli Friedman7e4faac2009-08-31 20:06:00 +00001839 return false;
1840}
1841
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001842/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1843// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001844ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001845 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001846 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001847 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001848 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1849 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001850
Nate Begemana0110022010-06-08 00:16:34 +00001851 // Determine which of the following types of shufflevector we're checking:
1852 // 1) unary, vector mask: (lhs, mask)
1853 // 2) binary, vector mask: (lhs, rhs, mask)
1854 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1855 QualType resType = TheCall->getArg(0)->getType();
1856 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001857
Douglas Gregorc25f7662009-05-19 22:10:17 +00001858 if (!TheCall->getArg(0)->isTypeDependent() &&
1859 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001860 QualType LHSType = TheCall->getArg(0)->getType();
1861 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001862
Craig Topperbaca3892013-07-29 06:47:04 +00001863 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1864 return ExprError(Diag(TheCall->getLocStart(),
1865 diag::err_shufflevector_non_vector)
1866 << SourceRange(TheCall->getArg(0)->getLocStart(),
1867 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001868
Nate Begemana0110022010-06-08 00:16:34 +00001869 numElements = LHSType->getAs<VectorType>()->getNumElements();
1870 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001871
Nate Begemana0110022010-06-08 00:16:34 +00001872 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1873 // with mask. If so, verify that RHS is an integer vector type with the
1874 // same number of elts as lhs.
1875 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001876 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001877 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001878 return ExprError(Diag(TheCall->getLocStart(),
1879 diag::err_shufflevector_incompatible_vector)
1880 << SourceRange(TheCall->getArg(1)->getLocStart(),
1881 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001882 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001883 return ExprError(Diag(TheCall->getLocStart(),
1884 diag::err_shufflevector_incompatible_vector)
1885 << SourceRange(TheCall->getArg(0)->getLocStart(),
1886 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001887 } else if (numElements != numResElements) {
1888 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001889 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001890 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001891 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001892 }
1893
1894 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001895 if (TheCall->getArg(i)->isTypeDependent() ||
1896 TheCall->getArg(i)->isValueDependent())
1897 continue;
1898
Nate Begemana0110022010-06-08 00:16:34 +00001899 llvm::APSInt Result(32);
1900 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1901 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001902 diag::err_shufflevector_nonconstant_argument)
1903 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001904
Craig Topper50ad5b72013-08-03 17:40:38 +00001905 // Allow -1 which will be translated to undef in the IR.
1906 if (Result.isSigned() && Result.isAllOnesValue())
1907 continue;
1908
Chris Lattner7ab824e2008-08-10 02:05:13 +00001909 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001910 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001911 diag::err_shufflevector_argument_too_large)
1912 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001913 }
1914
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001915 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001916
Chris Lattner7ab824e2008-08-10 02:05:13 +00001917 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001918 exprs.push_back(TheCall->getArg(i));
1919 TheCall->setArg(i, 0);
1920 }
1921
Benjamin Kramerc215e762012-08-24 11:54:20 +00001922 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001923 TheCall->getCallee()->getLocStart(),
1924 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001925}
Chris Lattner43be2e62007-12-19 23:59:04 +00001926
Hal Finkelc4d7c822013-09-18 03:29:45 +00001927/// SemaConvertVectorExpr - Handle __builtin_convertvector
1928ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1929 SourceLocation BuiltinLoc,
1930 SourceLocation RParenLoc) {
1931 ExprValueKind VK = VK_RValue;
1932 ExprObjectKind OK = OK_Ordinary;
1933 QualType DstTy = TInfo->getType();
1934 QualType SrcTy = E->getType();
1935
1936 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1937 return ExprError(Diag(BuiltinLoc,
1938 diag::err_convertvector_non_vector)
1939 << E->getSourceRange());
1940 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1941 return ExprError(Diag(BuiltinLoc,
1942 diag::err_convertvector_non_vector_type));
1943
1944 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1945 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1946 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1947 if (SrcElts != DstElts)
1948 return ExprError(Diag(BuiltinLoc,
1949 diag::err_convertvector_incompatible_vector)
1950 << E->getSourceRange());
1951 }
1952
1953 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1954 BuiltinLoc, RParenLoc));
1955
1956}
1957
Daniel Dunbarb7257262008-07-21 22:59:13 +00001958/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1959// This is declared to take (const void*, ...) and can take two
1960// optional constant int args.
1961bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001962 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001963
Chris Lattner3b054132008-11-19 05:08:23 +00001964 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001965 return Diag(TheCall->getLocEnd(),
1966 diag::err_typecheck_call_too_many_args_at_most)
1967 << 0 /*function call*/ << 3 << NumArgs
1968 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001969
1970 // Argument 0 is checked for us and the remaining arguments must be
1971 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001972 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001973 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001974
1975 // We can't check the value of a dependent argument.
1976 if (Arg->isTypeDependent() || Arg->isValueDependent())
1977 continue;
1978
Eli Friedman5efba262009-12-04 00:30:06 +00001979 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001980 if (SemaBuiltinConstantArg(TheCall, i, Result))
1981 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Daniel Dunbarb7257262008-07-21 22:59:13 +00001983 // FIXME: gcc issues a warning and rewrites these to 0. These
1984 // seems especially odd for the third argument since the default
1985 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001986 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001987 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001988 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001989 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001990 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001991 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001992 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001993 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001994 }
1995 }
1996
Chris Lattner3b054132008-11-19 05:08:23 +00001997 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001998}
1999
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002000/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
2001// This is declared to take (const char*, int)
2002bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
2003 Expr *Arg = TheCall->getArg(1);
2004
2005 // We can't check the value of a dependent argument.
2006 if (Arg->isTypeDependent() || Arg->isValueDependent())
2007 return false;
2008
2009 llvm::APSInt Result;
2010 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2011 return true;
2012
2013 if (Result.getLimitedValue() > 3)
2014 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2015 << "0" << "3" << Arg->getSourceRange();
2016
2017 return false;
2018}
2019
Eric Christopher8d0c6212010-04-17 02:26:23 +00002020/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2021/// TheCall is a constant expression.
2022bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2023 llvm::APSInt &Result) {
2024 Expr *Arg = TheCall->getArg(ArgNum);
2025 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2026 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2027
2028 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2029
2030 if (!Arg->isIntegerConstantExpr(Result, Context))
2031 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002032 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002033
Chris Lattnerd545ad12009-09-23 06:06:36 +00002034 return false;
2035}
2036
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002037/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
2038/// int type). This simply type checks that type is one of the defined
2039/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00002040// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002041bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002042 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002043
2044 // We can't check the value of a dependent argument.
2045 if (TheCall->getArg(1)->isTypeDependent() ||
2046 TheCall->getArg(1)->isValueDependent())
2047 return false;
2048
Eric Christopher8d0c6212010-04-17 02:26:23 +00002049 // Check constant-ness first.
2050 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2051 return true;
2052
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002053 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002054 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00002055 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2056 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002057 }
2058
2059 return false;
2060}
2061
Eli Friedmanc97d0142009-05-03 06:04:26 +00002062/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002063/// This checks that val is a constant 1.
2064bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2065 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002066 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002067
Eric Christopher8d0c6212010-04-17 02:26:23 +00002068 // TODO: This is less than ideal. Overload this to take a value.
2069 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2070 return true;
2071
2072 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002073 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2074 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2075
2076 return false;
2077}
2078
Richard Smithd7293d72013-08-05 18:49:43 +00002079namespace {
2080enum StringLiteralCheckType {
2081 SLCT_NotALiteral,
2082 SLCT_UncheckedLiteral,
2083 SLCT_CheckedLiteral
2084};
2085}
2086
Richard Smith55ce3522012-06-25 20:30:08 +00002087// Determine if an expression is a string literal or constant string.
2088// If this function returns false on the arguments to a function expecting a
2089// format string, we will usually need to emit a warning.
2090// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002091static StringLiteralCheckType
2092checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2093 bool HasVAListArg, unsigned format_idx,
2094 unsigned firstDataArg, Sema::FormatStringType Type,
2095 Sema::VariadicCallType CallType, bool InFunctionCall,
2096 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002097 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002098 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002099 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002100
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002101 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002102
Richard Smithd7293d72013-08-05 18:49:43 +00002103 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002104 // Technically -Wformat-nonliteral does not warn about this case.
2105 // The behavior of printf and friends in this case is implementation
2106 // dependent. Ideally if the format string cannot be null then
2107 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002108 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002109
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002110 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002111 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002112 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002113 // The expression is a literal if both sub-expressions were, and it was
2114 // completely checked only if both sub-expressions were checked.
2115 const AbstractConditionalOperator *C =
2116 cast<AbstractConditionalOperator>(E);
2117 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002118 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002119 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002120 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002121 if (Left == SLCT_NotALiteral)
2122 return SLCT_NotALiteral;
2123 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002124 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002125 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002126 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002127 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002128 }
2129
2130 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002131 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2132 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002133 }
2134
John McCallc07a0c72011-02-17 10:25:35 +00002135 case Stmt::OpaqueValueExprClass:
2136 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2137 E = src;
2138 goto tryAgain;
2139 }
Richard Smith55ce3522012-06-25 20:30:08 +00002140 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002141
Ted Kremeneka8890832011-02-24 23:03:04 +00002142 case Stmt::PredefinedExprClass:
2143 // While __func__, etc., are technically not string literals, they
2144 // cannot contain format specifiers and thus are not a security
2145 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002146 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002147
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002148 case Stmt::DeclRefExprClass: {
2149 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002150
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002151 // As an exception, do not flag errors for variables binding to
2152 // const string literals.
2153 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2154 bool isConstant = false;
2155 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002156
Richard Smithd7293d72013-08-05 18:49:43 +00002157 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2158 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002159 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002160 isConstant = T.isConstant(S.Context) &&
2161 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002162 } else if (T->isObjCObjectPointerType()) {
2163 // In ObjC, there is usually no "const ObjectPointer" type,
2164 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002165 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002168 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002169 if (const Expr *Init = VD->getAnyInitializer()) {
2170 // Look through initializers like const char c[] = { "foo" }
2171 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2172 if (InitList->isStringLiteralInit())
2173 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2174 }
Richard Smithd7293d72013-08-05 18:49:43 +00002175 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002176 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002177 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002178 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002179 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002180 }
Mike Stump11289f42009-09-09 15:08:12 +00002181
Anders Carlssonb012ca92009-06-28 19:55:58 +00002182 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2183 // special check to see if the format string is a function parameter
2184 // of the function calling the printf function. If the function
2185 // has an attribute indicating it is a printf-like function, then we
2186 // should suppress warnings concerning non-literals being used in a call
2187 // to a vprintf function. For example:
2188 //
2189 // void
2190 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2191 // va_list ap;
2192 // va_start(ap, fmt);
2193 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2194 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002195 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002196 if (HasVAListArg) {
2197 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2198 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2199 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002200 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002201 // adjust for implicit parameter
2202 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2203 if (MD->isInstance())
2204 ++PVIndex;
2205 // We also check if the formats are compatible.
2206 // We can't pass a 'scanf' string to a 'printf' function.
2207 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002208 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002209 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002210 }
2211 }
2212 }
2213 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002214 }
Mike Stump11289f42009-09-09 15:08:12 +00002215
Richard Smith55ce3522012-06-25 20:30:08 +00002216 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002217 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002218
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002219 case Stmt::CallExprClass:
2220 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002221 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002222 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2223 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2224 unsigned ArgIndex = FA->getFormatIdx();
2225 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2226 if (MD->isInstance())
2227 --ArgIndex;
2228 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002229
Richard Smithd7293d72013-08-05 18:49:43 +00002230 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002231 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002232 Type, CallType, InFunctionCall,
2233 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002234 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2235 unsigned BuiltinID = FD->getBuiltinID();
2236 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2237 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2238 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002239 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002240 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002241 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002242 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002243 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002244 }
2245 }
Mike Stump11289f42009-09-09 15:08:12 +00002246
Richard Smith55ce3522012-06-25 20:30:08 +00002247 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002248 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002249 case Stmt::ObjCStringLiteralClass:
2250 case Stmt::StringLiteralClass: {
2251 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002252
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002253 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002254 StrE = ObjCFExpr->getString();
2255 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002256 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002257
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002258 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002259 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2260 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002261 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002262 }
Mike Stump11289f42009-09-09 15:08:12 +00002263
Richard Smith55ce3522012-06-25 20:30:08 +00002264 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002265 }
Mike Stump11289f42009-09-09 15:08:12 +00002266
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002267 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002268 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002269 }
2270}
2271
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002272Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002273 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002274 .Case("scanf", FST_Scanf)
2275 .Cases("printf", "printf0", FST_Printf)
2276 .Cases("NSString", "CFString", FST_NSString)
2277 .Case("strftime", FST_Strftime)
2278 .Case("strfmon", FST_Strfmon)
2279 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2280 .Default(FST_Unknown);
2281}
2282
Jordan Rose3e0ec582012-07-19 18:10:23 +00002283/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002284/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002285/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002286bool Sema::CheckFormatArguments(const FormatAttr *Format,
2287 ArrayRef<const Expr *> Args,
2288 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002289 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002290 SourceLocation Loc, SourceRange Range,
2291 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002292 FormatStringInfo FSI;
2293 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002294 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002295 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002296 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002297 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002298}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002299
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002300bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002301 bool HasVAListArg, unsigned format_idx,
2302 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002303 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002304 SourceLocation Loc, SourceRange Range,
2305 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002306 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002307 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002308 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002309 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002310 }
Mike Stump11289f42009-09-09 15:08:12 +00002311
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002312 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002313
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002314 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002315 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002316 // Dynamically generated format strings are difficult to
2317 // automatically vet at compile time. Requiring that format strings
2318 // are string literals: (1) permits the checking of format strings by
2319 // the compiler and thereby (2) can practically remove the source of
2320 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002321
Mike Stump11289f42009-09-09 15:08:12 +00002322 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002323 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002324 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002325 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002326 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002327 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2328 format_idx, firstDataArg, Type, CallType,
2329 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002330 if (CT != SLCT_NotALiteral)
2331 // Literal format string found, check done!
2332 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002333
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002334 // Strftime is particular as it always uses a single 'time' argument,
2335 // so it is safe to pass a non-literal string.
2336 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002337 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002338
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002339 // Do not emit diag when the string param is a macro expansion and the
2340 // format is either NSString or CFString. This is a hack to prevent
2341 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2342 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002343 if (Type == FST_NSString &&
2344 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002345 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002346
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002347 // If there are no arguments specified, warn with -Wformat-security, otherwise
2348 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002349 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002350 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002351 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002352 << OrigFormatExpr->getSourceRange();
2353 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002354 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002355 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002356 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002357 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002358}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002359
Ted Kremenekab278de2010-01-28 23:39:18 +00002360namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002361class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2362protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002363 Sema &S;
2364 const StringLiteral *FExpr;
2365 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002366 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002367 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002368 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002369 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002370 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002371 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002372 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002373 bool usesPositionalArgs;
2374 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002375 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002376 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002377 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002378public:
Ted Kremenek02087932010-07-16 02:11:22 +00002379 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002380 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002381 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002382 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002383 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002384 Sema::VariadicCallType callType,
2385 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002386 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002387 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2388 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002389 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002390 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002391 inFunctionCall(inFunctionCall), CallType(callType),
2392 CheckedVarArgs(CheckedVarArgs) {
2393 CoveredArgs.resize(numDataArgs);
2394 CoveredArgs.reset();
2395 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002396
Ted Kremenek019d2242010-01-29 01:50:07 +00002397 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002398
Ted Kremenek02087932010-07-16 02:11:22 +00002399 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002400 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002401
Jordan Rose92303592012-09-08 04:00:03 +00002402 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002403 const analyze_format_string::FormatSpecifier &FS,
2404 const analyze_format_string::ConversionSpecifier &CS,
2405 const char *startSpecifier, unsigned specifierLen,
2406 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002407
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002408 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002409 const analyze_format_string::FormatSpecifier &FS,
2410 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002411
2412 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002413 const analyze_format_string::ConversionSpecifier &CS,
2414 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002415
Craig Toppere14c0f82014-03-12 04:55:44 +00002416 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002417
Craig Toppere14c0f82014-03-12 04:55:44 +00002418 void HandleInvalidPosition(const char *startSpecifier,
2419 unsigned specifierLen,
2420 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002421
Craig Toppere14c0f82014-03-12 04:55:44 +00002422 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002423
Craig Toppere14c0f82014-03-12 04:55:44 +00002424 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002425
Richard Trieu03cf7b72011-10-28 00:41:25 +00002426 template <typename Range>
2427 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2428 const Expr *ArgumentExpr,
2429 PartialDiagnostic PDiag,
2430 SourceLocation StringLoc,
2431 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002432 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002433
Ted Kremenek02087932010-07-16 02:11:22 +00002434protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002435 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2436 const char *startSpec,
2437 unsigned specifierLen,
2438 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002439
2440 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2441 const char *startSpec,
2442 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002443
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002444 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002445 CharSourceRange getSpecifierRange(const char *startSpecifier,
2446 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002447 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002448
Ted Kremenek5739de72010-01-29 01:06:55 +00002449 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002450
2451 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2452 const analyze_format_string::ConversionSpecifier &CS,
2453 const char *startSpecifier, unsigned specifierLen,
2454 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002455
2456 template <typename Range>
2457 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2458 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002459 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002460};
2461}
2462
Ted Kremenek02087932010-07-16 02:11:22 +00002463SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002464 return OrigFormatExpr->getSourceRange();
2465}
2466
Ted Kremenek02087932010-07-16 02:11:22 +00002467CharSourceRange CheckFormatHandler::
2468getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002469 SourceLocation Start = getLocationOfByte(startSpecifier);
2470 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2471
2472 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002473 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002474
2475 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002476}
2477
Ted Kremenek02087932010-07-16 02:11:22 +00002478SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002479 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002480}
2481
Ted Kremenek02087932010-07-16 02:11:22 +00002482void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2483 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002484 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2485 getLocationOfByte(startSpecifier),
2486 /*IsStringLocation*/true,
2487 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002488}
2489
Jordan Rose92303592012-09-08 04:00:03 +00002490void CheckFormatHandler::HandleInvalidLengthModifier(
2491 const analyze_format_string::FormatSpecifier &FS,
2492 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002493 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002494 using namespace analyze_format_string;
2495
2496 const LengthModifier &LM = FS.getLengthModifier();
2497 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2498
2499 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002500 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002501 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002502 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002503 getLocationOfByte(LM.getStart()),
2504 /*IsStringLocation*/true,
2505 getSpecifierRange(startSpecifier, specifierLen));
2506
2507 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2508 << FixedLM->toString()
2509 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2510
2511 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002512 FixItHint Hint;
2513 if (DiagID == diag::warn_format_nonsensical_length)
2514 Hint = FixItHint::CreateRemoval(LMRange);
2515
2516 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002517 getLocationOfByte(LM.getStart()),
2518 /*IsStringLocation*/true,
2519 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002520 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002521 }
2522}
2523
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002524void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002525 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002526 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002527 using namespace analyze_format_string;
2528
2529 const LengthModifier &LM = FS.getLengthModifier();
2530 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2531
2532 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002533 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002534 if (FixedLM) {
2535 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2536 << LM.toString() << 0,
2537 getLocationOfByte(LM.getStart()),
2538 /*IsStringLocation*/true,
2539 getSpecifierRange(startSpecifier, specifierLen));
2540
2541 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2542 << FixedLM->toString()
2543 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2544
2545 } else {
2546 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2547 << LM.toString() << 0,
2548 getLocationOfByte(LM.getStart()),
2549 /*IsStringLocation*/true,
2550 getSpecifierRange(startSpecifier, specifierLen));
2551 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002552}
2553
2554void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2555 const analyze_format_string::ConversionSpecifier &CS,
2556 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002557 using namespace analyze_format_string;
2558
2559 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002560 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002561 if (FixedCS) {
2562 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2563 << CS.toString() << /*conversion specifier*/1,
2564 getLocationOfByte(CS.getStart()),
2565 /*IsStringLocation*/true,
2566 getSpecifierRange(startSpecifier, specifierLen));
2567
2568 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2569 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2570 << FixedCS->toString()
2571 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2572 } else {
2573 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2574 << CS.toString() << /*conversion specifier*/1,
2575 getLocationOfByte(CS.getStart()),
2576 /*IsStringLocation*/true,
2577 getSpecifierRange(startSpecifier, specifierLen));
2578 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002579}
2580
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002581void CheckFormatHandler::HandlePosition(const char *startPos,
2582 unsigned posLen) {
2583 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2584 getLocationOfByte(startPos),
2585 /*IsStringLocation*/true,
2586 getSpecifierRange(startPos, posLen));
2587}
2588
Ted Kremenekd1668192010-02-27 01:41:03 +00002589void
Ted Kremenek02087932010-07-16 02:11:22 +00002590CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2591 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002592 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2593 << (unsigned) p,
2594 getLocationOfByte(startPos), /*IsStringLocation*/true,
2595 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002596}
2597
Ted Kremenek02087932010-07-16 02:11:22 +00002598void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002599 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002600 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2601 getLocationOfByte(startPos),
2602 /*IsStringLocation*/true,
2603 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002604}
2605
Ted Kremenek02087932010-07-16 02:11:22 +00002606void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002607 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002608 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002609 EmitFormatDiagnostic(
2610 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2611 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2612 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002613 }
Ted Kremenek02087932010-07-16 02:11:22 +00002614}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002615
Jordan Rose58bbe422012-07-19 18:10:08 +00002616// Note that this may return NULL if there was an error parsing or building
2617// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002618const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002619 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002620}
2621
2622void CheckFormatHandler::DoneProcessing() {
2623 // Does the number of data arguments exceed the number of
2624 // format conversions in the format string?
2625 if (!HasVAListArg) {
2626 // Find any arguments that weren't covered.
2627 CoveredArgs.flip();
2628 signed notCoveredArg = CoveredArgs.find_first();
2629 if (notCoveredArg >= 0) {
2630 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002631 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2632 SourceLocation Loc = E->getLocStart();
2633 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2635 Loc, /*IsStringLocation*/false,
2636 getFormatStringRange());
2637 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002638 }
Ted Kremenek02087932010-07-16 02:11:22 +00002639 }
2640 }
2641}
2642
Ted Kremenekce815422010-07-19 21:25:57 +00002643bool
2644CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2645 SourceLocation Loc,
2646 const char *startSpec,
2647 unsigned specifierLen,
2648 const char *csStart,
2649 unsigned csLen) {
2650
2651 bool keepGoing = true;
2652 if (argIndex < NumDataArgs) {
2653 // Consider the argument coverered, even though the specifier doesn't
2654 // make sense.
2655 CoveredArgs.set(argIndex);
2656 }
2657 else {
2658 // If argIndex exceeds the number of data arguments we
2659 // don't issue a warning because that is just a cascade of warnings (and
2660 // they may have intended '%%' anyway). We don't want to continue processing
2661 // the format string after this point, however, as we will like just get
2662 // gibberish when trying to match arguments.
2663 keepGoing = false;
2664 }
2665
Richard Trieu03cf7b72011-10-28 00:41:25 +00002666 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2667 << StringRef(csStart, csLen),
2668 Loc, /*IsStringLocation*/true,
2669 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002670
2671 return keepGoing;
2672}
2673
Richard Trieu03cf7b72011-10-28 00:41:25 +00002674void
2675CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2676 const char *startSpec,
2677 unsigned specifierLen) {
2678 EmitFormatDiagnostic(
2679 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2680 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2681}
2682
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002683bool
2684CheckFormatHandler::CheckNumArgs(
2685 const analyze_format_string::FormatSpecifier &FS,
2686 const analyze_format_string::ConversionSpecifier &CS,
2687 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2688
2689 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002690 PartialDiagnostic PDiag = FS.usesPositionalArg()
2691 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2692 << (argIndex+1) << NumDataArgs)
2693 : S.PDiag(diag::warn_printf_insufficient_data_args);
2694 EmitFormatDiagnostic(
2695 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2696 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002697 return false;
2698 }
2699 return true;
2700}
2701
Richard Trieu03cf7b72011-10-28 00:41:25 +00002702template<typename Range>
2703void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2704 SourceLocation Loc,
2705 bool IsStringLocation,
2706 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002707 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002708 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002709 Loc, IsStringLocation, StringRange, FixIt);
2710}
2711
2712/// \brief If the format string is not within the funcion call, emit a note
2713/// so that the function call and string are in diagnostic messages.
2714///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002715/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002716/// call and only one diagnostic message will be produced. Otherwise, an
2717/// extra note will be emitted pointing to location of the format string.
2718///
2719/// \param ArgumentExpr the expression that is passed as the format string
2720/// argument in the function call. Used for getting locations when two
2721/// diagnostics are emitted.
2722///
2723/// \param PDiag the callee should already have provided any strings for the
2724/// diagnostic message. This function only adds locations and fixits
2725/// to diagnostics.
2726///
2727/// \param Loc primary location for diagnostic. If two diagnostics are
2728/// required, one will be at Loc and a new SourceLocation will be created for
2729/// the other one.
2730///
2731/// \param IsStringLocation if true, Loc points to the format string should be
2732/// used for the note. Otherwise, Loc points to the argument list and will
2733/// be used with PDiag.
2734///
2735/// \param StringRange some or all of the string to highlight. This is
2736/// templated so it can accept either a CharSourceRange or a SourceRange.
2737///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002738/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002739template<typename Range>
2740void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2741 const Expr *ArgumentExpr,
2742 PartialDiagnostic PDiag,
2743 SourceLocation Loc,
2744 bool IsStringLocation,
2745 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002746 ArrayRef<FixItHint> FixIt) {
2747 if (InFunctionCall) {
2748 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2749 D << StringRange;
2750 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2751 I != E; ++I) {
2752 D << *I;
2753 }
2754 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002755 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2756 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002757
2758 const Sema::SemaDiagnosticBuilder &Note =
2759 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2760 diag::note_format_string_defined);
2761
2762 Note << StringRange;
2763 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2764 I != E; ++I) {
2765 Note << *I;
2766 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002767 }
2768}
2769
Ted Kremenek02087932010-07-16 02:11:22 +00002770//===--- CHECK: Printf format string checking ------------------------------===//
2771
2772namespace {
2773class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002774 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002775public:
2776 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2777 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002778 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002779 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002780 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002781 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002782 Sema::VariadicCallType CallType,
2783 llvm::SmallBitVector &CheckedVarArgs)
2784 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2785 numDataArgs, beg, hasVAListArg, Args,
2786 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2787 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002788 {}
2789
Craig Toppere14c0f82014-03-12 04:55:44 +00002790
Ted Kremenek02087932010-07-16 02:11:22 +00002791 bool HandleInvalidPrintfConversionSpecifier(
2792 const analyze_printf::PrintfSpecifier &FS,
2793 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002794 unsigned specifierLen) override;
2795
Ted Kremenek02087932010-07-16 02:11:22 +00002796 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2797 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002798 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002799 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2800 const char *StartSpecifier,
2801 unsigned SpecifierLen,
2802 const Expr *E);
2803
Ted Kremenek02087932010-07-16 02:11:22 +00002804 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2805 const char *startSpecifier, unsigned specifierLen);
2806 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2807 const analyze_printf::OptionalAmount &Amt,
2808 unsigned type,
2809 const char *startSpecifier, unsigned specifierLen);
2810 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2811 const analyze_printf::OptionalFlag &flag,
2812 const char *startSpecifier, unsigned specifierLen);
2813 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2814 const analyze_printf::OptionalFlag &ignoredFlag,
2815 const analyze_printf::OptionalFlag &flag,
2816 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002817 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002818 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002819
Ted Kremenek02087932010-07-16 02:11:22 +00002820};
2821}
2822
2823bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2824 const analyze_printf::PrintfSpecifier &FS,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002827 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002828 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002829
Ted Kremenekce815422010-07-19 21:25:57 +00002830 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2831 getLocationOfByte(CS.getStart()),
2832 startSpecifier, specifierLen,
2833 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002834}
2835
Ted Kremenek02087932010-07-16 02:11:22 +00002836bool CheckPrintfHandler::HandleAmount(
2837 const analyze_format_string::OptionalAmount &Amt,
2838 unsigned k, const char *startSpecifier,
2839 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002840
2841 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002842 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002843 unsigned argIndex = Amt.getArgIndex();
2844 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002845 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2846 << k,
2847 getLocationOfByte(Amt.getStart()),
2848 /*IsStringLocation*/true,
2849 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002850 // Don't do any more checking. We will just emit
2851 // spurious errors.
2852 return false;
2853 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002854
Ted Kremenek5739de72010-01-29 01:06:55 +00002855 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002856 // Although not in conformance with C99, we also allow the argument to be
2857 // an 'unsigned int' as that is a reasonably safe case. GCC also
2858 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002859 CoveredArgs.set(argIndex);
2860 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002861 if (!Arg)
2862 return false;
2863
Ted Kremenek5739de72010-01-29 01:06:55 +00002864 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002865
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002866 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2867 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002868
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002869 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002871 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002872 << T << Arg->getSourceRange(),
2873 getLocationOfByte(Amt.getStart()),
2874 /*IsStringLocation*/true,
2875 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002876 // Don't do any more checking. We will just emit
2877 // spurious errors.
2878 return false;
2879 }
2880 }
2881 }
2882 return true;
2883}
Ted Kremenek5739de72010-01-29 01:06:55 +00002884
Tom Careb49ec692010-06-17 19:00:27 +00002885void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002886 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002887 const analyze_printf::OptionalAmount &Amt,
2888 unsigned type,
2889 const char *startSpecifier,
2890 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002891 const analyze_printf::PrintfConversionSpecifier &CS =
2892 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002893
Richard Trieu03cf7b72011-10-28 00:41:25 +00002894 FixItHint fixit =
2895 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2896 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2897 Amt.getConstantLength()))
2898 : FixItHint();
2899
2900 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2901 << type << CS.toString(),
2902 getLocationOfByte(Amt.getStart()),
2903 /*IsStringLocation*/true,
2904 getSpecifierRange(startSpecifier, specifierLen),
2905 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002906}
2907
Ted Kremenek02087932010-07-16 02:11:22 +00002908void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002909 const analyze_printf::OptionalFlag &flag,
2910 const char *startSpecifier,
2911 unsigned specifierLen) {
2912 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002913 const analyze_printf::PrintfConversionSpecifier &CS =
2914 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2916 << flag.toString() << CS.toString(),
2917 getLocationOfByte(flag.getPosition()),
2918 /*IsStringLocation*/true,
2919 getSpecifierRange(startSpecifier, specifierLen),
2920 FixItHint::CreateRemoval(
2921 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002922}
2923
2924void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002925 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002926 const analyze_printf::OptionalFlag &ignoredFlag,
2927 const analyze_printf::OptionalFlag &flag,
2928 const char *startSpecifier,
2929 unsigned specifierLen) {
2930 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002931 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2932 << ignoredFlag.toString() << flag.toString(),
2933 getLocationOfByte(ignoredFlag.getPosition()),
2934 /*IsStringLocation*/true,
2935 getSpecifierRange(startSpecifier, specifierLen),
2936 FixItHint::CreateRemoval(
2937 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002938}
2939
Richard Smith55ce3522012-06-25 20:30:08 +00002940// Determines if the specified is a C++ class or struct containing
2941// a member with the specified name and kind (e.g. a CXXMethodDecl named
2942// "c_str()").
2943template<typename MemberKind>
2944static llvm::SmallPtrSet<MemberKind*, 1>
2945CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2946 const RecordType *RT = Ty->getAs<RecordType>();
2947 llvm::SmallPtrSet<MemberKind*, 1> Results;
2948
2949 if (!RT)
2950 return Results;
2951 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002952 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002953 return Results;
2954
2955 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2956 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002957 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002958
2959 // We just need to include all members of the right kind turned up by the
2960 // filter, at this point.
2961 if (S.LookupQualifiedName(R, RT->getDecl()))
2962 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2963 NamedDecl *decl = (*I)->getUnderlyingDecl();
2964 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2965 Results.insert(FK);
2966 }
2967 return Results;
2968}
2969
Richard Smith2868a732014-02-28 01:36:39 +00002970/// Check if we could call '.c_str()' on an object.
2971///
2972/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2973/// allow the call, or if it would be ambiguous).
2974bool Sema::hasCStrMethod(const Expr *E) {
2975 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2976 MethodSet Results =
2977 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2978 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2979 MI != ME; ++MI)
2980 if ((*MI)->getMinRequiredArguments() == 0)
2981 return true;
2982 return false;
2983}
2984
Richard Smith55ce3522012-06-25 20:30:08 +00002985// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002986// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002987// Returns true when a c_str() conversion method is found.
2988bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002989 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002990 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2991
2992 MethodSet Results =
2993 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2994
2995 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2996 MI != ME; ++MI) {
2997 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002998 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002999 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003000 // FIXME: Suggest parens if the expression needs them.
3001 SourceLocation EndLoc =
3002 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
3003 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3004 << "c_str()"
3005 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3006 return true;
3007 }
3008 }
3009
3010 return false;
3011}
3012
Ted Kremenekab278de2010-01-28 23:39:18 +00003013bool
Ted Kremenek02087932010-07-16 02:11:22 +00003014CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003015 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003016 const char *startSpecifier,
3017 unsigned specifierLen) {
3018
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003019 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003020 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003021 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003022
Ted Kremenek6cd69422010-07-19 22:01:06 +00003023 if (FS.consumesDataArgument()) {
3024 if (atFirstArg) {
3025 atFirstArg = false;
3026 usesPositionalArgs = FS.usesPositionalArg();
3027 }
3028 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003029 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3030 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003031 return false;
3032 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003033 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003034
Ted Kremenekd1668192010-02-27 01:41:03 +00003035 // First check if the field width, precision, and conversion specifier
3036 // have matching data arguments.
3037 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3038 startSpecifier, specifierLen)) {
3039 return false;
3040 }
3041
3042 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3043 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003044 return false;
3045 }
3046
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003047 if (!CS.consumesDataArgument()) {
3048 // FIXME: Technically specifying a precision or field width here
3049 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003050 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003051 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003052
Ted Kremenek4a49d982010-02-26 19:18:41 +00003053 // Consume the argument.
3054 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003055 if (argIndex < NumDataArgs) {
3056 // The check to see if the argIndex is valid will come later.
3057 // We set the bit here because we may exit early from this
3058 // function if we encounter some other error.
3059 CoveredArgs.set(argIndex);
3060 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003061
3062 // Check for using an Objective-C specific conversion specifier
3063 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003064 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003065 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3066 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003067 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003068
Tom Careb49ec692010-06-17 19:00:27 +00003069 // Check for invalid use of field width
3070 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003071 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003072 startSpecifier, specifierLen);
3073 }
3074
3075 // Check for invalid use of precision
3076 if (!FS.hasValidPrecision()) {
3077 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3078 startSpecifier, specifierLen);
3079 }
3080
3081 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003082 if (!FS.hasValidThousandsGroupingPrefix())
3083 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003084 if (!FS.hasValidLeadingZeros())
3085 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3086 if (!FS.hasValidPlusPrefix())
3087 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003088 if (!FS.hasValidSpacePrefix())
3089 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003090 if (!FS.hasValidAlternativeForm())
3091 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3092 if (!FS.hasValidLeftJustified())
3093 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3094
3095 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003096 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3097 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3098 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003099 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3100 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3101 startSpecifier, specifierLen);
3102
3103 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003104 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003105 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3106 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003107 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003108 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003109 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3111 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003112
Jordan Rose92303592012-09-08 04:00:03 +00003113 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3114 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3115
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003116 // The remaining checks depend on the data arguments.
3117 if (HasVAListArg)
3118 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003119
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003120 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003121 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003122
Jordan Rose58bbe422012-07-19 18:10:08 +00003123 const Expr *Arg = getDataArg(argIndex);
3124 if (!Arg)
3125 return true;
3126
3127 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003128}
3129
Jordan Roseaee34382012-09-05 22:56:26 +00003130static bool requiresParensToAddCast(const Expr *E) {
3131 // FIXME: We should have a general way to reason about operator
3132 // precedence and whether parens are actually needed here.
3133 // Take care of a few common cases where they aren't.
3134 const Expr *Inside = E->IgnoreImpCasts();
3135 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3136 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3137
3138 switch (Inside->getStmtClass()) {
3139 case Stmt::ArraySubscriptExprClass:
3140 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003141 case Stmt::CharacterLiteralClass:
3142 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003143 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003144 case Stmt::FloatingLiteralClass:
3145 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003146 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003147 case Stmt::ObjCArrayLiteralClass:
3148 case Stmt::ObjCBoolLiteralExprClass:
3149 case Stmt::ObjCBoxedExprClass:
3150 case Stmt::ObjCDictionaryLiteralClass:
3151 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003152 case Stmt::ObjCIvarRefExprClass:
3153 case Stmt::ObjCMessageExprClass:
3154 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003155 case Stmt::ObjCStringLiteralClass:
3156 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003157 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003158 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003159 case Stmt::UnaryOperatorClass:
3160 return false;
3161 default:
3162 return true;
3163 }
3164}
3165
Richard Smith55ce3522012-06-25 20:30:08 +00003166bool
3167CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3168 const char *StartSpecifier,
3169 unsigned SpecifierLen,
3170 const Expr *E) {
3171 using namespace analyze_format_string;
3172 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003173 // Now type check the data expression that matches the
3174 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003175 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3176 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003177 if (!AT.isValid())
3178 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003179
Jordan Rose598ec092012-12-05 18:44:40 +00003180 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003181 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3182 ExprTy = TET->getUnderlyingExpr()->getType();
3183 }
3184
Jordan Rose598ec092012-12-05 18:44:40 +00003185 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003186 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003187
Jordan Rose22b74712012-09-05 22:56:19 +00003188 // Look through argument promotions for our error message's reported type.
3189 // This includes the integral and floating promotions, but excludes array
3190 // and function pointer decay; seeing that an argument intended to be a
3191 // string has type 'char [6]' is probably more confusing than 'char *'.
3192 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3193 if (ICE->getCastKind() == CK_IntegralCast ||
3194 ICE->getCastKind() == CK_FloatingCast) {
3195 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003196 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003197
3198 // Check if we didn't match because of an implicit cast from a 'char'
3199 // or 'short' to an 'int'. This is done because printf is a varargs
3200 // function.
3201 if (ICE->getType() == S.Context.IntTy ||
3202 ICE->getType() == S.Context.UnsignedIntTy) {
3203 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003204 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003205 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003206 }
Jordan Rose98709982012-06-04 22:48:57 +00003207 }
Jordan Rose598ec092012-12-05 18:44:40 +00003208 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3209 // Special case for 'a', which has type 'int' in C.
3210 // Note, however, that we do /not/ want to treat multibyte constants like
3211 // 'MooV' as characters! This form is deprecated but still exists.
3212 if (ExprTy == S.Context.IntTy)
3213 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3214 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003215 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003216
Jordan Rose0e5badd2012-12-05 18:44:49 +00003217 // %C in an Objective-C context prints a unichar, not a wchar_t.
3218 // If the argument is an integer of some kind, believe the %C and suggest
3219 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003220 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003221 if (ObjCContext &&
3222 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3223 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3224 !ExprTy->isCharType()) {
3225 // 'unichar' is defined as a typedef of unsigned short, but we should
3226 // prefer using the typedef if it is visible.
3227 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003228
3229 // While we are here, check if the value is an IntegerLiteral that happens
3230 // to be within the valid range.
3231 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3232 const llvm::APInt &V = IL->getValue();
3233 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3234 return true;
3235 }
3236
Jordan Rose0e5badd2012-12-05 18:44:49 +00003237 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3238 Sema::LookupOrdinaryName);
3239 if (S.LookupName(Result, S.getCurScope())) {
3240 NamedDecl *ND = Result.getFoundDecl();
3241 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3242 if (TD->getUnderlyingType() == IntendedTy)
3243 IntendedTy = S.Context.getTypedefType(TD);
3244 }
3245 }
3246 }
3247
3248 // Special-case some of Darwin's platform-independence types by suggesting
3249 // casts to primitive types that are known to be large enough.
3250 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003251 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003252 // Use a 'while' to peel off layers of typedefs.
3253 QualType TyTy = IntendedTy;
3254 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003255 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003256 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003257 .Case("NSInteger", S.Context.LongTy)
3258 .Case("NSUInteger", S.Context.UnsignedLongTy)
3259 .Case("SInt32", S.Context.IntTy)
3260 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003261 .Default(QualType());
3262
3263 if (!CastTy.isNull()) {
3264 ShouldNotPrintDirectly = true;
3265 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003266 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003267 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003268 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003269 }
3270 }
3271
Jordan Rose22b74712012-09-05 22:56:19 +00003272 // We may be able to offer a FixItHint if it is a supported type.
3273 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003274 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003275 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003276
Jordan Rose22b74712012-09-05 22:56:19 +00003277 if (success) {
3278 // Get the fix string from the fixed format specifier
3279 SmallString<16> buf;
3280 llvm::raw_svector_ostream os(buf);
3281 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003282
Jordan Roseaee34382012-09-05 22:56:26 +00003283 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3284
Jordan Rose0e5badd2012-12-05 18:44:49 +00003285 if (IntendedTy == ExprTy) {
3286 // In this case, the specifier is wrong and should be changed to match
3287 // the argument.
3288 EmitFormatDiagnostic(
3289 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3290 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3291 << E->getSourceRange(),
3292 E->getLocStart(),
3293 /*IsStringLocation*/false,
3294 SpecRange,
3295 FixItHint::CreateReplacement(SpecRange, os.str()));
3296
3297 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003298 // The canonical type for formatting this value is different from the
3299 // actual type of the expression. (This occurs, for example, with Darwin's
3300 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3301 // should be printed as 'long' for 64-bit compatibility.)
3302 // Rather than emitting a normal format/argument mismatch, we want to
3303 // add a cast to the recommended type (and correct the format string
3304 // if necessary).
3305 SmallString<16> CastBuf;
3306 llvm::raw_svector_ostream CastFix(CastBuf);
3307 CastFix << "(";
3308 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3309 CastFix << ")";
3310
3311 SmallVector<FixItHint,4> Hints;
3312 if (!AT.matchesType(S.Context, IntendedTy))
3313 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3314
3315 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3316 // If there's already a cast present, just replace it.
3317 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3318 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3319
3320 } else if (!requiresParensToAddCast(E)) {
3321 // If the expression has high enough precedence,
3322 // just write the C-style cast.
3323 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3324 CastFix.str()));
3325 } else {
3326 // Otherwise, add parens around the expression as well as the cast.
3327 CastFix << "(";
3328 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3329 CastFix.str()));
3330
3331 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3332 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3333 }
3334
Jordan Rose0e5badd2012-12-05 18:44:49 +00003335 if (ShouldNotPrintDirectly) {
3336 // The expression has a type that should not be printed directly.
3337 // We extract the name from the typedef because we don't want to show
3338 // the underlying type in the diagnostic.
3339 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003340
Jordan Rose0e5badd2012-12-05 18:44:49 +00003341 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3342 << Name << IntendedTy
3343 << E->getSourceRange(),
3344 E->getLocStart(), /*IsStringLocation=*/false,
3345 SpecRange, Hints);
3346 } else {
3347 // In this case, the expression could be printed using a different
3348 // specifier, but we've decided that the specifier is probably correct
3349 // and we should cast instead. Just use the normal warning message.
3350 EmitFormatDiagnostic(
3351 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3352 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3353 << E->getSourceRange(),
3354 E->getLocStart(), /*IsStringLocation*/false,
3355 SpecRange, Hints);
3356 }
Jordan Roseaee34382012-09-05 22:56:26 +00003357 }
Jordan Rose22b74712012-09-05 22:56:19 +00003358 } else {
3359 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3360 SpecifierLen);
3361 // Since the warning for passing non-POD types to variadic functions
3362 // was deferred until now, we emit a warning for non-POD
3363 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003364 switch (S.isValidVarArgType(ExprTy)) {
3365 case Sema::VAK_Valid:
3366 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003367 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003368 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3369 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3370 << CSR
3371 << E->getSourceRange(),
3372 E->getLocStart(), /*IsStringLocation*/false, CSR);
3373 break;
3374
3375 case Sema::VAK_Undefined:
3376 EmitFormatDiagnostic(
3377 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003378 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003379 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003380 << CallType
3381 << AT.getRepresentativeTypeName(S.Context)
3382 << CSR
3383 << E->getSourceRange(),
3384 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003385 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003386 break;
3387
3388 case Sema::VAK_Invalid:
3389 if (ExprTy->isObjCObjectType())
3390 EmitFormatDiagnostic(
3391 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3392 << S.getLangOpts().CPlusPlus11
3393 << ExprTy
3394 << CallType
3395 << AT.getRepresentativeTypeName(S.Context)
3396 << CSR
3397 << E->getSourceRange(),
3398 E->getLocStart(), /*IsStringLocation*/false, CSR);
3399 else
3400 // FIXME: If this is an initializer list, suggest removing the braces
3401 // or inserting a cast to the target type.
3402 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3403 << isa<InitListExpr>(E) << ExprTy << CallType
3404 << AT.getRepresentativeTypeName(S.Context)
3405 << E->getSourceRange();
3406 break;
3407 }
3408
3409 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3410 "format string specifier index out of range");
3411 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003412 }
3413
Ted Kremenekab278de2010-01-28 23:39:18 +00003414 return true;
3415}
3416
Ted Kremenek02087932010-07-16 02:11:22 +00003417//===--- CHECK: Scanf format string checking ------------------------------===//
3418
3419namespace {
3420class CheckScanfHandler : public CheckFormatHandler {
3421public:
3422 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3423 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003424 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003425 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003426 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003427 Sema::VariadicCallType CallType,
3428 llvm::SmallBitVector &CheckedVarArgs)
3429 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3430 numDataArgs, beg, hasVAListArg,
3431 Args, formatIdx, inFunctionCall, CallType,
3432 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003433 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003434
3435 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3436 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003437 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003438
3439 bool HandleInvalidScanfConversionSpecifier(
3440 const analyze_scanf::ScanfSpecifier &FS,
3441 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003442 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003443
Craig Toppere14c0f82014-03-12 04:55:44 +00003444 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003445};
Ted Kremenek019d2242010-01-29 01:50:07 +00003446}
Ted Kremenekab278de2010-01-28 23:39:18 +00003447
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003448void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3449 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003450 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3451 getLocationOfByte(end), /*IsStringLocation*/true,
3452 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003453}
3454
Ted Kremenekce815422010-07-19 21:25:57 +00003455bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3456 const analyze_scanf::ScanfSpecifier &FS,
3457 const char *startSpecifier,
3458 unsigned specifierLen) {
3459
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003460 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003461 FS.getConversionSpecifier();
3462
3463 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3464 getLocationOfByte(CS.getStart()),
3465 startSpecifier, specifierLen,
3466 CS.getStart(), CS.getLength());
3467}
3468
Ted Kremenek02087932010-07-16 02:11:22 +00003469bool CheckScanfHandler::HandleScanfSpecifier(
3470 const analyze_scanf::ScanfSpecifier &FS,
3471 const char *startSpecifier,
3472 unsigned specifierLen) {
3473
3474 using namespace analyze_scanf;
3475 using namespace analyze_format_string;
3476
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003477 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003478
Ted Kremenek6cd69422010-07-19 22:01:06 +00003479 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3480 // be used to decide if we are using positional arguments consistently.
3481 if (FS.consumesDataArgument()) {
3482 if (atFirstArg) {
3483 atFirstArg = false;
3484 usesPositionalArgs = FS.usesPositionalArg();
3485 }
3486 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003487 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3488 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003489 return false;
3490 }
Ted Kremenek02087932010-07-16 02:11:22 +00003491 }
3492
3493 // Check if the field with is non-zero.
3494 const OptionalAmount &Amt = FS.getFieldWidth();
3495 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3496 if (Amt.getConstantAmount() == 0) {
3497 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3498 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003499 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3500 getLocationOfByte(Amt.getStart()),
3501 /*IsStringLocation*/true, R,
3502 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003503 }
3504 }
3505
3506 if (!FS.consumesDataArgument()) {
3507 // FIXME: Technically specifying a precision or field width here
3508 // makes no sense. Worth issuing a warning at some point.
3509 return true;
3510 }
3511
3512 // Consume the argument.
3513 unsigned argIndex = FS.getArgIndex();
3514 if (argIndex < NumDataArgs) {
3515 // The check to see if the argIndex is valid will come later.
3516 // We set the bit here because we may exit early from this
3517 // function if we encounter some other error.
3518 CoveredArgs.set(argIndex);
3519 }
3520
Ted Kremenek4407ea42010-07-20 20:04:47 +00003521 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003522 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003523 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3524 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003525 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003526 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003527 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003528 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3529 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003530
Jordan Rose92303592012-09-08 04:00:03 +00003531 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3532 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3533
Ted Kremenek02087932010-07-16 02:11:22 +00003534 // The remaining checks depend on the data arguments.
3535 if (HasVAListArg)
3536 return true;
3537
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003538 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003539 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003540
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003541 // Check that the argument type matches the format specifier.
3542 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003543 if (!Ex)
3544 return true;
3545
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003546 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3547 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003548 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003549 bool success = fixedFS.fixType(Ex->getType(),
3550 Ex->IgnoreImpCasts()->getType(),
3551 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003552
3553 if (success) {
3554 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003555 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003556 llvm::raw_svector_ostream os(buf);
3557 fixedFS.toString(os);
3558
3559 EmitFormatDiagnostic(
3560 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003561 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003562 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003563 Ex->getLocStart(),
3564 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003565 getSpecifierRange(startSpecifier, specifierLen),
3566 FixItHint::CreateReplacement(
3567 getSpecifierRange(startSpecifier, specifierLen),
3568 os.str()));
3569 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003570 EmitFormatDiagnostic(
3571 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003572 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003573 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003574 Ex->getLocStart(),
3575 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003576 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003577 }
3578 }
3579
Ted Kremenek02087932010-07-16 02:11:22 +00003580 return true;
3581}
3582
3583void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003584 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003585 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003586 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003587 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003588 bool inFunctionCall, VariadicCallType CallType,
3589 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003590
Ted Kremenekab278de2010-01-28 23:39:18 +00003591 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003592 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003593 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003594 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003595 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3596 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003597 return;
3598 }
Ted Kremenek02087932010-07-16 02:11:22 +00003599
Ted Kremenekab278de2010-01-28 23:39:18 +00003600 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003601 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003602 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003603 // Account for cases where the string literal is truncated in a declaration.
3604 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3605 assert(T && "String literal not of constant array type!");
3606 size_t TypeSize = T->getSize().getZExtValue();
3607 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003608 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003609
3610 // Emit a warning if the string literal is truncated and does not contain an
3611 // embedded null character.
3612 if (TypeSize <= StrRef.size() &&
3613 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3614 CheckFormatHandler::EmitFormatDiagnostic(
3615 *this, inFunctionCall, Args[format_idx],
3616 PDiag(diag::warn_printf_format_string_not_null_terminated),
3617 FExpr->getLocStart(),
3618 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3619 return;
3620 }
3621
Ted Kremenekab278de2010-01-28 23:39:18 +00003622 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003623 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003624 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003625 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003626 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3627 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003628 return;
3629 }
Ted Kremenek02087932010-07-16 02:11:22 +00003630
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003631 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003632 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003633 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003634 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003635 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003636
Hans Wennborg23926bd2011-12-15 10:25:47 +00003637 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003638 getLangOpts(),
3639 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003640 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003641 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003642 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003643 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003644 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003645
Hans Wennborg23926bd2011-12-15 10:25:47 +00003646 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003647 getLangOpts(),
3648 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003649 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003650 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003651}
3652
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003653//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3654
3655// Returns the related absolute value function that is larger, of 0 if one
3656// does not exist.
3657static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3658 switch (AbsFunction) {
3659 default:
3660 return 0;
3661
3662 case Builtin::BI__builtin_abs:
3663 return Builtin::BI__builtin_labs;
3664 case Builtin::BI__builtin_labs:
3665 return Builtin::BI__builtin_llabs;
3666 case Builtin::BI__builtin_llabs:
3667 return 0;
3668
3669 case Builtin::BI__builtin_fabsf:
3670 return Builtin::BI__builtin_fabs;
3671 case Builtin::BI__builtin_fabs:
3672 return Builtin::BI__builtin_fabsl;
3673 case Builtin::BI__builtin_fabsl:
3674 return 0;
3675
3676 case Builtin::BI__builtin_cabsf:
3677 return Builtin::BI__builtin_cabs;
3678 case Builtin::BI__builtin_cabs:
3679 return Builtin::BI__builtin_cabsl;
3680 case Builtin::BI__builtin_cabsl:
3681 return 0;
3682
3683 case Builtin::BIabs:
3684 return Builtin::BIlabs;
3685 case Builtin::BIlabs:
3686 return Builtin::BIllabs;
3687 case Builtin::BIllabs:
3688 return 0;
3689
3690 case Builtin::BIfabsf:
3691 return Builtin::BIfabs;
3692 case Builtin::BIfabs:
3693 return Builtin::BIfabsl;
3694 case Builtin::BIfabsl:
3695 return 0;
3696
3697 case Builtin::BIcabsf:
3698 return Builtin::BIcabs;
3699 case Builtin::BIcabs:
3700 return Builtin::BIcabsl;
3701 case Builtin::BIcabsl:
3702 return 0;
3703 }
3704}
3705
3706// Returns the argument type of the absolute value function.
3707static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3708 unsigned AbsType) {
3709 if (AbsType == 0)
3710 return QualType();
3711
3712 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3713 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3714 if (Error != ASTContext::GE_None)
3715 return QualType();
3716
3717 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3718 if (!FT)
3719 return QualType();
3720
3721 if (FT->getNumParams() != 1)
3722 return QualType();
3723
3724 return FT->getParamType(0);
3725}
3726
3727// Returns the best absolute value function, or zero, based on type and
3728// current absolute value function.
3729static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3730 unsigned AbsFunctionKind) {
3731 unsigned BestKind = 0;
3732 uint64_t ArgSize = Context.getTypeSize(ArgType);
3733 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3734 Kind = getLargerAbsoluteValueFunction(Kind)) {
3735 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3736 if (Context.getTypeSize(ParamType) >= ArgSize) {
3737 if (BestKind == 0)
3738 BestKind = Kind;
3739 else if (Context.hasSameType(ParamType, ArgType)) {
3740 BestKind = Kind;
3741 break;
3742 }
3743 }
3744 }
3745 return BestKind;
3746}
3747
3748enum AbsoluteValueKind {
3749 AVK_Integer,
3750 AVK_Floating,
3751 AVK_Complex
3752};
3753
3754static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3755 if (T->isIntegralOrEnumerationType())
3756 return AVK_Integer;
3757 if (T->isRealFloatingType())
3758 return AVK_Floating;
3759 if (T->isAnyComplexType())
3760 return AVK_Complex;
3761
3762 llvm_unreachable("Type not integer, floating, or complex");
3763}
3764
3765// Changes the absolute value function to a different type. Preserves whether
3766// the function is a builtin.
3767static unsigned changeAbsFunction(unsigned AbsKind,
3768 AbsoluteValueKind ValueKind) {
3769 switch (ValueKind) {
3770 case AVK_Integer:
3771 switch (AbsKind) {
3772 default:
3773 return 0;
3774 case Builtin::BI__builtin_fabsf:
3775 case Builtin::BI__builtin_fabs:
3776 case Builtin::BI__builtin_fabsl:
3777 case Builtin::BI__builtin_cabsf:
3778 case Builtin::BI__builtin_cabs:
3779 case Builtin::BI__builtin_cabsl:
3780 return Builtin::BI__builtin_abs;
3781 case Builtin::BIfabsf:
3782 case Builtin::BIfabs:
3783 case Builtin::BIfabsl:
3784 case Builtin::BIcabsf:
3785 case Builtin::BIcabs:
3786 case Builtin::BIcabsl:
3787 return Builtin::BIabs;
3788 }
3789 case AVK_Floating:
3790 switch (AbsKind) {
3791 default:
3792 return 0;
3793 case Builtin::BI__builtin_abs:
3794 case Builtin::BI__builtin_labs:
3795 case Builtin::BI__builtin_llabs:
3796 case Builtin::BI__builtin_cabsf:
3797 case Builtin::BI__builtin_cabs:
3798 case Builtin::BI__builtin_cabsl:
3799 return Builtin::BI__builtin_fabsf;
3800 case Builtin::BIabs:
3801 case Builtin::BIlabs:
3802 case Builtin::BIllabs:
3803 case Builtin::BIcabsf:
3804 case Builtin::BIcabs:
3805 case Builtin::BIcabsl:
3806 return Builtin::BIfabsf;
3807 }
3808 case AVK_Complex:
3809 switch (AbsKind) {
3810 default:
3811 return 0;
3812 case Builtin::BI__builtin_abs:
3813 case Builtin::BI__builtin_labs:
3814 case Builtin::BI__builtin_llabs:
3815 case Builtin::BI__builtin_fabsf:
3816 case Builtin::BI__builtin_fabs:
3817 case Builtin::BI__builtin_fabsl:
3818 return Builtin::BI__builtin_cabsf;
3819 case Builtin::BIabs:
3820 case Builtin::BIlabs:
3821 case Builtin::BIllabs:
3822 case Builtin::BIfabsf:
3823 case Builtin::BIfabs:
3824 case Builtin::BIfabsl:
3825 return Builtin::BIcabsf;
3826 }
3827 }
3828 llvm_unreachable("Unable to convert function");
3829}
3830
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003831static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003832 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3833 if (!FnInfo)
3834 return 0;
3835
3836 switch (FDecl->getBuiltinID()) {
3837 default:
3838 return 0;
3839 case Builtin::BI__builtin_abs:
3840 case Builtin::BI__builtin_fabs:
3841 case Builtin::BI__builtin_fabsf:
3842 case Builtin::BI__builtin_fabsl:
3843 case Builtin::BI__builtin_labs:
3844 case Builtin::BI__builtin_llabs:
3845 case Builtin::BI__builtin_cabs:
3846 case Builtin::BI__builtin_cabsf:
3847 case Builtin::BI__builtin_cabsl:
3848 case Builtin::BIabs:
3849 case Builtin::BIlabs:
3850 case Builtin::BIllabs:
3851 case Builtin::BIfabs:
3852 case Builtin::BIfabsf:
3853 case Builtin::BIfabsl:
3854 case Builtin::BIcabs:
3855 case Builtin::BIcabsf:
3856 case Builtin::BIcabsl:
3857 return FDecl->getBuiltinID();
3858 }
3859 llvm_unreachable("Unknown Builtin type");
3860}
3861
3862// If the replacement is valid, emit a note with replacement function.
3863// Additionally, suggest including the proper header if not already included.
3864static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3865 unsigned AbsKind) {
3866 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3867
3868 // Look up absolute value function in TU scope.
3869 DeclarationName DN(&S.Context.Idents.get(AbsName));
3870 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
Richard Trieufe771c02014-03-06 02:25:04 +00003871 R.suppressDiagnostics();
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003872 S.LookupName(R, S.TUScope);
3873
3874 // Skip notes if multiple results found in lookup.
3875 if (!R.empty() && !R.isSingleResult())
3876 return;
3877
3878 FunctionDecl *FD = 0;
3879 bool FoundFunction = R.isSingleResult();
3880 // When one result is found, see if it is the correct function.
3881 if (R.isSingleResult()) {
3882 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3883 if (!FD || FD->getBuiltinID() != AbsKind)
3884 return;
3885 }
3886
3887 // Look for local name conflict, prepend "::" as necessary.
3888 R.clear();
3889 S.LookupName(R, S.getCurScope());
3890
3891 if (!FoundFunction) {
3892 if (!R.empty()) {
3893 AbsName = "::" + AbsName;
3894 }
3895 } else { // FoundFunction
3896 if (R.isSingleResult()) {
3897 if (R.getFoundDecl() != FD) {
3898 AbsName = "::" + AbsName;
3899 }
3900 } else if (!R.empty()) {
3901 AbsName = "::" + AbsName;
3902 }
3903 }
3904
3905 S.Diag(Loc, diag::note_replace_abs_function)
3906 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3907
3908 if (!FoundFunction) {
3909 S.Diag(Loc, diag::note_please_include_header)
3910 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3911 << S.Context.BuiltinInfo.GetName(AbsKind);
3912 }
3913}
3914
3915// Warn when using the wrong abs() function.
3916void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3917 const FunctionDecl *FDecl,
3918 IdentifierInfo *FnInfo) {
3919 if (Call->getNumArgs() != 1)
3920 return;
3921
3922 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3923 if (AbsKind == 0)
3924 return;
3925
3926 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3927 QualType ParamType = Call->getArg(0)->getType();
3928
3929 // Unsigned types can not be negative. Suggest to drop the absolute value
3930 // function.
3931 if (ArgType->isUnsignedIntegerType()) {
3932 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3933 Diag(Call->getExprLoc(), diag::note_remove_abs)
3934 << FDecl
3935 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3936 return;
3937 }
3938
3939 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3940 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3941
3942 // The argument and parameter are the same kind. Check if they are the right
3943 // size.
3944 if (ArgValueKind == ParamValueKind) {
3945 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3946 return;
3947
3948 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3949 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3950 << FDecl << ArgType << ParamType;
3951
3952 if (NewAbsKind == 0)
3953 return;
3954
3955 emitReplacement(*this, Call->getExprLoc(),
3956 Call->getCallee()->getSourceRange(), NewAbsKind);
3957 return;
3958 }
3959
3960 // ArgValueKind != ParamValueKind
3961 // The wrong type of absolute value function was used. Attempt to find the
3962 // proper one.
3963 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3964 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3965 if (NewAbsKind == 0)
3966 return;
3967
3968 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3969 << FDecl << ParamValueKind << ArgValueKind;
3970
3971 emitReplacement(*this, Call->getExprLoc(),
3972 Call->getCallee()->getSourceRange(), NewAbsKind);
3973 return;
3974}
3975
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003976//===--- CHECK: Standard memory functions ---------------------------------===//
3977
Nico Weber0e6daef2013-12-26 23:38:39 +00003978/// \brief Takes the expression passed to the size_t parameter of functions
3979/// such as memcmp, strncat, etc and warns if it's a comparison.
3980///
3981/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3982static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3983 IdentifierInfo *FnName,
3984 SourceLocation FnLoc,
3985 SourceLocation RParenLoc) {
3986 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3987 if (!Size)
3988 return false;
3989
3990 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3991 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3992 return false;
3993
3994 Preprocessor &PP = S.getPreprocessor();
3995 SourceRange SizeRange = Size->getSourceRange();
3996 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3997 << SizeRange << FnName;
3998 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3999 << FnName
4000 << FixItHint::CreateInsertion(
4001 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
4002 ")")
4003 << FixItHint::CreateRemoval(RParenLoc);
4004 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
4005 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4006 << FixItHint::CreateInsertion(
4007 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
4008
4009 return true;
4010}
4011
Douglas Gregora74926b2011-05-03 20:05:22 +00004012/// \brief Determine whether the given type is a dynamic class type (e.g.,
4013/// whether it has a vtable).
4014static bool isDynamicClassType(QualType T) {
4015 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4016 if (CXXRecordDecl *Definition = Record->getDefinition())
4017 if (Definition->isDynamicClass())
4018 return true;
4019
4020 return false;
4021}
4022
Chandler Carruth889ed862011-06-21 23:04:20 +00004023/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004024/// otherwise returns NULL.
4025static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004026 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004027 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4028 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4029 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004030
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004031 return 0;
4032}
4033
Chandler Carruth889ed862011-06-21 23:04:20 +00004034/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004035static QualType getSizeOfArgType(const Expr* E) {
4036 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4037 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4038 if (SizeOf->getKind() == clang::UETT_SizeOf)
4039 return SizeOf->getTypeOfArgument();
4040
4041 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004042}
4043
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004044/// \brief Check for dangerous or invalid arguments to memset().
4045///
Chandler Carruthac687262011-06-03 06:23:57 +00004046/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004047/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4048/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004049///
4050/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004051void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004052 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004053 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004054 assert(BId != 0);
4055
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004056 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004057 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004058 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004059 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004060 return;
4061
Anna Zaks22122702012-01-17 00:37:07 +00004062 unsigned LastArg = (BId == Builtin::BImemset ||
4063 BId == Builtin::BIstrndup ? 1 : 2);
4064 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004065 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004066
Nico Weber0e6daef2013-12-26 23:38:39 +00004067 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4068 Call->getLocStart(), Call->getRParenLoc()))
4069 return;
4070
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004071 // We have special checking when the length is a sizeof expression.
4072 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4073 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4074 llvm::FoldingSetNodeID SizeOfArgID;
4075
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004076 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4077 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004078 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004079
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004080 QualType DestTy = Dest->getType();
4081 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4082 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004083
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004084 // Never warn about void type pointers. This can be used to suppress
4085 // false positives.
4086 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004087 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004088
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004089 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4090 // actually comparing the expressions for equality. Because computing the
4091 // expression IDs can be expensive, we only do this if the diagnostic is
4092 // enabled.
4093 if (SizeOfArg &&
4094 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4095 SizeOfArg->getExprLoc())) {
4096 // We only compute IDs for expressions if the warning is enabled, and
4097 // cache the sizeof arg's ID.
4098 if (SizeOfArgID == llvm::FoldingSetNodeID())
4099 SizeOfArg->Profile(SizeOfArgID, Context, true);
4100 llvm::FoldingSetNodeID DestID;
4101 Dest->Profile(DestID, Context, true);
4102 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004103 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4104 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004105 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004106 StringRef ReadableName = FnName->getName();
4107
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004108 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004109 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004110 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004111 if (!PointeeTy->isIncompleteType() &&
4112 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004113 ActionIdx = 2; // If the pointee's size is sizeof(char),
4114 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004115
4116 // If the function is defined as a builtin macro, do not show macro
4117 // expansion.
4118 SourceLocation SL = SizeOfArg->getExprLoc();
4119 SourceRange DSR = Dest->getSourceRange();
4120 SourceRange SSR = SizeOfArg->getSourceRange();
4121 SourceManager &SM = PP.getSourceManager();
4122
4123 if (SM.isMacroArgExpansion(SL)) {
4124 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4125 SL = SM.getSpellingLoc(SL);
4126 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4127 SM.getSpellingLoc(DSR.getEnd()));
4128 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4129 SM.getSpellingLoc(SSR.getEnd()));
4130 }
4131
Anna Zaksd08d9152012-05-30 23:14:52 +00004132 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004133 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004134 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004135 << PointeeTy
4136 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004137 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004138 << SSR);
4139 DiagRuntimeBehavior(SL, SizeOfArg,
4140 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4141 << ActionIdx
4142 << SSR);
4143
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004144 break;
4145 }
4146 }
4147
4148 // Also check for cases where the sizeof argument is the exact same
4149 // type as the memory argument, and where it points to a user-defined
4150 // record type.
4151 if (SizeOfArgTy != QualType()) {
4152 if (PointeeTy->isRecordType() &&
4153 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4154 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4155 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4156 << FnName << SizeOfArgTy << ArgIdx
4157 << PointeeTy << Dest->getSourceRange()
4158 << LenExpr->getSourceRange());
4159 break;
4160 }
Nico Weberc5e73862011-06-14 16:14:58 +00004161 }
4162
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004163 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004164 if (isDynamicClassType(PointeeTy)) {
4165
4166 unsigned OperationType = 0;
4167 // "overwritten" if we're warning about the destination for any call
4168 // but memcmp; otherwise a verb appropriate to the call.
4169 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4170 if (BId == Builtin::BImemcpy)
4171 OperationType = 1;
4172 else if(BId == Builtin::BImemmove)
4173 OperationType = 2;
4174 else if (BId == Builtin::BImemcmp)
4175 OperationType = 3;
4176 }
4177
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004178 DiagRuntimeBehavior(
4179 Dest->getExprLoc(), Dest,
4180 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004181 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004182 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004183 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004184 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004185 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4186 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004187 DiagRuntimeBehavior(
4188 Dest->getExprLoc(), Dest,
4189 PDiag(diag::warn_arc_object_memaccess)
4190 << ArgIdx << FnName << PointeeTy
4191 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004192 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004193 continue;
John McCall31168b02011-06-15 23:02:42 +00004194
4195 DiagRuntimeBehavior(
4196 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004197 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004198 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4199 break;
4200 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004201 }
4202}
4203
Ted Kremenek6865f772011-08-18 20:55:45 +00004204// A little helper routine: ignore addition and subtraction of integer literals.
4205// This intentionally does not ignore all integer constant expressions because
4206// we don't want to remove sizeof().
4207static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4208 Ex = Ex->IgnoreParenCasts();
4209
4210 for (;;) {
4211 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4212 if (!BO || !BO->isAdditiveOp())
4213 break;
4214
4215 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4216 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4217
4218 if (isa<IntegerLiteral>(RHS))
4219 Ex = LHS;
4220 else if (isa<IntegerLiteral>(LHS))
4221 Ex = RHS;
4222 else
4223 break;
4224 }
4225
4226 return Ex;
4227}
4228
Anna Zaks13b08572012-08-08 21:42:23 +00004229static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4230 ASTContext &Context) {
4231 // Only handle constant-sized or VLAs, but not flexible members.
4232 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4233 // Only issue the FIXIT for arrays of size > 1.
4234 if (CAT->getSize().getSExtValue() <= 1)
4235 return false;
4236 } else if (!Ty->isVariableArrayType()) {
4237 return false;
4238 }
4239 return true;
4240}
4241
Ted Kremenek6865f772011-08-18 20:55:45 +00004242// Warn if the user has made the 'size' argument to strlcpy or strlcat
4243// be the size of the source, instead of the destination.
4244void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4245 IdentifierInfo *FnName) {
4246
4247 // Don't crash if the user has the wrong number of arguments
4248 if (Call->getNumArgs() != 3)
4249 return;
4250
4251 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4252 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4253 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004254
4255 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4256 Call->getLocStart(), Call->getRParenLoc()))
4257 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004258
4259 // Look for 'strlcpy(dst, x, sizeof(x))'
4260 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4261 CompareWithSrc = Ex;
4262 else {
4263 // Look for 'strlcpy(dst, x, strlen(x))'
4264 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004265 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4266 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004267 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4268 }
4269 }
4270
4271 if (!CompareWithSrc)
4272 return;
4273
4274 // Determine if the argument to sizeof/strlen is equal to the source
4275 // argument. In principle there's all kinds of things you could do
4276 // here, for instance creating an == expression and evaluating it with
4277 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4278 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4279 if (!SrcArgDRE)
4280 return;
4281
4282 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4283 if (!CompareWithSrcDRE ||
4284 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4285 return;
4286
4287 const Expr *OriginalSizeArg = Call->getArg(2);
4288 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4289 << OriginalSizeArg->getSourceRange() << FnName;
4290
4291 // Output a FIXIT hint if the destination is an array (rather than a
4292 // pointer to an array). This could be enhanced to handle some
4293 // pointers if we know the actual size, like if DstArg is 'array+2'
4294 // we could say 'sizeof(array)-2'.
4295 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004296 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004297 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004298
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004299 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004300 llvm::raw_svector_ostream OS(sizeString);
4301 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004302 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004303 OS << ")";
4304
4305 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4306 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4307 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004308}
4309
Anna Zaks314cd092012-02-01 19:08:57 +00004310/// Check if two expressions refer to the same declaration.
4311static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4312 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4313 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4314 return D1->getDecl() == D2->getDecl();
4315 return false;
4316}
4317
4318static const Expr *getStrlenExprArg(const Expr *E) {
4319 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4320 const FunctionDecl *FD = CE->getDirectCallee();
4321 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4322 return 0;
4323 return CE->getArg(0)->IgnoreParenCasts();
4324 }
4325 return 0;
4326}
4327
4328// Warn on anti-patterns as the 'size' argument to strncat.
4329// The correct size argument should look like following:
4330// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4331void Sema::CheckStrncatArguments(const CallExpr *CE,
4332 IdentifierInfo *FnName) {
4333 // Don't crash if the user has the wrong number of arguments.
4334 if (CE->getNumArgs() < 3)
4335 return;
4336 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4337 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4338 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4339
Nico Weber0e6daef2013-12-26 23:38:39 +00004340 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4341 CE->getRParenLoc()))
4342 return;
4343
Anna Zaks314cd092012-02-01 19:08:57 +00004344 // Identify common expressions, which are wrongly used as the size argument
4345 // to strncat and may lead to buffer overflows.
4346 unsigned PatternType = 0;
4347 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4348 // - sizeof(dst)
4349 if (referToTheSameDecl(SizeOfArg, DstArg))
4350 PatternType = 1;
4351 // - sizeof(src)
4352 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4353 PatternType = 2;
4354 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4355 if (BE->getOpcode() == BO_Sub) {
4356 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4357 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4358 // - sizeof(dst) - strlen(dst)
4359 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4360 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4361 PatternType = 1;
4362 // - sizeof(src) - (anything)
4363 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4364 PatternType = 2;
4365 }
4366 }
4367
4368 if (PatternType == 0)
4369 return;
4370
Anna Zaks5069aa32012-02-03 01:27:37 +00004371 // Generate the diagnostic.
4372 SourceLocation SL = LenArg->getLocStart();
4373 SourceRange SR = LenArg->getSourceRange();
4374 SourceManager &SM = PP.getSourceManager();
4375
4376 // If the function is defined as a builtin macro, do not show macro expansion.
4377 if (SM.isMacroArgExpansion(SL)) {
4378 SL = SM.getSpellingLoc(SL);
4379 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4380 SM.getSpellingLoc(SR.getEnd()));
4381 }
4382
Anna Zaks13b08572012-08-08 21:42:23 +00004383 // Check if the destination is an array (rather than a pointer to an array).
4384 QualType DstTy = DstArg->getType();
4385 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4386 Context);
4387 if (!isKnownSizeArray) {
4388 if (PatternType == 1)
4389 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4390 else
4391 Diag(SL, diag::warn_strncat_src_size) << SR;
4392 return;
4393 }
4394
Anna Zaks314cd092012-02-01 19:08:57 +00004395 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004396 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004397 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004398 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004399
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004400 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004401 llvm::raw_svector_ostream OS(sizeString);
4402 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004403 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004404 OS << ") - ";
4405 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004406 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004407 OS << ") - 1";
4408
Anna Zaks5069aa32012-02-03 01:27:37 +00004409 Diag(SL, diag::note_strncat_wrong_size)
4410 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004411}
4412
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004413//===--- CHECK: Return Address of Stack Variable --------------------------===//
4414
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004415static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4416 Decl *ParentDecl);
4417static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4418 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004419
4420/// CheckReturnStackAddr - Check if a return statement returns the address
4421/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004422static void
4423CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4424 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004425
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004426 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004427 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004428
4429 // Perform checking for returned stack addresses, local blocks,
4430 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004431 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004432 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004433 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004434 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004435 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004436 }
4437
4438 if (stackE == 0)
4439 return; // Nothing suspicious was found.
4440
4441 SourceLocation diagLoc;
4442 SourceRange diagRange;
4443 if (refVars.empty()) {
4444 diagLoc = stackE->getLocStart();
4445 diagRange = stackE->getSourceRange();
4446 } else {
4447 // We followed through a reference variable. 'stackE' contains the
4448 // problematic expression but we will warn at the return statement pointing
4449 // at the reference variable. We will later display the "trail" of
4450 // reference variables using notes.
4451 diagLoc = refVars[0]->getLocStart();
4452 diagRange = refVars[0]->getSourceRange();
4453 }
4454
4455 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004456 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004457 : diag::warn_ret_stack_addr)
4458 << DR->getDecl()->getDeclName() << diagRange;
4459 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004460 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004461 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004462 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004463 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004464 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4465 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004466 << diagRange;
4467 }
4468
4469 // Display the "trail" of reference variables that we followed until we
4470 // found the problematic expression using notes.
4471 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4472 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4473 // If this var binds to another reference var, show the range of the next
4474 // var, otherwise the var binds to the problematic expression, in which case
4475 // show the range of the expression.
4476 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4477 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004478 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4479 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004480 }
4481}
4482
4483/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4484/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004485/// to a location on the stack, a local block, an address of a label, or a
4486/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004487/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004488/// encounter a subexpression that (1) clearly does not lead to one of the
4489/// above problematic expressions (2) is something we cannot determine leads to
4490/// a problematic expression based on such local checking.
4491///
4492/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4493/// the expression that they point to. Such variables are added to the
4494/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004495///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004496/// EvalAddr processes expressions that are pointers that are used as
4497/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004498/// At the base case of the recursion is a check for the above problematic
4499/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004500///
4501/// This implementation handles:
4502///
4503/// * pointer-to-pointer casts
4504/// * implicit conversions from array references to pointers
4505/// * taking the address of fields
4506/// * arbitrary interplay between "&" and "*" operators
4507/// * pointer arithmetic from an address of a stack variable
4508/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004509static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4510 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004511 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004512 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004513
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004514 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004515 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004516 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004517 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004518 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004519
Peter Collingbourne91147592011-04-15 00:35:48 +00004520 E = E->IgnoreParens();
4521
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004522 // Our "symbolic interpreter" is just a dispatch off the currently
4523 // viewed AST node. We then recursively traverse the AST by calling
4524 // EvalAddr and EvalVal appropriately.
4525 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004526 case Stmt::DeclRefExprClass: {
4527 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4528
Richard Smith40f08eb2014-01-30 22:05:38 +00004529 // If we leave the immediate function, the lifetime isn't about to end.
4530 if (DR->refersToEnclosingLocal())
4531 return 0;
4532
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004533 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4534 // If this is a reference variable, follow through to the expression that
4535 // it points to.
4536 if (V->hasLocalStorage() &&
4537 V->getType()->isReferenceType() && V->hasInit()) {
4538 // Add the reference variable to the "trail".
4539 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004540 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004541 }
4542
4543 return NULL;
4544 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004545
Chris Lattner934edb22007-12-28 05:31:15 +00004546 case Stmt::UnaryOperatorClass: {
4547 // The only unary operator that make sense to handle here
4548 // is AddrOf. All others don't make sense as pointers.
4549 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004550
John McCalle3027922010-08-25 11:45:40 +00004551 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004552 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004553 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004554 return NULL;
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Chris Lattner934edb22007-12-28 05:31:15 +00004557 case Stmt::BinaryOperatorClass: {
4558 // Handle pointer arithmetic. All other binary operators are not valid
4559 // in this context.
4560 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004561 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004562
John McCalle3027922010-08-25 11:45:40 +00004563 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004564 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chris Lattner934edb22007-12-28 05:31:15 +00004566 Expr *Base = B->getLHS();
4567
4568 // Determine which argument is the real pointer base. It could be
4569 // the RHS argument instead of the LHS.
4570 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004571
Chris Lattner934edb22007-12-28 05:31:15 +00004572 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004573 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004574 }
Steve Naroff2752a172008-09-10 19:17:48 +00004575
Chris Lattner934edb22007-12-28 05:31:15 +00004576 // For conditional operators we need to see if either the LHS or RHS are
4577 // valid DeclRefExpr*s. If one of them is valid, we return it.
4578 case Stmt::ConditionalOperatorClass: {
4579 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004580
Chris Lattner934edb22007-12-28 05:31:15 +00004581 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004582 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4583 if (Expr *LHSExpr = C->getLHS()) {
4584 // In C++, we can have a throw-expression, which has 'void' type.
4585 if (!LHSExpr->getType()->isVoidType())
4586 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004587 return LHS;
4588 }
Chris Lattner934edb22007-12-28 05:31:15 +00004589
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004590 // In C++, we can have a throw-expression, which has 'void' type.
4591 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004592 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004593
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004594 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004595 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004596
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004597 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004598 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004599 return E; // local block.
4600 return NULL;
4601
4602 case Stmt::AddrLabelExprClass:
4603 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004604
John McCall28fc7092011-11-10 05:35:25 +00004605 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004606 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4607 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004608
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004609 // For casts, we need to handle conversions from arrays to
4610 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004611 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004612 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004613 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004614 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004615 case Stmt::CXXStaticCastExprClass:
4616 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004617 case Stmt::CXXConstCastExprClass:
4618 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004619 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4620 switch (cast<CastExpr>(E)->getCastKind()) {
4621 case CK_BitCast:
4622 case CK_LValueToRValue:
4623 case CK_NoOp:
4624 case CK_BaseToDerived:
4625 case CK_DerivedToBase:
4626 case CK_UncheckedDerivedToBase:
4627 case CK_Dynamic:
4628 case CK_CPointerToObjCPointerCast:
4629 case CK_BlockPointerToObjCPointerCast:
4630 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004631 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004632
4633 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004634 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004635
4636 default:
4637 return 0;
4638 }
Chris Lattner934edb22007-12-28 05:31:15 +00004639 }
Mike Stump11289f42009-09-09 15:08:12 +00004640
Douglas Gregorfe314812011-06-21 17:03:29 +00004641 case Stmt::MaterializeTemporaryExprClass:
4642 if (Expr *Result = EvalAddr(
4643 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004644 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004645 return Result;
4646
4647 return E;
4648
Chris Lattner934edb22007-12-28 05:31:15 +00004649 // Everything else: we simply don't reason about them.
4650 default:
4651 return NULL;
4652 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004653}
Mike Stump11289f42009-09-09 15:08:12 +00004654
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004655
4656/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4657/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004658static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4659 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004660do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004661 // We should only be called for evaluating non-pointer expressions, or
4662 // expressions with a pointer type that are not used as references but instead
4663 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004664
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004665 // Our "symbolic interpreter" is just a dispatch off the currently
4666 // viewed AST node. We then recursively traverse the AST by calling
4667 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004668
4669 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004670 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004671 case Stmt::ImplicitCastExprClass: {
4672 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004673 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004674 E = IE->getSubExpr();
4675 continue;
4676 }
4677 return NULL;
4678 }
4679
John McCall28fc7092011-11-10 05:35:25 +00004680 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004681 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004682
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004683 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004684 // When we hit a DeclRefExpr we are looking at code that refers to a
4685 // variable's name. If it's not a reference variable we check if it has
4686 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004687 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004688
Richard Smith40f08eb2014-01-30 22:05:38 +00004689 // If we leave the immediate function, the lifetime isn't about to end.
4690 if (DR->refersToEnclosingLocal())
4691 return 0;
4692
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004693 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4694 // Check if it refers to itself, e.g. "int& i = i;".
4695 if (V == ParentDecl)
4696 return DR;
4697
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004698 if (V->hasLocalStorage()) {
4699 if (!V->getType()->isReferenceType())
4700 return DR;
4701
4702 // Reference variable, follow through to the expression that
4703 // it points to.
4704 if (V->hasInit()) {
4705 // Add the reference variable to the "trail".
4706 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004707 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004708 }
4709 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004710 }
Mike Stump11289f42009-09-09 15:08:12 +00004711
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004712 return NULL;
4713 }
Mike Stump11289f42009-09-09 15:08:12 +00004714
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004715 case Stmt::UnaryOperatorClass: {
4716 // The only unary operator that make sense to handle here
4717 // is Deref. All others don't resolve to a "name." This includes
4718 // handling all sorts of rvalues passed to a unary operator.
4719 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004720
John McCalle3027922010-08-25 11:45:40 +00004721 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004722 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004723
4724 return NULL;
4725 }
Mike Stump11289f42009-09-09 15:08:12 +00004726
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004727 case Stmt::ArraySubscriptExprClass: {
4728 // Array subscripts are potential references to data on the stack. We
4729 // retrieve the DeclRefExpr* for the array variable if it indeed
4730 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004731 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004732 }
Mike Stump11289f42009-09-09 15:08:12 +00004733
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004734 case Stmt::ConditionalOperatorClass: {
4735 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004736 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004737 ConditionalOperator *C = cast<ConditionalOperator>(E);
4738
Anders Carlsson801c5c72007-11-30 19:04:31 +00004739 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004740 if (Expr *LHSExpr = C->getLHS()) {
4741 // In C++, we can have a throw-expression, which has 'void' type.
4742 if (!LHSExpr->getType()->isVoidType())
4743 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4744 return LHS;
4745 }
4746
4747 // In C++, we can have a throw-expression, which has 'void' type.
4748 if (C->getRHS()->getType()->isVoidType())
4749 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004750
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004751 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004752 }
Mike Stump11289f42009-09-09 15:08:12 +00004753
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004754 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004755 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004756 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004757
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004758 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004759 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004760 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004761
4762 // Check whether the member type is itself a reference, in which case
4763 // we're not going to refer to the member, but to what the member refers to.
4764 if (M->getMemberDecl()->getType()->isReferenceType())
4765 return NULL;
4766
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004767 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004768 }
Mike Stump11289f42009-09-09 15:08:12 +00004769
Douglas Gregorfe314812011-06-21 17:03:29 +00004770 case Stmt::MaterializeTemporaryExprClass:
4771 if (Expr *Result = EvalVal(
4772 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004773 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004774 return Result;
4775
4776 return E;
4777
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004778 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004779 // Check that we don't return or take the address of a reference to a
4780 // temporary. This is only useful in C++.
4781 if (!E->isTypeDependent() && E->isRValue())
4782 return E;
4783
4784 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004785 return NULL;
4786 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004787} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004788}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004789
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004790void
4791Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4792 SourceLocation ReturnLoc,
4793 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004794 const AttrVec *Attrs,
4795 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004796 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4797
4798 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004799 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4800 CheckNonNullExpr(*this, RetValExp))
4801 Diag(ReturnLoc, diag::warn_null_ret)
4802 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004803
4804 // C++11 [basic.stc.dynamic.allocation]p4:
4805 // If an allocation function declared with a non-throwing
4806 // exception-specification fails to allocate storage, it shall return
4807 // a null pointer. Any other allocation function that fails to allocate
4808 // storage shall indicate failure only by throwing an exception [...]
4809 if (FD) {
4810 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4811 if (Op == OO_New || Op == OO_Array_New) {
4812 const FunctionProtoType *Proto
4813 = FD->getType()->castAs<FunctionProtoType>();
4814 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4815 CheckNonNullExpr(*this, RetValExp))
4816 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4817 << FD << getLangOpts().CPlusPlus11;
4818 }
4819 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004820}
4821
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004822//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4823
4824/// Check for comparisons of floating point operands using != and ==.
4825/// Issue a warning if these are no self-comparisons, as they are not likely
4826/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004827void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004828 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4829 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004830
4831 // Special case: check for x == x (which is OK).
4832 // Do not emit warnings for such cases.
4833 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4834 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4835 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004836 return;
Mike Stump11289f42009-09-09 15:08:12 +00004837
4838
Ted Kremenekeda40e22007-11-29 00:59:04 +00004839 // Special case: check for comparisons against literals that can be exactly
4840 // represented by APFloat. In such cases, do not emit a warning. This
4841 // is a heuristic: often comparison against such literals are used to
4842 // detect if a value in a variable has not changed. This clearly can
4843 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004844 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4845 if (FLL->isExact())
4846 return;
4847 } else
4848 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4849 if (FLR->isExact())
4850 return;
Mike Stump11289f42009-09-09 15:08:12 +00004851
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004852 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004853 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004854 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004855 return;
Mike Stump11289f42009-09-09 15:08:12 +00004856
David Blaikie1f4ff152012-07-16 20:47:22 +00004857 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004858 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004859 return;
Mike Stump11289f42009-09-09 15:08:12 +00004860
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004861 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004862 Diag(Loc, diag::warn_floatingpoint_eq)
4863 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004864}
John McCallca01b222010-01-04 23:21:16 +00004865
John McCall70aa5392010-01-06 05:24:50 +00004866//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4867//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004868
John McCall70aa5392010-01-06 05:24:50 +00004869namespace {
John McCallca01b222010-01-04 23:21:16 +00004870
John McCall70aa5392010-01-06 05:24:50 +00004871/// Structure recording the 'active' range of an integer-valued
4872/// expression.
4873struct IntRange {
4874 /// The number of bits active in the int.
4875 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004876
John McCall70aa5392010-01-06 05:24:50 +00004877 /// True if the int is known not to have negative values.
4878 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004879
John McCall70aa5392010-01-06 05:24:50 +00004880 IntRange(unsigned Width, bool NonNegative)
4881 : Width(Width), NonNegative(NonNegative)
4882 {}
John McCallca01b222010-01-04 23:21:16 +00004883
John McCall817d4af2010-11-10 23:38:19 +00004884 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004885 static IntRange forBoolType() {
4886 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004887 }
4888
John McCall817d4af2010-11-10 23:38:19 +00004889 /// Returns the range of an opaque value of the given integral type.
4890 static IntRange forValueOfType(ASTContext &C, QualType T) {
4891 return forValueOfCanonicalType(C,
4892 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004893 }
4894
John McCall817d4af2010-11-10 23:38:19 +00004895 /// Returns the range of an opaque value of a canonical integral type.
4896 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004897 assert(T->isCanonicalUnqualified());
4898
4899 if (const VectorType *VT = dyn_cast<VectorType>(T))
4900 T = VT->getElementType().getTypePtr();
4901 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4902 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004903
David Majnemer6a426652013-06-07 22:07:20 +00004904 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004905 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004906 EnumDecl *Enum = ET->getDecl();
4907 if (!Enum->isCompleteDefinition())
4908 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004909
David Majnemer6a426652013-06-07 22:07:20 +00004910 unsigned NumPositive = Enum->getNumPositiveBits();
4911 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004912
David Majnemer6a426652013-06-07 22:07:20 +00004913 if (NumNegative == 0)
4914 return IntRange(NumPositive, true/*NonNegative*/);
4915 else
4916 return IntRange(std::max(NumPositive + 1, NumNegative),
4917 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004918 }
John McCall70aa5392010-01-06 05:24:50 +00004919
4920 const BuiltinType *BT = cast<BuiltinType>(T);
4921 assert(BT->isInteger());
4922
4923 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4924 }
4925
John McCall817d4af2010-11-10 23:38:19 +00004926 /// Returns the "target" range of a canonical integral type, i.e.
4927 /// the range of values expressible in the type.
4928 ///
4929 /// This matches forValueOfCanonicalType except that enums have the
4930 /// full range of their type, not the range of their enumerators.
4931 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4932 assert(T->isCanonicalUnqualified());
4933
4934 if (const VectorType *VT = dyn_cast<VectorType>(T))
4935 T = VT->getElementType().getTypePtr();
4936 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4937 T = CT->getElementType().getTypePtr();
4938 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004939 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004940
4941 const BuiltinType *BT = cast<BuiltinType>(T);
4942 assert(BT->isInteger());
4943
4944 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4945 }
4946
4947 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004948 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004949 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004950 L.NonNegative && R.NonNegative);
4951 }
4952
John McCall817d4af2010-11-10 23:38:19 +00004953 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004954 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004955 return IntRange(std::min(L.Width, R.Width),
4956 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004957 }
4958};
4959
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004960static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4961 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004962 if (value.isSigned() && value.isNegative())
4963 return IntRange(value.getMinSignedBits(), false);
4964
4965 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004966 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004967
4968 // isNonNegative() just checks the sign bit without considering
4969 // signedness.
4970 return IntRange(value.getActiveBits(), true);
4971}
4972
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004973static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4974 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004975 if (result.isInt())
4976 return GetValueRange(C, result.getInt(), MaxWidth);
4977
4978 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004979 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4980 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4981 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4982 R = IntRange::join(R, El);
4983 }
John McCall70aa5392010-01-06 05:24:50 +00004984 return R;
4985 }
4986
4987 if (result.isComplexInt()) {
4988 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4989 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4990 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004991 }
4992
4993 // This can happen with lossless casts to intptr_t of "based" lvalues.
4994 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004995 // FIXME: The only reason we need to pass the type in here is to get
4996 // the sign right on this one case. It would be nice if APValue
4997 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004998 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004999 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005000}
John McCall70aa5392010-01-06 05:24:50 +00005001
Eli Friedmane6d33952013-07-08 20:20:06 +00005002static QualType GetExprType(Expr *E) {
5003 QualType Ty = E->getType();
5004 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5005 Ty = AtomicRHS->getValueType();
5006 return Ty;
5007}
5008
John McCall70aa5392010-01-06 05:24:50 +00005009/// Pseudo-evaluate the given integer expression, estimating the
5010/// range of values it might take.
5011///
5012/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005013static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005014 E = E->IgnoreParens();
5015
5016 // Try a full evaluation first.
5017 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005018 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005019 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005020
5021 // I think we only want to look through implicit casts here; if the
5022 // user has an explicit widening cast, we should treat the value as
5023 // being of the new, wider type.
5024 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005025 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005026 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5027
Eli Friedmane6d33952013-07-08 20:20:06 +00005028 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005029
John McCalle3027922010-08-25 11:45:40 +00005030 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005031
John McCall70aa5392010-01-06 05:24:50 +00005032 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005033 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005034 return OutputTypeRange;
5035
5036 IntRange SubRange
5037 = GetExprRange(C, CE->getSubExpr(),
5038 std::min(MaxWidth, OutputTypeRange.Width));
5039
5040 // Bail out if the subexpr's range is as wide as the cast type.
5041 if (SubRange.Width >= OutputTypeRange.Width)
5042 return OutputTypeRange;
5043
5044 // Otherwise, we take the smaller width, and we're non-negative if
5045 // either the output type or the subexpr is.
5046 return IntRange(SubRange.Width,
5047 SubRange.NonNegative || OutputTypeRange.NonNegative);
5048 }
5049
5050 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5051 // If we can fold the condition, just take that operand.
5052 bool CondResult;
5053 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5054 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5055 : CO->getFalseExpr(),
5056 MaxWidth);
5057
5058 // Otherwise, conservatively merge.
5059 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5060 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5061 return IntRange::join(L, R);
5062 }
5063
5064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5065 switch (BO->getOpcode()) {
5066
5067 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005068 case BO_LAnd:
5069 case BO_LOr:
5070 case BO_LT:
5071 case BO_GT:
5072 case BO_LE:
5073 case BO_GE:
5074 case BO_EQ:
5075 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005076 return IntRange::forBoolType();
5077
John McCallc3688382011-07-13 06:35:24 +00005078 // The type of the assignments is the type of the LHS, so the RHS
5079 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005080 case BO_MulAssign:
5081 case BO_DivAssign:
5082 case BO_RemAssign:
5083 case BO_AddAssign:
5084 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005085 case BO_XorAssign:
5086 case BO_OrAssign:
5087 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005088 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005089
John McCallc3688382011-07-13 06:35:24 +00005090 // Simple assignments just pass through the RHS, which will have
5091 // been coerced to the LHS type.
5092 case BO_Assign:
5093 // TODO: bitfields?
5094 return GetExprRange(C, BO->getRHS(), MaxWidth);
5095
John McCall70aa5392010-01-06 05:24:50 +00005096 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005097 case BO_PtrMemD:
5098 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005099 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005100
John McCall2ce81ad2010-01-06 22:07:33 +00005101 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005102 case BO_And:
5103 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005104 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5105 GetExprRange(C, BO->getRHS(), MaxWidth));
5106
John McCall70aa5392010-01-06 05:24:50 +00005107 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005108 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005109 // ...except that we want to treat '1 << (blah)' as logically
5110 // positive. It's an important idiom.
5111 if (IntegerLiteral *I
5112 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5113 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005114 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005115 return IntRange(R.Width, /*NonNegative*/ true);
5116 }
5117 }
5118 // fallthrough
5119
John McCalle3027922010-08-25 11:45:40 +00005120 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005121 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005122
John McCall2ce81ad2010-01-06 22:07:33 +00005123 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005124 case BO_Shr:
5125 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005126 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5127
5128 // If the shift amount is a positive constant, drop the width by
5129 // that much.
5130 llvm::APSInt shift;
5131 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5132 shift.isNonNegative()) {
5133 unsigned zext = shift.getZExtValue();
5134 if (zext >= L.Width)
5135 L.Width = (L.NonNegative ? 0 : 1);
5136 else
5137 L.Width -= zext;
5138 }
5139
5140 return L;
5141 }
5142
5143 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005144 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005145 return GetExprRange(C, BO->getRHS(), MaxWidth);
5146
John McCall2ce81ad2010-01-06 22:07:33 +00005147 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005148 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005149 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005150 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005151 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005152
John McCall51431812011-07-14 22:39:48 +00005153 // The width of a division result is mostly determined by the size
5154 // of the LHS.
5155 case BO_Div: {
5156 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005157 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005158 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5159
5160 // If the divisor is constant, use that.
5161 llvm::APSInt divisor;
5162 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5163 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5164 if (log2 >= L.Width)
5165 L.Width = (L.NonNegative ? 0 : 1);
5166 else
5167 L.Width = std::min(L.Width - log2, MaxWidth);
5168 return L;
5169 }
5170
5171 // Otherwise, just use the LHS's width.
5172 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5173 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5174 }
5175
5176 // The result of a remainder can't be larger than the result of
5177 // either side.
5178 case BO_Rem: {
5179 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005180 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005181 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5182 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5183
5184 IntRange meet = IntRange::meet(L, R);
5185 meet.Width = std::min(meet.Width, MaxWidth);
5186 return meet;
5187 }
5188
5189 // The default behavior is okay for these.
5190 case BO_Mul:
5191 case BO_Add:
5192 case BO_Xor:
5193 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005194 break;
5195 }
5196
John McCall51431812011-07-14 22:39:48 +00005197 // The default case is to treat the operation as if it were closed
5198 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005199 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5200 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5201 return IntRange::join(L, R);
5202 }
5203
5204 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5205 switch (UO->getOpcode()) {
5206 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005207 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005208 return IntRange::forBoolType();
5209
5210 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005211 case UO_Deref:
5212 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005213 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005214
5215 default:
5216 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5217 }
5218 }
5219
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005220 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5221 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5222
John McCalld25db7e2013-05-06 21:39:12 +00005223 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005224 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005225 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005226
Eli Friedmane6d33952013-07-08 20:20:06 +00005227 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005228}
John McCall263a48b2010-01-04 23:31:57 +00005229
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005230static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005231 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005232}
5233
John McCall263a48b2010-01-04 23:31:57 +00005234/// Checks whether the given value, which currently has the given
5235/// source semantics, has the same value when coerced through the
5236/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005237static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5238 const llvm::fltSemantics &Src,
5239 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005240 llvm::APFloat truncated = value;
5241
5242 bool ignored;
5243 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5244 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5245
5246 return truncated.bitwiseIsEqual(value);
5247}
5248
5249/// Checks whether the given value, which currently has the given
5250/// source semantics, has the same value when coerced through the
5251/// target semantics.
5252///
5253/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005254static bool IsSameFloatAfterCast(const APValue &value,
5255 const llvm::fltSemantics &Src,
5256 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005257 if (value.isFloat())
5258 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5259
5260 if (value.isVector()) {
5261 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5262 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5263 return false;
5264 return true;
5265 }
5266
5267 assert(value.isComplexFloat());
5268 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5269 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5270}
5271
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005272static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005273
Ted Kremenek6274be42010-09-23 21:43:44 +00005274static bool IsZero(Sema &S, Expr *E) {
5275 // Suppress cases where we are comparing against an enum constant.
5276 if (const DeclRefExpr *DR =
5277 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5278 if (isa<EnumConstantDecl>(DR->getDecl()))
5279 return false;
5280
5281 // Suppress cases where the '0' value is expanded from a macro.
5282 if (E->getLocStart().isMacroID())
5283 return false;
5284
John McCallcc7e5bf2010-05-06 08:58:33 +00005285 llvm::APSInt Value;
5286 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5287}
5288
John McCall2551c1b2010-10-06 00:25:24 +00005289static bool HasEnumType(Expr *E) {
5290 // Strip off implicit integral promotions.
5291 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005292 if (ICE->getCastKind() != CK_IntegralCast &&
5293 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005294 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005295 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005296 }
5297
5298 return E->getType()->isEnumeralType();
5299}
5300
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005301static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005302 // Disable warning in template instantiations.
5303 if (!S.ActiveTemplateInstantiations.empty())
5304 return;
5305
John McCalle3027922010-08-25 11:45:40 +00005306 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005307 if (E->isValueDependent())
5308 return;
5309
John McCalle3027922010-08-25 11:45:40 +00005310 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005311 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005312 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005313 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005314 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005315 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005316 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005317 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005318 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005319 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005320 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005321 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005322 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005323 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005324 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005325 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5326 }
5327}
5328
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005329static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005330 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005331 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005332 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005333 // Disable warning in template instantiations.
5334 if (!S.ActiveTemplateInstantiations.empty())
5335 return;
5336
Richard Trieu0f097742014-04-04 04:13:47 +00005337 // TODO: Investigate using GetExprRange() to get tighter bounds
5338 // on the bit ranges.
5339 QualType OtherT = Other->getType();
5340 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5341 unsigned OtherWidth = OtherRange.Width;
5342
5343 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5344
Richard Trieu560910c2012-11-14 22:50:24 +00005345 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005346 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005347 return;
5348
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005349 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005350 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005351
Richard Trieu0f097742014-04-04 04:13:47 +00005352 // Used for diagnostic printout.
5353 enum {
5354 LiteralConstant = 0,
5355 CXXBoolLiteralTrue,
5356 CXXBoolLiteralFalse
5357 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005358
Richard Trieu0f097742014-04-04 04:13:47 +00005359 if (!OtherIsBooleanType) {
5360 QualType ConstantT = Constant->getType();
5361 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005362
Richard Trieu0f097742014-04-04 04:13:47 +00005363 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5364 return;
5365 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5366 "comparison with non-integer type");
5367
5368 bool ConstantSigned = ConstantT->isSignedIntegerType();
5369 bool CommonSigned = CommonT->isSignedIntegerType();
5370
5371 bool EqualityOnly = false;
5372
5373 if (CommonSigned) {
5374 // The common type is signed, therefore no signed to unsigned conversion.
5375 if (!OtherRange.NonNegative) {
5376 // Check that the constant is representable in type OtherT.
5377 if (ConstantSigned) {
5378 if (OtherWidth >= Value.getMinSignedBits())
5379 return;
5380 } else { // !ConstantSigned
5381 if (OtherWidth >= Value.getActiveBits() + 1)
5382 return;
5383 }
5384 } else { // !OtherSigned
5385 // Check that the constant is representable in type OtherT.
5386 // Negative values are out of range.
5387 if (ConstantSigned) {
5388 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5389 return;
5390 } else { // !ConstantSigned
5391 if (OtherWidth >= Value.getActiveBits())
5392 return;
5393 }
Richard Trieu560910c2012-11-14 22:50:24 +00005394 }
Richard Trieu0f097742014-04-04 04:13:47 +00005395 } else { // !CommonSigned
5396 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005397 if (OtherWidth >= Value.getActiveBits())
5398 return;
Richard Trieu0f097742014-04-04 04:13:47 +00005399 } else if (!OtherRange.NonNegative && !ConstantSigned) {
5400 // Check to see if the constant is representable in OtherT.
5401 if (OtherWidth > Value.getActiveBits())
5402 return;
5403 // Check to see if the constant is equivalent to a negative value
5404 // cast to CommonT.
5405 if (S.Context.getIntWidth(ConstantT) ==
5406 S.Context.getIntWidth(CommonT) &&
5407 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5408 return;
5409 // The constant value rests between values that OtherT can represent
5410 // after conversion. Relational comparison still works, but equality
5411 // comparisons will be tautological.
5412 EqualityOnly = true;
5413 } else { // OtherSigned && ConstantSigned
5414 assert(0 && "Two signed types converted to unsigned types.");
Richard Trieu560910c2012-11-14 22:50:24 +00005415 }
5416 }
Richard Trieu0f097742014-04-04 04:13:47 +00005417
5418 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5419
5420 if (op == BO_EQ || op == BO_NE) {
5421 IsTrue = op == BO_NE;
5422 } else if (EqualityOnly) {
5423 return;
5424 } else if (RhsConstant) {
5425 if (op == BO_GT || op == BO_GE)
5426 IsTrue = !PositiveConstant;
5427 else // op == BO_LT || op == BO_LE
5428 IsTrue = PositiveConstant;
5429 } else {
5430 if (op == BO_LT || op == BO_LE)
5431 IsTrue = !PositiveConstant;
5432 else // op == BO_GT || op == BO_GE
5433 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005434 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005435 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005436 // Other isKnownToHaveBooleanValue
5437 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5438 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5439 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5440
5441 static const struct LinkedConditions {
5442 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5443 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5444 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5445 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5446 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5447 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5448
5449 } TruthTable = {
5450 // Constant on LHS. | Constant on RHS. |
5451 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5452 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5453 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5454 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5455 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5456 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5457 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5458 };
5459
5460 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5461
5462 enum ConstantValue ConstVal = Zero;
5463 if (Value.isUnsigned() || Value.isNonNegative()) {
5464 if (Value == 0) {
5465 LiteralOrBoolConstant =
5466 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5467 ConstVal = Zero;
5468 } else if (Value == 1) {
5469 LiteralOrBoolConstant =
5470 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5471 ConstVal = One;
5472 } else {
5473 LiteralOrBoolConstant = LiteralConstant;
5474 ConstVal = GT_One;
5475 }
5476 } else {
5477 ConstVal = LT_Zero;
5478 }
5479
5480 CompareBoolWithConstantResult CmpRes;
5481
5482 switch (op) {
5483 case BO_LT:
5484 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5485 break;
5486 case BO_GT:
5487 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5488 break;
5489 case BO_LE:
5490 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5491 break;
5492 case BO_GE:
5493 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5494 break;
5495 case BO_EQ:
5496 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5497 break;
5498 case BO_NE:
5499 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5500 break;
5501 default:
5502 CmpRes = Unkwn;
5503 break;
5504 }
5505
5506 if (CmpRes == AFals) {
5507 IsTrue = false;
5508 } else if (CmpRes == ATrue) {
5509 IsTrue = true;
5510 } else {
5511 return;
5512 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005513 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005514
5515 // If this is a comparison to an enum constant, include that
5516 // constant in the diagnostic.
5517 const EnumConstantDecl *ED = 0;
5518 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5519 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5520
5521 SmallString<64> PrettySourceValue;
5522 llvm::raw_svector_ostream OS(PrettySourceValue);
5523 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005524 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005525 else
5526 OS << Value;
5527
Richard Trieu0f097742014-04-04 04:13:47 +00005528 S.DiagRuntimeBehavior(
5529 E->getOperatorLoc(), E,
5530 S.PDiag(diag::warn_out_of_range_compare)
5531 << OS.str() << LiteralOrBoolConstant
5532 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5533 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005534}
5535
John McCallcc7e5bf2010-05-06 08:58:33 +00005536/// Analyze the operands of the given comparison. Implements the
5537/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005538static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005539 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5540 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005541}
John McCall263a48b2010-01-04 23:31:57 +00005542
John McCallca01b222010-01-04 23:21:16 +00005543/// \brief Implements -Wsign-compare.
5544///
Richard Trieu82402a02011-09-15 21:56:47 +00005545/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005546static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005547 // The type the comparison is being performed in.
5548 QualType T = E->getLHS()->getType();
5549 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5550 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005551 if (E->isValueDependent())
5552 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005553
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005554 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5555 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005556
5557 bool IsComparisonConstant = false;
5558
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005559 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005560 // of 'true' or 'false'.
5561 if (T->isIntegralType(S.Context)) {
5562 llvm::APSInt RHSValue;
5563 bool IsRHSIntegralLiteral =
5564 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5565 llvm::APSInt LHSValue;
5566 bool IsLHSIntegralLiteral =
5567 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5568 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5569 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5570 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5571 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5572 else
5573 IsComparisonConstant =
5574 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005575 } else if (!T->hasUnsignedIntegerRepresentation())
5576 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005577
John McCallcc7e5bf2010-05-06 08:58:33 +00005578 // We don't do anything special if this isn't an unsigned integral
5579 // comparison: we're only interested in integral comparisons, and
5580 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005581 //
5582 // We also don't care about value-dependent expressions or expressions
5583 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005584 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005585 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005586
John McCallcc7e5bf2010-05-06 08:58:33 +00005587 // Check to see if one of the (unmodified) operands is of different
5588 // signedness.
5589 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005590 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5591 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005592 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005593 signedOperand = LHS;
5594 unsignedOperand = RHS;
5595 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5596 signedOperand = RHS;
5597 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005598 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005599 CheckTrivialUnsignedComparison(S, E);
5600 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005601 }
5602
John McCallcc7e5bf2010-05-06 08:58:33 +00005603 // Otherwise, calculate the effective range of the signed operand.
5604 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005605
John McCallcc7e5bf2010-05-06 08:58:33 +00005606 // Go ahead and analyze implicit conversions in the operands. Note
5607 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005608 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5609 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005610
John McCallcc7e5bf2010-05-06 08:58:33 +00005611 // If the signed range is non-negative, -Wsign-compare won't fire,
5612 // but we should still check for comparisons which are always true
5613 // or false.
5614 if (signedRange.NonNegative)
5615 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005616
5617 // For (in)equality comparisons, if the unsigned operand is a
5618 // constant which cannot collide with a overflowed signed operand,
5619 // then reinterpreting the signed operand as unsigned will not
5620 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005621 if (E->isEqualityOp()) {
5622 unsigned comparisonWidth = S.Context.getIntWidth(T);
5623 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005624
John McCallcc7e5bf2010-05-06 08:58:33 +00005625 // We should never be unable to prove that the unsigned operand is
5626 // non-negative.
5627 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5628
5629 if (unsignedRange.Width < comparisonWidth)
5630 return;
5631 }
5632
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005633 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5634 S.PDiag(diag::warn_mixed_sign_comparison)
5635 << LHS->getType() << RHS->getType()
5636 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005637}
5638
John McCall1f425642010-11-11 03:21:53 +00005639/// Analyzes an attempt to assign the given value to a bitfield.
5640///
5641/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005642static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5643 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005644 assert(Bitfield->isBitField());
5645 if (Bitfield->isInvalidDecl())
5646 return false;
5647
John McCalldeebbcf2010-11-11 05:33:51 +00005648 // White-list bool bitfields.
5649 if (Bitfield->getType()->isBooleanType())
5650 return false;
5651
Douglas Gregor789adec2011-02-04 13:09:01 +00005652 // Ignore value- or type-dependent expressions.
5653 if (Bitfield->getBitWidth()->isValueDependent() ||
5654 Bitfield->getBitWidth()->isTypeDependent() ||
5655 Init->isValueDependent() ||
5656 Init->isTypeDependent())
5657 return false;
5658
John McCall1f425642010-11-11 03:21:53 +00005659 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5660
Richard Smith5fab0c92011-12-28 19:48:30 +00005661 llvm::APSInt Value;
5662 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005663 return false;
5664
John McCall1f425642010-11-11 03:21:53 +00005665 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005666 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005667
5668 if (OriginalWidth <= FieldWidth)
5669 return false;
5670
Eli Friedmanc267a322012-01-26 23:11:39 +00005671 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005672 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005673 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005674
Eli Friedmanc267a322012-01-26 23:11:39 +00005675 // Check whether the stored value is equal to the original value.
5676 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005677 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005678 return false;
5679
Eli Friedmanc267a322012-01-26 23:11:39 +00005680 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005681 // therefore don't strictly fit into a signed bitfield of width 1.
5682 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005683 return false;
5684
John McCall1f425642010-11-11 03:21:53 +00005685 std::string PrettyValue = Value.toString(10);
5686 std::string PrettyTrunc = TruncatedValue.toString(10);
5687
5688 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5689 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5690 << Init->getSourceRange();
5691
5692 return true;
5693}
5694
John McCalld2a53122010-11-09 23:24:47 +00005695/// Analyze the given simple or compound assignment for warning-worthy
5696/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005697static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005698 // Just recurse on the LHS.
5699 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5700
5701 // We want to recurse on the RHS as normal unless we're assigning to
5702 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005703 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005704 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005705 E->getOperatorLoc())) {
5706 // Recurse, ignoring any implicit conversions on the RHS.
5707 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5708 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005709 }
5710 }
5711
5712 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5713}
5714
John McCall263a48b2010-01-04 23:31:57 +00005715/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005716static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005717 SourceLocation CContext, unsigned diag,
5718 bool pruneControlFlow = false) {
5719 if (pruneControlFlow) {
5720 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5721 S.PDiag(diag)
5722 << SourceType << T << E->getSourceRange()
5723 << SourceRange(CContext));
5724 return;
5725 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005726 S.Diag(E->getExprLoc(), diag)
5727 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5728}
5729
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005730/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005731static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005732 SourceLocation CContext, unsigned diag,
5733 bool pruneControlFlow = false) {
5734 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005735}
5736
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005737/// Diagnose an implicit cast from a literal expression. Does not warn when the
5738/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005739void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5740 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005741 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005742 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005743 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005744 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5745 T->hasUnsignedIntegerRepresentation());
5746 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005747 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005748 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005749 return;
5750
Eli Friedman07185912013-08-29 23:44:43 +00005751 // FIXME: Force the precision of the source value down so we don't print
5752 // digits which are usually useless (we don't really care here if we
5753 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5754 // would automatically print the shortest representation, but it's a bit
5755 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005756 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005757 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5758 precision = (precision * 59 + 195) / 196;
5759 Value.toString(PrettySourceValue, precision);
5760
David Blaikie9b88cc02012-05-15 17:18:27 +00005761 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005762 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5763 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5764 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005765 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005766
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005767 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005768 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5769 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005770}
5771
John McCall18a2c2c2010-11-09 22:22:12 +00005772std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5773 if (!Range.Width) return "0";
5774
5775 llvm::APSInt ValueInRange = Value;
5776 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005777 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005778 return ValueInRange.toString(10);
5779}
5780
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005781static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5782 if (!isa<ImplicitCastExpr>(Ex))
5783 return false;
5784
5785 Expr *InnerE = Ex->IgnoreParenImpCasts();
5786 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5787 const Type *Source =
5788 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5789 if (Target->isDependentType())
5790 return false;
5791
5792 const BuiltinType *FloatCandidateBT =
5793 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5794 const Type *BoolCandidateType = ToBool ? Target : Source;
5795
5796 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5797 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5798}
5799
5800void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5801 SourceLocation CC) {
5802 unsigned NumArgs = TheCall->getNumArgs();
5803 for (unsigned i = 0; i < NumArgs; ++i) {
5804 Expr *CurrA = TheCall->getArg(i);
5805 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5806 continue;
5807
5808 bool IsSwapped = ((i > 0) &&
5809 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5810 IsSwapped |= ((i < (NumArgs - 1)) &&
5811 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5812 if (IsSwapped) {
5813 // Warn on this floating-point to bool conversion.
5814 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5815 CurrA->getType(), CC,
5816 diag::warn_impcast_floating_point_to_bool);
5817 }
5818 }
5819}
5820
John McCallcc7e5bf2010-05-06 08:58:33 +00005821void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005822 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005823 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005824
John McCallcc7e5bf2010-05-06 08:58:33 +00005825 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5826 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5827 if (Source == Target) return;
5828 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005829
Chandler Carruthc22845a2011-07-26 05:40:03 +00005830 // If the conversion context location is invalid don't complain. We also
5831 // don't want to emit a warning if the issue occurs from the expansion of
5832 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5833 // delay this check as long as possible. Once we detect we are in that
5834 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005835 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005836 return;
5837
Richard Trieu021baa32011-09-23 20:10:00 +00005838 // Diagnose implicit casts to bool.
5839 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5840 if (isa<StringLiteral>(E))
5841 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005842 // and expressions, for instance, assert(0 && "error here"), are
5843 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005844 return DiagnoseImpCast(S, E, T, CC,
5845 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005846 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5847 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5848 // This covers the literal expressions that evaluate to Objective-C
5849 // objects.
5850 return DiagnoseImpCast(S, E, T, CC,
5851 diag::warn_impcast_objective_c_literal_to_bool);
5852 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005853 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5854 // Warn on pointer to bool conversion that is always true.
5855 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5856 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005857 }
Richard Trieu021baa32011-09-23 20:10:00 +00005858 }
John McCall263a48b2010-01-04 23:31:57 +00005859
5860 // Strip vector types.
5861 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005862 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005863 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005864 return;
John McCallacf0ee52010-10-08 02:01:28 +00005865 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005866 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005867
5868 // If the vector cast is cast between two vectors of the same size, it is
5869 // a bitcast, not a conversion.
5870 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5871 return;
John McCall263a48b2010-01-04 23:31:57 +00005872
5873 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5874 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5875 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005876 if (auto VecTy = dyn_cast<VectorType>(Target))
5877 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005878
5879 // Strip complex types.
5880 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005881 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005882 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005883 return;
5884
John McCallacf0ee52010-10-08 02:01:28 +00005885 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005886 }
John McCall263a48b2010-01-04 23:31:57 +00005887
5888 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5889 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5890 }
5891
5892 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5893 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5894
5895 // If the source is floating point...
5896 if (SourceBT && SourceBT->isFloatingPoint()) {
5897 // ...and the target is floating point...
5898 if (TargetBT && TargetBT->isFloatingPoint()) {
5899 // ...then warn if we're dropping FP rank.
5900
5901 // Builtin FP kinds are ordered by increasing FP rank.
5902 if (SourceBT->getKind() > TargetBT->getKind()) {
5903 // Don't warn about float constants that are precisely
5904 // representable in the target type.
5905 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005906 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005907 // Value might be a float, a float vector, or a float complex.
5908 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005909 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5910 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005911 return;
5912 }
5913
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005914 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005915 return;
5916
John McCallacf0ee52010-10-08 02:01:28 +00005917 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005918 }
5919 return;
5920 }
5921
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005922 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005923 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005924 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005925 return;
5926
Chandler Carruth22c7a792011-02-17 11:05:49 +00005927 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005928 // We also want to warn on, e.g., "int i = -1.234"
5929 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5930 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5931 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5932
Chandler Carruth016ef402011-04-10 08:36:24 +00005933 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5934 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005935 } else {
5936 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5937 }
5938 }
John McCall263a48b2010-01-04 23:31:57 +00005939
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005940 // If the target is bool, warn if expr is a function or method call.
5941 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5942 isa<CallExpr>(E)) {
5943 // Check last argument of function call to see if it is an
5944 // implicit cast from a type matching the type the result
5945 // is being cast to.
5946 CallExpr *CEx = cast<CallExpr>(E);
5947 unsigned NumArgs = CEx->getNumArgs();
5948 if (NumArgs > 0) {
5949 Expr *LastA = CEx->getArg(NumArgs - 1);
5950 Expr *InnerE = LastA->IgnoreParenImpCasts();
5951 const Type *InnerType =
5952 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5953 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5954 // Warn on this floating-point to bool conversion
5955 DiagnoseImpCast(S, E, T, CC,
5956 diag::warn_impcast_floating_point_to_bool);
5957 }
5958 }
5959 }
John McCall263a48b2010-01-04 23:31:57 +00005960 return;
5961 }
5962
Richard Trieubeaf3452011-05-29 19:59:02 +00005963 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005964 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005965 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005966 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005967 SourceLocation Loc = E->getSourceRange().getBegin();
5968 if (Loc.isMacroID())
5969 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005970 if (!Loc.isMacroID() || CC.isMacroID())
5971 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5972 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005973 << FixItHint::CreateReplacement(Loc,
5974 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005975 }
5976
David Blaikie9366d2b2012-06-19 21:19:06 +00005977 if (!Source->isIntegerType() || !Target->isIntegerType())
5978 return;
5979
David Blaikie7555b6a2012-05-15 16:56:36 +00005980 // TODO: remove this early return once the false positives for constant->bool
5981 // in templates, macros, etc, are reduced or removed.
5982 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5983 return;
5984
John McCallcc7e5bf2010-05-06 08:58:33 +00005985 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005986 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005987
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005988 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005989 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005990 // TODO: this should happen for bitfield stores, too.
5991 llvm::APSInt Value(32);
5992 if (E->isIntegerConstantExpr(Value, S.Context)) {
5993 if (S.SourceMgr.isInSystemMacro(CC))
5994 return;
5995
John McCall18a2c2c2010-11-09 22:22:12 +00005996 std::string PrettySourceValue = Value.toString(10);
5997 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005998
Ted Kremenek33ba9952011-10-22 02:37:33 +00005999 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6000 S.PDiag(diag::warn_impcast_integer_precision_constant)
6001 << PrettySourceValue << PrettyTargetValue
6002 << E->getType() << T << E->getSourceRange()
6003 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006004 return;
6005 }
6006
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006007 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6008 if (S.SourceMgr.isInSystemMacro(CC))
6009 return;
6010
David Blaikie9455da02012-04-12 22:40:54 +00006011 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006012 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6013 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006014 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006015 }
6016
6017 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6018 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6019 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006020
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006021 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006022 return;
6023
John McCallcc7e5bf2010-05-06 08:58:33 +00006024 unsigned DiagID = diag::warn_impcast_integer_sign;
6025
6026 // Traditionally, gcc has warned about this under -Wsign-compare.
6027 // We also want to warn about it in -Wconversion.
6028 // So if -Wconversion is off, use a completely identical diagnostic
6029 // in the sign-compare group.
6030 // The conditional-checking code will
6031 if (ICContext) {
6032 DiagID = diag::warn_impcast_integer_sign_conditional;
6033 *ICContext = true;
6034 }
6035
John McCallacf0ee52010-10-08 02:01:28 +00006036 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006037 }
6038
Douglas Gregora78f1932011-02-22 02:45:07 +00006039 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006040 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6041 // type, to give us better diagnostics.
6042 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006043 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006044 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6045 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6046 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6047 SourceType = S.Context.getTypeDeclType(Enum);
6048 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6049 }
6050 }
6051
Douglas Gregora78f1932011-02-22 02:45:07 +00006052 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6053 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006054 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6055 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006056 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006057 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006058 return;
6059
Douglas Gregor364f7db2011-03-12 00:14:31 +00006060 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006061 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006062 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006063
John McCall263a48b2010-01-04 23:31:57 +00006064 return;
6065}
6066
David Blaikie18e9ac72012-05-15 21:57:38 +00006067void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6068 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006069
6070void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006071 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006072 E = E->IgnoreParenImpCasts();
6073
6074 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006075 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006076
John McCallacf0ee52010-10-08 02:01:28 +00006077 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006078 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006079 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006080 return;
6081}
6082
David Blaikie18e9ac72012-05-15 21:57:38 +00006083void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6084 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006085 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006086
6087 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006088 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6089 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006090
6091 // If -Wconversion would have warned about either of the candidates
6092 // for a signedness conversion to the context type...
6093 if (!Suspicious) return;
6094
6095 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006096 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6097 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006098 return;
6099
John McCallcc7e5bf2010-05-06 08:58:33 +00006100 // ...then check whether it would have warned about either of the
6101 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006102 if (E->getType() == T) return;
6103
6104 Suspicious = false;
6105 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6106 E->getType(), CC, &Suspicious);
6107 if (!Suspicious)
6108 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006109 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006110}
6111
6112/// AnalyzeImplicitConversions - Find and report any interesting
6113/// implicit conversions in the given expression. There are a couple
6114/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006115void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006116 QualType T = OrigE->getType();
6117 Expr *E = OrigE->IgnoreParenImpCasts();
6118
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006119 if (E->isTypeDependent() || E->isValueDependent())
6120 return;
6121
John McCallcc7e5bf2010-05-06 08:58:33 +00006122 // For conditional operators, we analyze the arguments as if they
6123 // were being fed directly into the output.
6124 if (isa<ConditionalOperator>(E)) {
6125 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006126 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006127 return;
6128 }
6129
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006130 // Check implicit argument conversions for function calls.
6131 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6132 CheckImplicitArgumentConversions(S, Call, CC);
6133
John McCallcc7e5bf2010-05-06 08:58:33 +00006134 // Go ahead and check any implicit conversions we might have skipped.
6135 // The non-canonical typecheck is just an optimization;
6136 // CheckImplicitConversion will filter out dead implicit conversions.
6137 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006138 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006139
6140 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006141
6142 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006143 if (POE->getResultExpr())
6144 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006145 }
6146
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006147 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6148 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6149
John McCallcc7e5bf2010-05-06 08:58:33 +00006150 // Skip past explicit casts.
6151 if (isa<ExplicitCastExpr>(E)) {
6152 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006153 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006154 }
6155
John McCalld2a53122010-11-09 23:24:47 +00006156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6157 // Do a somewhat different check with comparison operators.
6158 if (BO->isComparisonOp())
6159 return AnalyzeComparison(S, BO);
6160
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006161 // And with simple assignments.
6162 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006163 return AnalyzeAssignment(S, BO);
6164 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006165
6166 // These break the otherwise-useful invariant below. Fortunately,
6167 // we don't really need to recurse into them, because any internal
6168 // expressions should have been analyzed already when they were
6169 // built into statements.
6170 if (isa<StmtExpr>(E)) return;
6171
6172 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006173 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006174
6175 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006176 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006177 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006178 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006179 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006180 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006181 if (!ChildExpr)
6182 continue;
6183
Richard Trieu955231d2014-01-25 01:10:35 +00006184 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006185 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006186 // Ignore checking string literals that are in logical and operators.
6187 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006188 continue;
6189 AnalyzeImplicitConversions(S, ChildExpr, CC);
6190 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006191}
6192
6193} // end anonymous namespace
6194
Richard Trieu3bb8b562014-02-26 02:36:06 +00006195enum {
6196 AddressOf,
6197 FunctionPointer,
6198 ArrayPointer
6199};
6200
6201/// \brief Diagnose pointers that are always non-null.
6202/// \param E the expression containing the pointer
6203/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6204/// compared to a null pointer
6205/// \param IsEqual True when the comparison is equal to a null pointer
6206/// \param Range Extra SourceRange to highlight in the diagnostic
6207void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6208 Expr::NullPointerConstantKind NullKind,
6209 bool IsEqual, SourceRange Range) {
6210
6211 // Don't warn inside macros.
6212 if (E->getExprLoc().isMacroID())
6213 return;
6214 E = E->IgnoreImpCasts();
6215
6216 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6217
6218 bool IsAddressOf = false;
6219
6220 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6221 if (UO->getOpcode() != UO_AddrOf)
6222 return;
6223 IsAddressOf = true;
6224 E = UO->getSubExpr();
6225 }
6226
6227 // Expect to find a single Decl. Skip anything more complicated.
6228 ValueDecl *D = 0;
6229 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6230 D = R->getDecl();
6231 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6232 D = M->getMemberDecl();
6233 }
6234
6235 // Weak Decls can be null.
6236 if (!D || D->isWeak())
6237 return;
6238
6239 QualType T = D->getType();
6240 const bool IsArray = T->isArrayType();
6241 const bool IsFunction = T->isFunctionType();
6242
6243 if (IsAddressOf) {
6244 // Address of function is used to silence the function warning.
6245 if (IsFunction)
6246 return;
6247 // Address of reference can be null.
6248 if (T->isReferenceType())
6249 return;
6250 }
6251
6252 // Found nothing.
6253 if (!IsAddressOf && !IsFunction && !IsArray)
6254 return;
6255
6256 // Pretty print the expression for the diagnostic.
6257 std::string Str;
6258 llvm::raw_string_ostream S(Str);
6259 E->printPretty(S, 0, getPrintingPolicy());
6260
6261 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6262 : diag::warn_impcast_pointer_to_bool;
6263 unsigned DiagType;
6264 if (IsAddressOf)
6265 DiagType = AddressOf;
6266 else if (IsFunction)
6267 DiagType = FunctionPointer;
6268 else if (IsArray)
6269 DiagType = ArrayPointer;
6270 else
6271 llvm_unreachable("Could not determine diagnostic.");
6272 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6273 << Range << IsEqual;
6274
6275 if (!IsFunction)
6276 return;
6277
6278 // Suggest '&' to silence the function warning.
6279 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6280 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6281
6282 // Check to see if '()' fixit should be emitted.
6283 QualType ReturnType;
6284 UnresolvedSet<4> NonTemplateOverloads;
6285 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6286 if (ReturnType.isNull())
6287 return;
6288
6289 if (IsCompare) {
6290 // There are two cases here. If there is null constant, the only suggest
6291 // for a pointer return type. If the null is 0, then suggest if the return
6292 // type is a pointer or an integer type.
6293 if (!ReturnType->isPointerType()) {
6294 if (NullKind == Expr::NPCK_ZeroExpression ||
6295 NullKind == Expr::NPCK_ZeroLiteral) {
6296 if (!ReturnType->isIntegerType())
6297 return;
6298 } else {
6299 return;
6300 }
6301 }
6302 } else { // !IsCompare
6303 // For function to bool, only suggest if the function pointer has bool
6304 // return type.
6305 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6306 return;
6307 }
6308 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6309 << FixItHint::CreateInsertion(
6310 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6311}
6312
6313
John McCallcc7e5bf2010-05-06 08:58:33 +00006314/// Diagnoses "dangerous" implicit conversions within the given
6315/// expression (which is a full expression). Implements -Wconversion
6316/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006317///
6318/// \param CC the "context" location of the implicit conversion, i.e.
6319/// the most location of the syntactic entity requiring the implicit
6320/// conversion
6321void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006322 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006323 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006324 return;
6325
6326 // Don't diagnose for value- or type-dependent expressions.
6327 if (E->isTypeDependent() || E->isValueDependent())
6328 return;
6329
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006330 // Check for array bounds violations in cases where the check isn't triggered
6331 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6332 // ArraySubscriptExpr is on the RHS of a variable initialization.
6333 CheckArrayAccess(E);
6334
John McCallacf0ee52010-10-08 02:01:28 +00006335 // This is not the right CC for (e.g.) a variable initialization.
6336 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006337}
6338
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006339/// Diagnose when expression is an integer constant expression and its evaluation
6340/// results in integer overflow
6341void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006342 if (isa<BinaryOperator>(E->IgnoreParens()))
6343 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006344}
6345
Richard Smithc406cb72013-01-17 01:17:56 +00006346namespace {
6347/// \brief Visitor for expressions which looks for unsequenced operations on the
6348/// same object.
6349class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006350 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6351
Richard Smithc406cb72013-01-17 01:17:56 +00006352 /// \brief A tree of sequenced regions within an expression. Two regions are
6353 /// unsequenced if one is an ancestor or a descendent of the other. When we
6354 /// finish processing an expression with sequencing, such as a comma
6355 /// expression, we fold its tree nodes into its parent, since they are
6356 /// unsequenced with respect to nodes we will visit later.
6357 class SequenceTree {
6358 struct Value {
6359 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6360 unsigned Parent : 31;
6361 bool Merged : 1;
6362 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006363 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006364
6365 public:
6366 /// \brief A region within an expression which may be sequenced with respect
6367 /// to some other region.
6368 class Seq {
6369 explicit Seq(unsigned N) : Index(N) {}
6370 unsigned Index;
6371 friend class SequenceTree;
6372 public:
6373 Seq() : Index(0) {}
6374 };
6375
6376 SequenceTree() { Values.push_back(Value(0)); }
6377 Seq root() const { return Seq(0); }
6378
6379 /// \brief Create a new sequence of operations, which is an unsequenced
6380 /// subset of \p Parent. This sequence of operations is sequenced with
6381 /// respect to other children of \p Parent.
6382 Seq allocate(Seq Parent) {
6383 Values.push_back(Value(Parent.Index));
6384 return Seq(Values.size() - 1);
6385 }
6386
6387 /// \brief Merge a sequence of operations into its parent.
6388 void merge(Seq S) {
6389 Values[S.Index].Merged = true;
6390 }
6391
6392 /// \brief Determine whether two operations are unsequenced. This operation
6393 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6394 /// should have been merged into its parent as appropriate.
6395 bool isUnsequenced(Seq Cur, Seq Old) {
6396 unsigned C = representative(Cur.Index);
6397 unsigned Target = representative(Old.Index);
6398 while (C >= Target) {
6399 if (C == Target)
6400 return true;
6401 C = Values[C].Parent;
6402 }
6403 return false;
6404 }
6405
6406 private:
6407 /// \brief Pick a representative for a sequence.
6408 unsigned representative(unsigned K) {
6409 if (Values[K].Merged)
6410 // Perform path compression as we go.
6411 return Values[K].Parent = representative(Values[K].Parent);
6412 return K;
6413 }
6414 };
6415
6416 /// An object for which we can track unsequenced uses.
6417 typedef NamedDecl *Object;
6418
6419 /// Different flavors of object usage which we track. We only track the
6420 /// least-sequenced usage of each kind.
6421 enum UsageKind {
6422 /// A read of an object. Multiple unsequenced reads are OK.
6423 UK_Use,
6424 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006425 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006426 UK_ModAsValue,
6427 /// A modification of an object which is not sequenced before the value
6428 /// computation of the expression, such as n++.
6429 UK_ModAsSideEffect,
6430
6431 UK_Count = UK_ModAsSideEffect + 1
6432 };
6433
6434 struct Usage {
6435 Usage() : Use(0), Seq() {}
6436 Expr *Use;
6437 SequenceTree::Seq Seq;
6438 };
6439
6440 struct UsageInfo {
6441 UsageInfo() : Diagnosed(false) {}
6442 Usage Uses[UK_Count];
6443 /// Have we issued a diagnostic for this variable already?
6444 bool Diagnosed;
6445 };
6446 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6447
6448 Sema &SemaRef;
6449 /// Sequenced regions within the expression.
6450 SequenceTree Tree;
6451 /// Declaration modifications and references which we have seen.
6452 UsageInfoMap UsageMap;
6453 /// The region we are currently within.
6454 SequenceTree::Seq Region;
6455 /// Filled in with declarations which were modified as a side-effect
6456 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006457 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006458 /// Expressions to check later. We defer checking these to reduce
6459 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006460 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006461
6462 /// RAII object wrapping the visitation of a sequenced subexpression of an
6463 /// expression. At the end of this process, the side-effects of the evaluation
6464 /// become sequenced with respect to the value computation of the result, so
6465 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6466 /// UK_ModAsValue.
6467 struct SequencedSubexpression {
6468 SequencedSubexpression(SequenceChecker &Self)
6469 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6470 Self.ModAsSideEffect = &ModAsSideEffect;
6471 }
6472 ~SequencedSubexpression() {
6473 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6474 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6475 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6476 Self.addUsage(U, ModAsSideEffect[I].first,
6477 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6478 }
6479 Self.ModAsSideEffect = OldModAsSideEffect;
6480 }
6481
6482 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006483 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6484 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006485 };
6486
Richard Smith40238f02013-06-20 22:21:56 +00006487 /// RAII object wrapping the visitation of a subexpression which we might
6488 /// choose to evaluate as a constant. If any subexpression is evaluated and
6489 /// found to be non-constant, this allows us to suppress the evaluation of
6490 /// the outer expression.
6491 class EvaluationTracker {
6492 public:
6493 EvaluationTracker(SequenceChecker &Self)
6494 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6495 Self.EvalTracker = this;
6496 }
6497 ~EvaluationTracker() {
6498 Self.EvalTracker = Prev;
6499 if (Prev)
6500 Prev->EvalOK &= EvalOK;
6501 }
6502
6503 bool evaluate(const Expr *E, bool &Result) {
6504 if (!EvalOK || E->isValueDependent())
6505 return false;
6506 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6507 return EvalOK;
6508 }
6509
6510 private:
6511 SequenceChecker &Self;
6512 EvaluationTracker *Prev;
6513 bool EvalOK;
6514 } *EvalTracker;
6515
Richard Smithc406cb72013-01-17 01:17:56 +00006516 /// \brief Find the object which is produced by the specified expression,
6517 /// if any.
6518 Object getObject(Expr *E, bool Mod) const {
6519 E = E->IgnoreParenCasts();
6520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6521 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6522 return getObject(UO->getSubExpr(), Mod);
6523 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6524 if (BO->getOpcode() == BO_Comma)
6525 return getObject(BO->getRHS(), Mod);
6526 if (Mod && BO->isAssignmentOp())
6527 return getObject(BO->getLHS(), Mod);
6528 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6529 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6530 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6531 return ME->getMemberDecl();
6532 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6533 // FIXME: If this is a reference, map through to its value.
6534 return DRE->getDecl();
6535 return 0;
6536 }
6537
6538 /// \brief Note that an object was modified or used by an expression.
6539 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6540 Usage &U = UI.Uses[UK];
6541 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6542 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6543 ModAsSideEffect->push_back(std::make_pair(O, U));
6544 U.Use = Ref;
6545 U.Seq = Region;
6546 }
6547 }
6548 /// \brief Check whether a modification or use conflicts with a prior usage.
6549 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6550 bool IsModMod) {
6551 if (UI.Diagnosed)
6552 return;
6553
6554 const Usage &U = UI.Uses[OtherKind];
6555 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6556 return;
6557
6558 Expr *Mod = U.Use;
6559 Expr *ModOrUse = Ref;
6560 if (OtherKind == UK_Use)
6561 std::swap(Mod, ModOrUse);
6562
6563 SemaRef.Diag(Mod->getExprLoc(),
6564 IsModMod ? diag::warn_unsequenced_mod_mod
6565 : diag::warn_unsequenced_mod_use)
6566 << O << SourceRange(ModOrUse->getExprLoc());
6567 UI.Diagnosed = true;
6568 }
6569
6570 void notePreUse(Object O, Expr *Use) {
6571 UsageInfo &U = UsageMap[O];
6572 // Uses conflict with other modifications.
6573 checkUsage(O, U, Use, UK_ModAsValue, false);
6574 }
6575 void notePostUse(Object O, Expr *Use) {
6576 UsageInfo &U = UsageMap[O];
6577 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6578 addUsage(U, O, Use, UK_Use);
6579 }
6580
6581 void notePreMod(Object O, Expr *Mod) {
6582 UsageInfo &U = UsageMap[O];
6583 // Modifications conflict with other modifications and with uses.
6584 checkUsage(O, U, Mod, UK_ModAsValue, true);
6585 checkUsage(O, U, Mod, UK_Use, false);
6586 }
6587 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6588 UsageInfo &U = UsageMap[O];
6589 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6590 addUsage(U, O, Use, UK);
6591 }
6592
6593public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006594 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6595 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6596 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006597 Visit(E);
6598 }
6599
6600 void VisitStmt(Stmt *S) {
6601 // Skip all statements which aren't expressions for now.
6602 }
6603
6604 void VisitExpr(Expr *E) {
6605 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006606 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006607 }
6608
6609 void VisitCastExpr(CastExpr *E) {
6610 Object O = Object();
6611 if (E->getCastKind() == CK_LValueToRValue)
6612 O = getObject(E->getSubExpr(), false);
6613
6614 if (O)
6615 notePreUse(O, E);
6616 VisitExpr(E);
6617 if (O)
6618 notePostUse(O, E);
6619 }
6620
6621 void VisitBinComma(BinaryOperator *BO) {
6622 // C++11 [expr.comma]p1:
6623 // Every value computation and side effect associated with the left
6624 // expression is sequenced before every value computation and side
6625 // effect associated with the right expression.
6626 SequenceTree::Seq LHS = Tree.allocate(Region);
6627 SequenceTree::Seq RHS = Tree.allocate(Region);
6628 SequenceTree::Seq OldRegion = Region;
6629
6630 {
6631 SequencedSubexpression SeqLHS(*this);
6632 Region = LHS;
6633 Visit(BO->getLHS());
6634 }
6635
6636 Region = RHS;
6637 Visit(BO->getRHS());
6638
6639 Region = OldRegion;
6640
6641 // Forget that LHS and RHS are sequenced. They are both unsequenced
6642 // with respect to other stuff.
6643 Tree.merge(LHS);
6644 Tree.merge(RHS);
6645 }
6646
6647 void VisitBinAssign(BinaryOperator *BO) {
6648 // The modification is sequenced after the value computation of the LHS
6649 // and RHS, so check it before inspecting the operands and update the
6650 // map afterwards.
6651 Object O = getObject(BO->getLHS(), true);
6652 if (!O)
6653 return VisitExpr(BO);
6654
6655 notePreMod(O, BO);
6656
6657 // C++11 [expr.ass]p7:
6658 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6659 // only once.
6660 //
6661 // Therefore, for a compound assignment operator, O is considered used
6662 // everywhere except within the evaluation of E1 itself.
6663 if (isa<CompoundAssignOperator>(BO))
6664 notePreUse(O, BO);
6665
6666 Visit(BO->getLHS());
6667
6668 if (isa<CompoundAssignOperator>(BO))
6669 notePostUse(O, BO);
6670
6671 Visit(BO->getRHS());
6672
Richard Smith83e37bee2013-06-26 23:16:51 +00006673 // C++11 [expr.ass]p1:
6674 // the assignment is sequenced [...] before the value computation of the
6675 // assignment expression.
6676 // C11 6.5.16/3 has no such rule.
6677 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6678 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006679 }
6680 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6681 VisitBinAssign(CAO);
6682 }
6683
6684 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6685 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6686 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6687 Object O = getObject(UO->getSubExpr(), true);
6688 if (!O)
6689 return VisitExpr(UO);
6690
6691 notePreMod(O, UO);
6692 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006693 // C++11 [expr.pre.incr]p1:
6694 // the expression ++x is equivalent to x+=1
6695 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6696 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006697 }
6698
6699 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6700 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6701 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6702 Object O = getObject(UO->getSubExpr(), true);
6703 if (!O)
6704 return VisitExpr(UO);
6705
6706 notePreMod(O, UO);
6707 Visit(UO->getSubExpr());
6708 notePostMod(O, UO, UK_ModAsSideEffect);
6709 }
6710
6711 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6712 void VisitBinLOr(BinaryOperator *BO) {
6713 // The side-effects of the LHS of an '&&' are sequenced before the
6714 // value computation of the RHS, and hence before the value computation
6715 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6716 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006717 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006718 {
6719 SequencedSubexpression Sequenced(*this);
6720 Visit(BO->getLHS());
6721 }
6722
6723 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006724 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006725 if (!Result)
6726 Visit(BO->getRHS());
6727 } else {
6728 // Check for unsequenced operations in the RHS, treating it as an
6729 // entirely separate evaluation.
6730 //
6731 // FIXME: If there are operations in the RHS which are unsequenced
6732 // with respect to operations outside the RHS, and those operations
6733 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006734 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006735 }
Richard Smithc406cb72013-01-17 01:17:56 +00006736 }
6737 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006738 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006739 {
6740 SequencedSubexpression Sequenced(*this);
6741 Visit(BO->getLHS());
6742 }
6743
6744 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006745 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006746 if (Result)
6747 Visit(BO->getRHS());
6748 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006749 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006750 }
Richard Smithc406cb72013-01-17 01:17:56 +00006751 }
6752
6753 // Only visit the condition, unless we can be sure which subexpression will
6754 // be chosen.
6755 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006756 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006757 {
6758 SequencedSubexpression Sequenced(*this);
6759 Visit(CO->getCond());
6760 }
Richard Smithc406cb72013-01-17 01:17:56 +00006761
6762 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006763 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006764 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006765 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006766 WorkList.push_back(CO->getTrueExpr());
6767 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006768 }
Richard Smithc406cb72013-01-17 01:17:56 +00006769 }
6770
Richard Smithe3dbfe02013-06-30 10:40:20 +00006771 void VisitCallExpr(CallExpr *CE) {
6772 // C++11 [intro.execution]p15:
6773 // When calling a function [...], every value computation and side effect
6774 // associated with any argument expression, or with the postfix expression
6775 // designating the called function, is sequenced before execution of every
6776 // expression or statement in the body of the function [and thus before
6777 // the value computation of its result].
6778 SequencedSubexpression Sequenced(*this);
6779 Base::VisitCallExpr(CE);
6780
6781 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6782 }
6783
Richard Smithc406cb72013-01-17 01:17:56 +00006784 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006785 // This is a call, so all subexpressions are sequenced before the result.
6786 SequencedSubexpression Sequenced(*this);
6787
Richard Smithc406cb72013-01-17 01:17:56 +00006788 if (!CCE->isListInitialization())
6789 return VisitExpr(CCE);
6790
6791 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006792 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006793 SequenceTree::Seq Parent = Region;
6794 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6795 E = CCE->arg_end();
6796 I != E; ++I) {
6797 Region = Tree.allocate(Parent);
6798 Elts.push_back(Region);
6799 Visit(*I);
6800 }
6801
6802 // Forget that the initializers are sequenced.
6803 Region = Parent;
6804 for (unsigned I = 0; I < Elts.size(); ++I)
6805 Tree.merge(Elts[I]);
6806 }
6807
6808 void VisitInitListExpr(InitListExpr *ILE) {
6809 if (!SemaRef.getLangOpts().CPlusPlus11)
6810 return VisitExpr(ILE);
6811
6812 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006813 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006814 SequenceTree::Seq Parent = Region;
6815 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6816 Expr *E = ILE->getInit(I);
6817 if (!E) continue;
6818 Region = Tree.allocate(Parent);
6819 Elts.push_back(Region);
6820 Visit(E);
6821 }
6822
6823 // Forget that the initializers are sequenced.
6824 Region = Parent;
6825 for (unsigned I = 0; I < Elts.size(); ++I)
6826 Tree.merge(Elts[I]);
6827 }
6828};
6829}
6830
6831void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006832 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006833 WorkList.push_back(E);
6834 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006835 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006836 SequenceChecker(*this, Item, WorkList);
6837 }
Richard Smithc406cb72013-01-17 01:17:56 +00006838}
6839
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006840void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6841 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006842 CheckImplicitConversions(E, CheckLoc);
6843 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006844 if (!IsConstexpr && !E->isValueDependent())
6845 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006846}
6847
John McCall1f425642010-11-11 03:21:53 +00006848void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6849 FieldDecl *BitField,
6850 Expr *Init) {
6851 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6852}
6853
Mike Stump0c2ec772010-01-21 03:59:47 +00006854/// CheckParmsForFunctionDef - Check that the parameters of the given
6855/// function are appropriate for the definition of a function. This
6856/// takes care of any checks that cannot be performed on the
6857/// declaration itself, e.g., that the types of each of the function
6858/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006859bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6860 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006861 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006862 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006863 for (; P != PEnd; ++P) {
6864 ParmVarDecl *Param = *P;
6865
Mike Stump0c2ec772010-01-21 03:59:47 +00006866 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6867 // function declarator that is part of a function definition of
6868 // that function shall not have incomplete type.
6869 //
6870 // This is also C++ [dcl.fct]p6.
6871 if (!Param->isInvalidDecl() &&
6872 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006873 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006874 Param->setInvalidDecl();
6875 HasInvalidParm = true;
6876 }
6877
6878 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6879 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006880 if (CheckParameterNames &&
6881 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006882 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006883 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006884 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006885
6886 // C99 6.7.5.3p12:
6887 // If the function declarator is not part of a definition of that
6888 // function, parameters may have incomplete type and may use the [*]
6889 // notation in their sequences of declarator specifiers to specify
6890 // variable length array types.
6891 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006892 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006893 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006894 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006895 // information is added for it.
6896 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006897 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006898 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006899 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006900 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006901
6902 // MSVC destroys objects passed by value in the callee. Therefore a
6903 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006904 // object's destructor. However, we don't perform any direct access check
6905 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006906 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6907 .getCXXABI()
6908 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006909 if (!Param->isInvalidDecl()) {
6910 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6911 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6912 if (!ClassDecl->isInvalidDecl() &&
6913 !ClassDecl->hasIrrelevantDestructor() &&
6914 !ClassDecl->isDependentContext()) {
6915 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6916 MarkFunctionReferenced(Param->getLocation(), Destructor);
6917 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6918 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006919 }
6920 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006921 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006922 }
6923
6924 return HasInvalidParm;
6925}
John McCall2b5c1b22010-08-12 21:44:57 +00006926
6927/// CheckCastAlign - Implements -Wcast-align, which warns when a
6928/// pointer cast increases the alignment requirements.
6929void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6930 // This is actually a lot of work to potentially be doing on every
6931 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006932 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6933 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006934 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006935 return;
6936
6937 // Ignore dependent types.
6938 if (T->isDependentType() || Op->getType()->isDependentType())
6939 return;
6940
6941 // Require that the destination be a pointer type.
6942 const PointerType *DestPtr = T->getAs<PointerType>();
6943 if (!DestPtr) return;
6944
6945 // If the destination has alignment 1, we're done.
6946 QualType DestPointee = DestPtr->getPointeeType();
6947 if (DestPointee->isIncompleteType()) return;
6948 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6949 if (DestAlign.isOne()) return;
6950
6951 // Require that the source be a pointer type.
6952 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6953 if (!SrcPtr) return;
6954 QualType SrcPointee = SrcPtr->getPointeeType();
6955
6956 // Whitelist casts from cv void*. We already implicitly
6957 // whitelisted casts to cv void*, since they have alignment 1.
6958 // Also whitelist casts involving incomplete types, which implicitly
6959 // includes 'void'.
6960 if (SrcPointee->isIncompleteType()) return;
6961
6962 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6963 if (SrcAlign >= DestAlign) return;
6964
6965 Diag(TRange.getBegin(), diag::warn_cast_align)
6966 << Op->getType() << T
6967 << static_cast<unsigned>(SrcAlign.getQuantity())
6968 << static_cast<unsigned>(DestAlign.getQuantity())
6969 << TRange << Op->getSourceRange();
6970}
6971
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006972static const Type* getElementType(const Expr *BaseExpr) {
6973 const Type* EltType = BaseExpr->getType().getTypePtr();
6974 if (EltType->isAnyPointerType())
6975 return EltType->getPointeeType().getTypePtr();
6976 else if (EltType->isArrayType())
6977 return EltType->getBaseElementTypeUnsafe();
6978 return EltType;
6979}
6980
Chandler Carruth28389f02011-08-05 09:10:50 +00006981/// \brief Check whether this array fits the idiom of a size-one tail padded
6982/// array member of a struct.
6983///
6984/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6985/// commonly used to emulate flexible arrays in C89 code.
6986static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6987 const NamedDecl *ND) {
6988 if (Size != 1 || !ND) return false;
6989
6990 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6991 if (!FD) return false;
6992
6993 // Don't consider sizes resulting from macro expansions or template argument
6994 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006995
6996 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006997 while (TInfo) {
6998 TypeLoc TL = TInfo->getTypeLoc();
6999 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007000 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7001 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007002 TInfo = TDL->getTypeSourceInfo();
7003 continue;
7004 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007005 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7006 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007007 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7008 return false;
7009 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007010 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007011 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007012
7013 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007014 if (!RD) return false;
7015 if (RD->isUnion()) return false;
7016 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7017 if (!CRD->isStandardLayout()) return false;
7018 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007019
Benjamin Kramer8c543672011-08-06 03:04:42 +00007020 // See if this is the last field decl in the record.
7021 const Decl *D = FD;
7022 while ((D = D->getNextDeclInContext()))
7023 if (isa<FieldDecl>(D))
7024 return false;
7025 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007026}
7027
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007028void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007029 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007030 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007031 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007032 if (IndexExpr->isValueDependent())
7033 return;
7034
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007035 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007036 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007037 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007038 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007039 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007040 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007041
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007042 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007043 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007044 return;
Richard Smith13f67182011-12-16 19:31:14 +00007045 if (IndexNegated)
7046 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007047
Chandler Carruth126b1552011-08-05 08:07:29 +00007048 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00007049 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7050 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007051 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007052 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007053
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007054 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007055 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007056 if (!size.isStrictlyPositive())
7057 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007058
7059 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007060 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007061 // Make sure we're comparing apples to apples when comparing index to size
7062 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7063 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007064 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007065 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007066 if (ptrarith_typesize != array_typesize) {
7067 // There's a cast to a different size type involved
7068 uint64_t ratio = array_typesize / ptrarith_typesize;
7069 // TODO: Be smarter about handling cases where array_typesize is not a
7070 // multiple of ptrarith_typesize
7071 if (ptrarith_typesize * ratio == array_typesize)
7072 size *= llvm::APInt(size.getBitWidth(), ratio);
7073 }
7074 }
7075
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007076 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007077 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007078 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007079 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007080
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007081 // For array subscripting the index must be less than size, but for pointer
7082 // arithmetic also allow the index (offset) to be equal to size since
7083 // computing the next address after the end of the array is legal and
7084 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007085 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007086 return;
7087
7088 // Also don't warn for arrays of size 1 which are members of some
7089 // structure. These are often used to approximate flexible arrays in C89
7090 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007091 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007092 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007093
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007094 // Suppress the warning if the subscript expression (as identified by the
7095 // ']' location) and the index expression are both from macro expansions
7096 // within a system header.
7097 if (ASE) {
7098 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7099 ASE->getRBracketLoc());
7100 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7101 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7102 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007103 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007104 return;
7105 }
7106 }
7107
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007108 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007109 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007110 DiagID = diag::warn_array_index_exceeds_bounds;
7111
7112 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7113 PDiag(DiagID) << index.toString(10, true)
7114 << size.toString(10, true)
7115 << (unsigned)size.getLimitedValue(~0U)
7116 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007117 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007118 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007119 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007120 DiagID = diag::warn_ptr_arith_precedes_bounds;
7121 if (index.isNegative()) index = -index;
7122 }
7123
7124 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7125 PDiag(DiagID) << index.toString(10, true)
7126 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007127 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007128
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007129 if (!ND) {
7130 // Try harder to find a NamedDecl to point at in the note.
7131 while (const ArraySubscriptExpr *ASE =
7132 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7133 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7134 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7135 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7136 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7137 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7138 }
7139
Chandler Carruth1af88f12011-02-17 21:10:52 +00007140 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007141 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7142 PDiag(diag::note_array_index_out_of_bounds)
7143 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007144}
7145
Ted Kremenekdf26df72011-03-01 18:41:00 +00007146void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007147 int AllowOnePastEnd = 0;
7148 while (expr) {
7149 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007150 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007151 case Stmt::ArraySubscriptExprClass: {
7152 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007153 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007154 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007155 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007156 }
7157 case Stmt::UnaryOperatorClass: {
7158 // Only unwrap the * and & unary operators
7159 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7160 expr = UO->getSubExpr();
7161 switch (UO->getOpcode()) {
7162 case UO_AddrOf:
7163 AllowOnePastEnd++;
7164 break;
7165 case UO_Deref:
7166 AllowOnePastEnd--;
7167 break;
7168 default:
7169 return;
7170 }
7171 break;
7172 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007173 case Stmt::ConditionalOperatorClass: {
7174 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7175 if (const Expr *lhs = cond->getLHS())
7176 CheckArrayAccess(lhs);
7177 if (const Expr *rhs = cond->getRHS())
7178 CheckArrayAccess(rhs);
7179 return;
7180 }
7181 default:
7182 return;
7183 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007184 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007185}
John McCall31168b02011-06-15 23:02:42 +00007186
7187//===--- CHECK: Objective-C retain cycles ----------------------------------//
7188
7189namespace {
7190 struct RetainCycleOwner {
7191 RetainCycleOwner() : Variable(0), Indirect(false) {}
7192 VarDecl *Variable;
7193 SourceRange Range;
7194 SourceLocation Loc;
7195 bool Indirect;
7196
7197 void setLocsFrom(Expr *e) {
7198 Loc = e->getExprLoc();
7199 Range = e->getSourceRange();
7200 }
7201 };
7202}
7203
7204/// Consider whether capturing the given variable can possibly lead to
7205/// a retain cycle.
7206static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007207 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007208 // lifetime. In MRR, it's captured strongly if the variable is
7209 // __block and has an appropriate type.
7210 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7211 return false;
7212
7213 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007214 if (ref)
7215 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007216 return true;
7217}
7218
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007219static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007220 while (true) {
7221 e = e->IgnoreParens();
7222 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7223 switch (cast->getCastKind()) {
7224 case CK_BitCast:
7225 case CK_LValueBitCast:
7226 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007227 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007228 e = cast->getSubExpr();
7229 continue;
7230
John McCall31168b02011-06-15 23:02:42 +00007231 default:
7232 return false;
7233 }
7234 }
7235
7236 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7237 ObjCIvarDecl *ivar = ref->getDecl();
7238 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7239 return false;
7240
7241 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007242 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007243 return false;
7244
7245 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7246 owner.Indirect = true;
7247 return true;
7248 }
7249
7250 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7251 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7252 if (!var) return false;
7253 return considerVariable(var, ref, owner);
7254 }
7255
John McCall31168b02011-06-15 23:02:42 +00007256 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7257 if (member->isArrow()) return false;
7258
7259 // Don't count this as an indirect ownership.
7260 e = member->getBase();
7261 continue;
7262 }
7263
John McCallfe96e0b2011-11-06 09:01:30 +00007264 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7265 // Only pay attention to pseudo-objects on property references.
7266 ObjCPropertyRefExpr *pre
7267 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7268 ->IgnoreParens());
7269 if (!pre) return false;
7270 if (pre->isImplicitProperty()) return false;
7271 ObjCPropertyDecl *property = pre->getExplicitProperty();
7272 if (!property->isRetaining() &&
7273 !(property->getPropertyIvarDecl() &&
7274 property->getPropertyIvarDecl()->getType()
7275 .getObjCLifetime() == Qualifiers::OCL_Strong))
7276 return false;
7277
7278 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007279 if (pre->isSuperReceiver()) {
7280 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7281 if (!owner.Variable)
7282 return false;
7283 owner.Loc = pre->getLocation();
7284 owner.Range = pre->getSourceRange();
7285 return true;
7286 }
John McCallfe96e0b2011-11-06 09:01:30 +00007287 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7288 ->getSourceExpr());
7289 continue;
7290 }
7291
John McCall31168b02011-06-15 23:02:42 +00007292 // Array ivars?
7293
7294 return false;
7295 }
7296}
7297
7298namespace {
7299 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7300 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7301 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7302 Variable(variable), Capturer(0) {}
7303
7304 VarDecl *Variable;
7305 Expr *Capturer;
7306
7307 void VisitDeclRefExpr(DeclRefExpr *ref) {
7308 if (ref->getDecl() == Variable && !Capturer)
7309 Capturer = ref;
7310 }
7311
John McCall31168b02011-06-15 23:02:42 +00007312 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7313 if (Capturer) return;
7314 Visit(ref->getBase());
7315 if (Capturer && ref->isFreeIvar())
7316 Capturer = ref;
7317 }
7318
7319 void VisitBlockExpr(BlockExpr *block) {
7320 // Look inside nested blocks
7321 if (block->getBlockDecl()->capturesVariable(Variable))
7322 Visit(block->getBlockDecl()->getBody());
7323 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007324
7325 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7326 if (Capturer) return;
7327 if (OVE->getSourceExpr())
7328 Visit(OVE->getSourceExpr());
7329 }
John McCall31168b02011-06-15 23:02:42 +00007330 };
7331}
7332
7333/// Check whether the given argument is a block which captures a
7334/// variable.
7335static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7336 assert(owner.Variable && owner.Loc.isValid());
7337
7338 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007339
7340 // Look through [^{...} copy] and Block_copy(^{...}).
7341 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7342 Selector Cmd = ME->getSelector();
7343 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7344 e = ME->getInstanceReceiver();
7345 if (!e)
7346 return 0;
7347 e = e->IgnoreParenCasts();
7348 }
7349 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7350 if (CE->getNumArgs() == 1) {
7351 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007352 if (Fn) {
7353 const IdentifierInfo *FnI = Fn->getIdentifier();
7354 if (FnI && FnI->isStr("_Block_copy")) {
7355 e = CE->getArg(0)->IgnoreParenCasts();
7356 }
7357 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007358 }
7359 }
7360
John McCall31168b02011-06-15 23:02:42 +00007361 BlockExpr *block = dyn_cast<BlockExpr>(e);
7362 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7363 return 0;
7364
7365 FindCaptureVisitor visitor(S.Context, owner.Variable);
7366 visitor.Visit(block->getBlockDecl()->getBody());
7367 return visitor.Capturer;
7368}
7369
7370static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7371 RetainCycleOwner &owner) {
7372 assert(capturer);
7373 assert(owner.Variable && owner.Loc.isValid());
7374
7375 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7376 << owner.Variable << capturer->getSourceRange();
7377 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7378 << owner.Indirect << owner.Range;
7379}
7380
7381/// Check for a keyword selector that starts with the word 'add' or
7382/// 'set'.
7383static bool isSetterLikeSelector(Selector sel) {
7384 if (sel.isUnarySelector()) return false;
7385
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007386 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007387 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007388 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007389 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007390 else if (str.startswith("add")) {
7391 // Specially whitelist 'addOperationWithBlock:'.
7392 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7393 return false;
7394 str = str.substr(3);
7395 }
John McCall31168b02011-06-15 23:02:42 +00007396 else
7397 return false;
7398
7399 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007400 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007401}
7402
7403/// Check a message send to see if it's likely to cause a retain cycle.
7404void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7405 // Only check instance methods whose selector looks like a setter.
7406 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7407 return;
7408
7409 // Try to find a variable that the receiver is strongly owned by.
7410 RetainCycleOwner owner;
7411 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007412 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007413 return;
7414 } else {
7415 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7416 owner.Variable = getCurMethodDecl()->getSelfDecl();
7417 owner.Loc = msg->getSuperLoc();
7418 owner.Range = msg->getSuperLoc();
7419 }
7420
7421 // Check whether the receiver is captured by any of the arguments.
7422 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7423 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7424 return diagnoseRetainCycle(*this, capturer, owner);
7425}
7426
7427/// Check a property assign to see if it's likely to cause a retain cycle.
7428void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7429 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007430 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007431 return;
7432
7433 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7434 diagnoseRetainCycle(*this, capturer, owner);
7435}
7436
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007437void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7438 RetainCycleOwner Owner;
7439 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7440 return;
7441
7442 // Because we don't have an expression for the variable, we have to set the
7443 // location explicitly here.
7444 Owner.Loc = Var->getLocation();
7445 Owner.Range = Var->getSourceRange();
7446
7447 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7448 diagnoseRetainCycle(*this, Capturer, Owner);
7449}
7450
Ted Kremenek9304da92012-12-21 08:04:28 +00007451static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7452 Expr *RHS, bool isProperty) {
7453 // Check if RHS is an Objective-C object literal, which also can get
7454 // immediately zapped in a weak reference. Note that we explicitly
7455 // allow ObjCStringLiterals, since those are designed to never really die.
7456 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007457
Ted Kremenek64873352012-12-21 22:46:35 +00007458 // This enum needs to match with the 'select' in
7459 // warn_objc_arc_literal_assign (off-by-1).
7460 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7461 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7462 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007463
7464 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007465 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007466 << (isProperty ? 0 : 1)
7467 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007468
7469 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007470}
7471
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007472static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7473 Qualifiers::ObjCLifetime LT,
7474 Expr *RHS, bool isProperty) {
7475 // Strip off any implicit cast added to get to the one ARC-specific.
7476 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7477 if (cast->getCastKind() == CK_ARCConsumeObject) {
7478 S.Diag(Loc, diag::warn_arc_retained_assign)
7479 << (LT == Qualifiers::OCL_ExplicitNone)
7480 << (isProperty ? 0 : 1)
7481 << RHS->getSourceRange();
7482 return true;
7483 }
7484 RHS = cast->getSubExpr();
7485 }
7486
7487 if (LT == Qualifiers::OCL_Weak &&
7488 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7489 return true;
7490
7491 return false;
7492}
7493
Ted Kremenekb36234d2012-12-21 08:04:20 +00007494bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7495 QualType LHS, Expr *RHS) {
7496 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7497
7498 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7499 return false;
7500
7501 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7502 return true;
7503
7504 return false;
7505}
7506
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007507void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7508 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007509 QualType LHSType;
7510 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007511 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007512 ObjCPropertyRefExpr *PRE
7513 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7514 if (PRE && !PRE->isImplicitProperty()) {
7515 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7516 if (PD)
7517 LHSType = PD->getType();
7518 }
7519
7520 if (LHSType.isNull())
7521 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007522
7523 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7524
7525 if (LT == Qualifiers::OCL_Weak) {
7526 DiagnosticsEngine::Level Level =
7527 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7528 if (Level != DiagnosticsEngine::Ignored)
7529 getCurFunction()->markSafeWeakUse(LHS);
7530 }
7531
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007532 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7533 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007534
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007535 // FIXME. Check for other life times.
7536 if (LT != Qualifiers::OCL_None)
7537 return;
7538
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007539 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007540 if (PRE->isImplicitProperty())
7541 return;
7542 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7543 if (!PD)
7544 return;
7545
Bill Wendling44426052012-12-20 19:22:21 +00007546 unsigned Attributes = PD->getPropertyAttributes();
7547 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007548 // when 'assign' attribute was not explicitly specified
7549 // by user, ignore it and rely on property type itself
7550 // for lifetime info.
7551 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7552 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7553 LHSType->isObjCRetainableType())
7554 return;
7555
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007556 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007557 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007558 Diag(Loc, diag::warn_arc_retained_property_assign)
7559 << RHS->getSourceRange();
7560 return;
7561 }
7562 RHS = cast->getSubExpr();
7563 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007564 }
Bill Wendling44426052012-12-20 19:22:21 +00007565 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007566 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7567 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007568 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007569 }
7570}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007571
7572//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7573
7574namespace {
7575bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7576 SourceLocation StmtLoc,
7577 const NullStmt *Body) {
7578 // Do not warn if the body is a macro that expands to nothing, e.g:
7579 //
7580 // #define CALL(x)
7581 // if (condition)
7582 // CALL(0);
7583 //
7584 if (Body->hasLeadingEmptyMacro())
7585 return false;
7586
7587 // Get line numbers of statement and body.
7588 bool StmtLineInvalid;
7589 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7590 &StmtLineInvalid);
7591 if (StmtLineInvalid)
7592 return false;
7593
7594 bool BodyLineInvalid;
7595 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7596 &BodyLineInvalid);
7597 if (BodyLineInvalid)
7598 return false;
7599
7600 // Warn if null statement and body are on the same line.
7601 if (StmtLine != BodyLine)
7602 return false;
7603
7604 return true;
7605}
7606} // Unnamed namespace
7607
7608void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7609 const Stmt *Body,
7610 unsigned DiagID) {
7611 // Since this is a syntactic check, don't emit diagnostic for template
7612 // instantiations, this just adds noise.
7613 if (CurrentInstantiationScope)
7614 return;
7615
7616 // The body should be a null statement.
7617 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7618 if (!NBody)
7619 return;
7620
7621 // Do the usual checks.
7622 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7623 return;
7624
7625 Diag(NBody->getSemiLoc(), DiagID);
7626 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7627}
7628
7629void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7630 const Stmt *PossibleBody) {
7631 assert(!CurrentInstantiationScope); // Ensured by caller
7632
7633 SourceLocation StmtLoc;
7634 const Stmt *Body;
7635 unsigned DiagID;
7636 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7637 StmtLoc = FS->getRParenLoc();
7638 Body = FS->getBody();
7639 DiagID = diag::warn_empty_for_body;
7640 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7641 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7642 Body = WS->getBody();
7643 DiagID = diag::warn_empty_while_body;
7644 } else
7645 return; // Neither `for' nor `while'.
7646
7647 // The body should be a null statement.
7648 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7649 if (!NBody)
7650 return;
7651
7652 // Skip expensive checks if diagnostic is disabled.
7653 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7654 DiagnosticsEngine::Ignored)
7655 return;
7656
7657 // Do the usual checks.
7658 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7659 return;
7660
7661 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7662 // noise level low, emit diagnostics only if for/while is followed by a
7663 // CompoundStmt, e.g.:
7664 // for (int i = 0; i < n; i++);
7665 // {
7666 // a(i);
7667 // }
7668 // or if for/while is followed by a statement with more indentation
7669 // than for/while itself:
7670 // for (int i = 0; i < n; i++);
7671 // a(i);
7672 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7673 if (!ProbableTypo) {
7674 bool BodyColInvalid;
7675 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7676 PossibleBody->getLocStart(),
7677 &BodyColInvalid);
7678 if (BodyColInvalid)
7679 return;
7680
7681 bool StmtColInvalid;
7682 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7683 S->getLocStart(),
7684 &StmtColInvalid);
7685 if (StmtColInvalid)
7686 return;
7687
7688 if (BodyCol > StmtCol)
7689 ProbableTypo = true;
7690 }
7691
7692 if (ProbableTypo) {
7693 Diag(NBody->getSemiLoc(), DiagID);
7694 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7695 }
7696}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007697
7698//===--- Layout compatibility ----------------------------------------------//
7699
7700namespace {
7701
7702bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7703
7704/// \brief Check if two enumeration types are layout-compatible.
7705bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7706 // C++11 [dcl.enum] p8:
7707 // Two enumeration types are layout-compatible if they have the same
7708 // underlying type.
7709 return ED1->isComplete() && ED2->isComplete() &&
7710 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7711}
7712
7713/// \brief Check if two fields are layout-compatible.
7714bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7715 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7716 return false;
7717
7718 if (Field1->isBitField() != Field2->isBitField())
7719 return false;
7720
7721 if (Field1->isBitField()) {
7722 // Make sure that the bit-fields are the same length.
7723 unsigned Bits1 = Field1->getBitWidthValue(C);
7724 unsigned Bits2 = Field2->getBitWidthValue(C);
7725
7726 if (Bits1 != Bits2)
7727 return false;
7728 }
7729
7730 return true;
7731}
7732
7733/// \brief Check if two standard-layout structs are layout-compatible.
7734/// (C++11 [class.mem] p17)
7735bool isLayoutCompatibleStruct(ASTContext &C,
7736 RecordDecl *RD1,
7737 RecordDecl *RD2) {
7738 // If both records are C++ classes, check that base classes match.
7739 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7740 // If one of records is a CXXRecordDecl we are in C++ mode,
7741 // thus the other one is a CXXRecordDecl, too.
7742 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7743 // Check number of base classes.
7744 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7745 return false;
7746
7747 // Check the base classes.
7748 for (CXXRecordDecl::base_class_const_iterator
7749 Base1 = D1CXX->bases_begin(),
7750 BaseEnd1 = D1CXX->bases_end(),
7751 Base2 = D2CXX->bases_begin();
7752 Base1 != BaseEnd1;
7753 ++Base1, ++Base2) {
7754 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7755 return false;
7756 }
7757 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7758 // If only RD2 is a C++ class, it should have zero base classes.
7759 if (D2CXX->getNumBases() > 0)
7760 return false;
7761 }
7762
7763 // Check the fields.
7764 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7765 Field2End = RD2->field_end(),
7766 Field1 = RD1->field_begin(),
7767 Field1End = RD1->field_end();
7768 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7769 if (!isLayoutCompatible(C, *Field1, *Field2))
7770 return false;
7771 }
7772 if (Field1 != Field1End || Field2 != Field2End)
7773 return false;
7774
7775 return true;
7776}
7777
7778/// \brief Check if two standard-layout unions are layout-compatible.
7779/// (C++11 [class.mem] p18)
7780bool isLayoutCompatibleUnion(ASTContext &C,
7781 RecordDecl *RD1,
7782 RecordDecl *RD2) {
7783 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007784 for (auto *Field2 : RD2->fields())
7785 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007786
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007787 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007788 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7789 I = UnmatchedFields.begin(),
7790 E = UnmatchedFields.end();
7791
7792 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007793 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007794 bool Result = UnmatchedFields.erase(*I);
7795 (void) Result;
7796 assert(Result);
7797 break;
7798 }
7799 }
7800 if (I == E)
7801 return false;
7802 }
7803
7804 return UnmatchedFields.empty();
7805}
7806
7807bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7808 if (RD1->isUnion() != RD2->isUnion())
7809 return false;
7810
7811 if (RD1->isUnion())
7812 return isLayoutCompatibleUnion(C, RD1, RD2);
7813 else
7814 return isLayoutCompatibleStruct(C, RD1, RD2);
7815}
7816
7817/// \brief Check if two types are layout-compatible in C++11 sense.
7818bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7819 if (T1.isNull() || T2.isNull())
7820 return false;
7821
7822 // C++11 [basic.types] p11:
7823 // If two types T1 and T2 are the same type, then T1 and T2 are
7824 // layout-compatible types.
7825 if (C.hasSameType(T1, T2))
7826 return true;
7827
7828 T1 = T1.getCanonicalType().getUnqualifiedType();
7829 T2 = T2.getCanonicalType().getUnqualifiedType();
7830
7831 const Type::TypeClass TC1 = T1->getTypeClass();
7832 const Type::TypeClass TC2 = T2->getTypeClass();
7833
7834 if (TC1 != TC2)
7835 return false;
7836
7837 if (TC1 == Type::Enum) {
7838 return isLayoutCompatible(C,
7839 cast<EnumType>(T1)->getDecl(),
7840 cast<EnumType>(T2)->getDecl());
7841 } else if (TC1 == Type::Record) {
7842 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7843 return false;
7844
7845 return isLayoutCompatible(C,
7846 cast<RecordType>(T1)->getDecl(),
7847 cast<RecordType>(T2)->getDecl());
7848 }
7849
7850 return false;
7851}
7852}
7853
7854//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7855
7856namespace {
7857/// \brief Given a type tag expression find the type tag itself.
7858///
7859/// \param TypeExpr Type tag expression, as it appears in user's code.
7860///
7861/// \param VD Declaration of an identifier that appears in a type tag.
7862///
7863/// \param MagicValue Type tag magic value.
7864bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7865 const ValueDecl **VD, uint64_t *MagicValue) {
7866 while(true) {
7867 if (!TypeExpr)
7868 return false;
7869
7870 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7871
7872 switch (TypeExpr->getStmtClass()) {
7873 case Stmt::UnaryOperatorClass: {
7874 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7875 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7876 TypeExpr = UO->getSubExpr();
7877 continue;
7878 }
7879 return false;
7880 }
7881
7882 case Stmt::DeclRefExprClass: {
7883 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7884 *VD = DRE->getDecl();
7885 return true;
7886 }
7887
7888 case Stmt::IntegerLiteralClass: {
7889 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7890 llvm::APInt MagicValueAPInt = IL->getValue();
7891 if (MagicValueAPInt.getActiveBits() <= 64) {
7892 *MagicValue = MagicValueAPInt.getZExtValue();
7893 return true;
7894 } else
7895 return false;
7896 }
7897
7898 case Stmt::BinaryConditionalOperatorClass:
7899 case Stmt::ConditionalOperatorClass: {
7900 const AbstractConditionalOperator *ACO =
7901 cast<AbstractConditionalOperator>(TypeExpr);
7902 bool Result;
7903 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7904 if (Result)
7905 TypeExpr = ACO->getTrueExpr();
7906 else
7907 TypeExpr = ACO->getFalseExpr();
7908 continue;
7909 }
7910 return false;
7911 }
7912
7913 case Stmt::BinaryOperatorClass: {
7914 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7915 if (BO->getOpcode() == BO_Comma) {
7916 TypeExpr = BO->getRHS();
7917 continue;
7918 }
7919 return false;
7920 }
7921
7922 default:
7923 return false;
7924 }
7925 }
7926}
7927
7928/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7929///
7930/// \param TypeExpr Expression that specifies a type tag.
7931///
7932/// \param MagicValues Registered magic values.
7933///
7934/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7935/// kind.
7936///
7937/// \param TypeInfo Information about the corresponding C type.
7938///
7939/// \returns true if the corresponding C type was found.
7940bool GetMatchingCType(
7941 const IdentifierInfo *ArgumentKind,
7942 const Expr *TypeExpr, const ASTContext &Ctx,
7943 const llvm::DenseMap<Sema::TypeTagMagicValue,
7944 Sema::TypeTagData> *MagicValues,
7945 bool &FoundWrongKind,
7946 Sema::TypeTagData &TypeInfo) {
7947 FoundWrongKind = false;
7948
7949 // Variable declaration that has type_tag_for_datatype attribute.
7950 const ValueDecl *VD = NULL;
7951
7952 uint64_t MagicValue;
7953
7954 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7955 return false;
7956
7957 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007958 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007959 if (I->getArgumentKind() != ArgumentKind) {
7960 FoundWrongKind = true;
7961 return false;
7962 }
7963 TypeInfo.Type = I->getMatchingCType();
7964 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7965 TypeInfo.MustBeNull = I->getMustBeNull();
7966 return true;
7967 }
7968 return false;
7969 }
7970
7971 if (!MagicValues)
7972 return false;
7973
7974 llvm::DenseMap<Sema::TypeTagMagicValue,
7975 Sema::TypeTagData>::const_iterator I =
7976 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7977 if (I == MagicValues->end())
7978 return false;
7979
7980 TypeInfo = I->second;
7981 return true;
7982}
7983} // unnamed namespace
7984
7985void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7986 uint64_t MagicValue, QualType Type,
7987 bool LayoutCompatible,
7988 bool MustBeNull) {
7989 if (!TypeTagForDatatypeMagicValues)
7990 TypeTagForDatatypeMagicValues.reset(
7991 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7992
7993 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7994 (*TypeTagForDatatypeMagicValues)[Magic] =
7995 TypeTagData(Type, LayoutCompatible, MustBeNull);
7996}
7997
7998namespace {
7999bool IsSameCharType(QualType T1, QualType T2) {
8000 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8001 if (!BT1)
8002 return false;
8003
8004 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8005 if (!BT2)
8006 return false;
8007
8008 BuiltinType::Kind T1Kind = BT1->getKind();
8009 BuiltinType::Kind T2Kind = BT2->getKind();
8010
8011 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8012 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8013 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8014 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8015}
8016} // unnamed namespace
8017
8018void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8019 const Expr * const *ExprArgs) {
8020 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8021 bool IsPointerAttr = Attr->getIsPointer();
8022
8023 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8024 bool FoundWrongKind;
8025 TypeTagData TypeInfo;
8026 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8027 TypeTagForDatatypeMagicValues.get(),
8028 FoundWrongKind, TypeInfo)) {
8029 if (FoundWrongKind)
8030 Diag(TypeTagExpr->getExprLoc(),
8031 diag::warn_type_tag_for_datatype_wrong_kind)
8032 << TypeTagExpr->getSourceRange();
8033 return;
8034 }
8035
8036 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8037 if (IsPointerAttr) {
8038 // Skip implicit cast of pointer to `void *' (as a function argument).
8039 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008040 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008041 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008042 ArgumentExpr = ICE->getSubExpr();
8043 }
8044 QualType ArgumentType = ArgumentExpr->getType();
8045
8046 // Passing a `void*' pointer shouldn't trigger a warning.
8047 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8048 return;
8049
8050 if (TypeInfo.MustBeNull) {
8051 // Type tag with matching void type requires a null pointer.
8052 if (!ArgumentExpr->isNullPointerConstant(Context,
8053 Expr::NPC_ValueDependentIsNotNull)) {
8054 Diag(ArgumentExpr->getExprLoc(),
8055 diag::warn_type_safety_null_pointer_required)
8056 << ArgumentKind->getName()
8057 << ArgumentExpr->getSourceRange()
8058 << TypeTagExpr->getSourceRange();
8059 }
8060 return;
8061 }
8062
8063 QualType RequiredType = TypeInfo.Type;
8064 if (IsPointerAttr)
8065 RequiredType = Context.getPointerType(RequiredType);
8066
8067 bool mismatch = false;
8068 if (!TypeInfo.LayoutCompatible) {
8069 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8070
8071 // C++11 [basic.fundamental] p1:
8072 // Plain char, signed char, and unsigned char are three distinct types.
8073 //
8074 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8075 // char' depending on the current char signedness mode.
8076 if (mismatch)
8077 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8078 RequiredType->getPointeeType())) ||
8079 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8080 mismatch = false;
8081 } else
8082 if (IsPointerAttr)
8083 mismatch = !isLayoutCompatible(Context,
8084 ArgumentType->getPointeeType(),
8085 RequiredType->getPointeeType());
8086 else
8087 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8088
8089 if (mismatch)
8090 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008091 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008092 << TypeInfo.LayoutCompatible << RequiredType
8093 << ArgumentExpr->getSourceRange()
8094 << TypeTagExpr->getSourceRange();
8095}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008096