blob: f6bb8370d5371921cb7fe8eed833b4a910abf215 [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"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#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 {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.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
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 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) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000116 ExprResult TheCallResult(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;
Hal Finkelf0417332014-07-17 14:25:55 +0000178 case Builtin::BI__assume:
179 if (SemaBuiltinAssume(TheCall))
180 return ExprError();
181 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000182 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000183 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000186 case Builtin::BI__builtin_longjmp:
187 if (SemaBuiltinLongjmp(TheCall))
188 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000189 break;
John McCallbebede42011-02-26 05:39:39 +0000190
191 case Builtin::BI__builtin_classify_type:
192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
194 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000195 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000196 if (checkArgCount(*this, TheCall, 1)) return true;
197 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000198 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000199 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000200 case Builtin::BI__sync_fetch_and_add_1:
201 case Builtin::BI__sync_fetch_and_add_2:
202 case Builtin::BI__sync_fetch_and_add_4:
203 case Builtin::BI__sync_fetch_and_add_8:
204 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000205 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000206 case Builtin::BI__sync_fetch_and_sub_1:
207 case Builtin::BI__sync_fetch_and_sub_2:
208 case Builtin::BI__sync_fetch_and_sub_4:
209 case Builtin::BI__sync_fetch_and_sub_8:
210 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000211 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000212 case Builtin::BI__sync_fetch_and_or_1:
213 case Builtin::BI__sync_fetch_and_or_2:
214 case Builtin::BI__sync_fetch_and_or_4:
215 case Builtin::BI__sync_fetch_and_or_8:
216 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000217 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000218 case Builtin::BI__sync_fetch_and_and_1:
219 case Builtin::BI__sync_fetch_and_and_2:
220 case Builtin::BI__sync_fetch_and_and_4:
221 case Builtin::BI__sync_fetch_and_and_8:
222 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000223 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000224 case Builtin::BI__sync_fetch_and_xor_1:
225 case Builtin::BI__sync_fetch_and_xor_2:
226 case Builtin::BI__sync_fetch_and_xor_4:
227 case Builtin::BI__sync_fetch_and_xor_8:
228 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000229 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000230 case Builtin::BI__sync_add_and_fetch_1:
231 case Builtin::BI__sync_add_and_fetch_2:
232 case Builtin::BI__sync_add_and_fetch_4:
233 case Builtin::BI__sync_add_and_fetch_8:
234 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000235 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000236 case Builtin::BI__sync_sub_and_fetch_1:
237 case Builtin::BI__sync_sub_and_fetch_2:
238 case Builtin::BI__sync_sub_and_fetch_4:
239 case Builtin::BI__sync_sub_and_fetch_8:
240 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000241 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000242 case Builtin::BI__sync_and_and_fetch_1:
243 case Builtin::BI__sync_and_and_fetch_2:
244 case Builtin::BI__sync_and_and_fetch_4:
245 case Builtin::BI__sync_and_and_fetch_8:
246 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000247 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000248 case Builtin::BI__sync_or_and_fetch_1:
249 case Builtin::BI__sync_or_and_fetch_2:
250 case Builtin::BI__sync_or_and_fetch_4:
251 case Builtin::BI__sync_or_and_fetch_8:
252 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000253 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000254 case Builtin::BI__sync_xor_and_fetch_1:
255 case Builtin::BI__sync_xor_and_fetch_2:
256 case Builtin::BI__sync_xor_and_fetch_4:
257 case Builtin::BI__sync_xor_and_fetch_8:
258 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000259 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000260 case Builtin::BI__sync_val_compare_and_swap_1:
261 case Builtin::BI__sync_val_compare_and_swap_2:
262 case Builtin::BI__sync_val_compare_and_swap_4:
263 case Builtin::BI__sync_val_compare_and_swap_8:
264 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000265 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000266 case Builtin::BI__sync_bool_compare_and_swap_1:
267 case Builtin::BI__sync_bool_compare_and_swap_2:
268 case Builtin::BI__sync_bool_compare_and_swap_4:
269 case Builtin::BI__sync_bool_compare_and_swap_8:
270 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000271 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000272 case Builtin::BI__sync_lock_test_and_set_1:
273 case Builtin::BI__sync_lock_test_and_set_2:
274 case Builtin::BI__sync_lock_test_and_set_4:
275 case Builtin::BI__sync_lock_test_and_set_8:
276 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000277 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000278 case Builtin::BI__sync_lock_release_1:
279 case Builtin::BI__sync_lock_release_2:
280 case Builtin::BI__sync_lock_release_4:
281 case Builtin::BI__sync_lock_release_8:
282 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000283 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000284 case Builtin::BI__sync_swap_1:
285 case Builtin::BI__sync_swap_2:
286 case Builtin::BI__sync_swap_4:
287 case Builtin::BI__sync_swap_8:
288 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#define BUILTIN(ID, TYPE, ATTRS)
291#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
292 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000293 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000294#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000295 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000296 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000297 return ExprError();
298 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000299 case Builtin::BI__builtin_addressof:
300 if (SemaBuiltinAddressof(*this, TheCall))
301 return ExprError();
302 break;
Richard Smith760520b2014-06-03 23:27:44 +0000303 case Builtin::BI__builtin_operator_new:
304 case Builtin::BI__builtin_operator_delete:
305 if (!getLangOpts().CPlusPlus) {
306 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
307 << (BuiltinID == Builtin::BI__builtin_operator_new
308 ? "__builtin_operator_new"
309 : "__builtin_operator_delete")
310 << "C++";
311 return ExprError();
312 }
313 // CodeGen assumes it can find the global new and delete to call,
314 // so ensure that they are declared.
315 DeclareGlobalNewDelete();
316 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000317 }
Richard Smith760520b2014-06-03 23:27:44 +0000318
Nate Begeman4904e322010-06-08 02:47:44 +0000319 // Since the target specific builtins for each arch overlap, only check those
320 // of the arch we are compiling for.
321 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000322 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000323 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000324 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000325 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000326 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000327 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
328 return ExprError();
329 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000330 case llvm::Triple::aarch64:
331 case llvm::Triple::aarch64_be:
Tim Northovera2ee4332014-03-29 15:09:45 +0000332 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000333 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000334 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000335 return ExprError();
336 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000337 case llvm::Triple::mips:
338 case llvm::Triple::mipsel:
339 case llvm::Triple::mips64:
340 case llvm::Triple::mips64el:
341 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
342 return ExprError();
343 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000344 case llvm::Triple::x86:
345 case llvm::Triple::x86_64:
346 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
347 return ExprError();
348 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000349 default:
350 break;
351 }
352 }
353
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000354 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000355}
356
Nate Begeman91e1fea2010-06-14 05:21:25 +0000357// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000358static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000359 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000360 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000361 switch (Type.getEltType()) {
362 case NeonTypeFlags::Int8:
363 case NeonTypeFlags::Poly8:
364 return shift ? 7 : (8 << IsQuad) - 1;
365 case NeonTypeFlags::Int16:
366 case NeonTypeFlags::Poly16:
367 return shift ? 15 : (4 << IsQuad) - 1;
368 case NeonTypeFlags::Int32:
369 return shift ? 31 : (2 << IsQuad) - 1;
370 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000371 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000372 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000373 case NeonTypeFlags::Poly128:
374 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000375 case NeonTypeFlags::Float16:
376 assert(!shift && "cannot shift float types!");
377 return (4 << IsQuad) - 1;
378 case NeonTypeFlags::Float32:
379 assert(!shift && "cannot shift float types!");
380 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000381 case NeonTypeFlags::Float64:
382 assert(!shift && "cannot shift float types!");
383 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000384 }
David Blaikie8a40f702012-01-17 06:56:22 +0000385 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000386}
387
Bob Wilsone4d77232011-11-08 05:04:11 +0000388/// getNeonEltType - Return the QualType corresponding to the elements of
389/// the vector type specified by the NeonTypeFlags. This is used to check
390/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000391static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000392 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000393 switch (Flags.getEltType()) {
394 case NeonTypeFlags::Int8:
395 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
396 case NeonTypeFlags::Int16:
397 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
398 case NeonTypeFlags::Int32:
399 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
400 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000401 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000402 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
403 else
404 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
405 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000406 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000407 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000408 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000409 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000410 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000411 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000412 case NeonTypeFlags::Poly128:
413 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000414 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000415 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000416 case NeonTypeFlags::Float32:
417 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000418 case NeonTypeFlags::Float64:
419 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000420 }
David Blaikie8a40f702012-01-17 06:56:22 +0000421 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000422}
423
Tim Northover12670412014-02-19 10:37:05 +0000424bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000425 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000426 uint64_t mask = 0;
427 unsigned TV = 0;
428 int PtrArgNum = -1;
429 bool HasConstPtr = false;
430 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000431#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000432#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000433#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000434 }
435
436 // For NEON intrinsics which are overloaded on vector element type, validate
437 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000438 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000439 if (mask) {
440 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
441 return true;
442
443 TV = Result.getLimitedValue(64);
444 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
445 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000446 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000447 }
448
449 if (PtrArgNum >= 0) {
450 // Check that pointer arguments have the specified type.
451 Expr *Arg = TheCall->getArg(PtrArgNum);
452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
453 Arg = ICE->getSubExpr();
454 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
455 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000456
Tim Northovera2ee4332014-03-29 15:09:45 +0000457 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
458 bool IsPolyUnsigned =
459 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
460 bool IsInt64Long =
461 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
462 QualType EltTy =
463 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000464 if (HasConstPtr)
465 EltTy = EltTy.withConst();
466 QualType LHSTy = Context.getPointerType(EltTy);
467 AssignConvertType ConvTy;
468 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
469 if (RHS.isInvalid())
470 return true;
471 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
472 RHS.get(), AA_Assigning))
473 return true;
474 }
475
476 // For NEON intrinsics which take an immediate value as part of the
477 // instruction, range check them here.
478 unsigned i = 0, l = 0, u = 0;
479 switch (BuiltinID) {
480 default:
481 return false;
Tim Northover12670412014-02-19 10:37:05 +0000482#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000483#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000484#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000485 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000486
Richard Sandiford28940af2014-04-16 08:47:51 +0000487 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000488}
489
Tim Northovera2ee4332014-03-29 15:09:45 +0000490bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
491 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000492 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000493 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000494 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000495 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000496 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000497 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
498 BuiltinID == AArch64::BI__builtin_arm_strex ||
499 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000500 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000501 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000502 BuiltinID == ARM::BI__builtin_arm_ldaex ||
503 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
504 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000505
506 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
507
508 // Ensure that we have the proper number of arguments.
509 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
510 return true;
511
512 // Inspect the pointer argument of the atomic builtin. This should always be
513 // a pointer type, whose element is an integral scalar or pointer type.
514 // Because it is a pointer type, we don't have to worry about any implicit
515 // casts here.
516 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
517 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
518 if (PointerArgRes.isInvalid())
519 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000520 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000521
522 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
523 if (!pointerType) {
524 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
525 << PointerArg->getType() << PointerArg->getSourceRange();
526 return true;
527 }
528
529 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
530 // task is to insert the appropriate casts into the AST. First work out just
531 // what the appropriate type is.
532 QualType ValType = pointerType->getPointeeType();
533 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
534 if (IsLdrex)
535 AddrType.addConst();
536
537 // Issue a warning if the cast is dodgy.
538 CastKind CastNeeded = CK_NoOp;
539 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
540 CastNeeded = CK_BitCast;
541 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
542 << PointerArg->getType()
543 << Context.getPointerType(AddrType)
544 << AA_Passing << PointerArg->getSourceRange();
545 }
546
547 // Finally, do the cast and replace the argument with the corrected version.
548 AddrType = Context.getPointerType(AddrType);
549 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
550 if (PointerArgRes.isInvalid())
551 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000552 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000553
554 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
555
556 // In general, we allow ints, floats and pointers to be loaded and stored.
557 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
558 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
559 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
560 << PointerArg->getType() << PointerArg->getSourceRange();
561 return true;
562 }
563
564 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000565 if (Context.getTypeSize(ValType) > MaxWidth) {
566 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000567 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
568 << PointerArg->getType() << PointerArg->getSourceRange();
569 return true;
570 }
571
572 switch (ValType.getObjCLifetime()) {
573 case Qualifiers::OCL_None:
574 case Qualifiers::OCL_ExplicitNone:
575 // okay
576 break;
577
578 case Qualifiers::OCL_Weak:
579 case Qualifiers::OCL_Strong:
580 case Qualifiers::OCL_Autoreleasing:
581 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
582 << ValType << PointerArg->getSourceRange();
583 return true;
584 }
585
586
587 if (IsLdrex) {
588 TheCall->setType(ValType);
589 return false;
590 }
591
592 // Initialize the argument to be stored.
593 ExprResult ValArg = TheCall->getArg(0);
594 InitializedEntity Entity = InitializedEntity::InitializeParameter(
595 Context, ValType, /*consume*/ false);
596 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
597 if (ValArg.isInvalid())
598 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000599 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000600
601 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
602 // but the custom checker bypasses all default analysis.
603 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000604 return false;
605}
606
Nate Begeman4904e322010-06-08 02:47:44 +0000607bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000608 llvm::APSInt Result;
609
Tim Northover6aacd492013-07-16 09:47:53 +0000610 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000611 BuiltinID == ARM::BI__builtin_arm_ldaex ||
612 BuiltinID == ARM::BI__builtin_arm_strex ||
613 BuiltinID == ARM::BI__builtin_arm_stlex) {
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
Yi Kong4efadfb2014-07-03 16:01:25 +0000620 // For intrinsics which take an immediate value as part of the instruction,
621 // 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:
Yi Kong4efadfb2014-07-03 16:01:25 +0000630 case ARM::BI__builtin_arm_dsb:
631 case ARM::BI__builtin_arm_isb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000632 }
Nate Begemand773fe62010-06-13 04:47:52 +0000633
Nate Begemanf568b072010-08-03 21:32:34 +0000634 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000635 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000636}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000637
Tim Northover573cbee2014-05-24 12:52:07 +0000638bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000639 CallExpr *TheCall) {
640 llvm::APSInt Result;
641
Tim Northover573cbee2014-05-24 12:52:07 +0000642 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000643 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
644 BuiltinID == AArch64::BI__builtin_arm_strex ||
645 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000646 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
647 }
648
649 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
650 return true;
651
Yi Kong19a29ac2014-07-17 10:52:06 +0000652 // For intrinsics which take an immediate value as part of the instruction,
653 // range check them here.
654 unsigned i = 0, l = 0, u = 0;
655 switch (BuiltinID) {
656 default: return false;
657 case AArch64::BI__builtin_arm_dmb:
658 case AArch64::BI__builtin_arm_dsb:
659 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
660 }
661
662 // FIXME: VFP Intrinsics should error if VFP not present.
663 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000664}
665
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000666bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
667 unsigned i = 0, l = 0, u = 0;
668 switch (BuiltinID) {
669 default: return false;
670 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
671 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000672 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
673 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
674 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
675 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
676 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000677 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000678
Richard Sandiford28940af2014-04-16 08:47:51 +0000679 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000680}
681
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000682bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
683 switch (BuiltinID) {
684 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000685 // This is declared to take (const char*, int)
686 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000687 }
688 return false;
689}
690
Richard Smith55ce3522012-06-25 20:30:08 +0000691/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
692/// parameter with the FormatAttr's correct format_idx and firstDataArg.
693/// Returns true when the format fits the function and the FormatStringInfo has
694/// been populated.
695bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
696 FormatStringInfo *FSI) {
697 FSI->HasVAListArg = Format->getFirstArg() == 0;
698 FSI->FormatIdx = Format->getFormatIdx() - 1;
699 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000700
Richard Smith55ce3522012-06-25 20:30:08 +0000701 // The way the format attribute works in GCC, the implicit this argument
702 // of member functions is counted. However, it doesn't appear in our own
703 // lists, so decrement format_idx in that case.
704 if (IsCXXMember) {
705 if(FSI->FormatIdx == 0)
706 return false;
707 --FSI->FormatIdx;
708 if (FSI->FirstDataArg != 0)
709 --FSI->FirstDataArg;
710 }
711 return true;
712}
Mike Stump11289f42009-09-09 15:08:12 +0000713
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000714/// Checks if a the given expression evaluates to null.
715///
716/// \brief Returns true if the value evaluates to null.
717static bool CheckNonNullExpr(Sema &S,
718 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000719 // As a special case, transparent unions initialized with zero are
720 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000721 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000722 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
723 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000724 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000725 if (const InitListExpr *ILE =
726 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000727 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000728 }
729
730 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000731 return (!Expr->isValueDependent() &&
732 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
733 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000734}
735
736static void CheckNonNullArgument(Sema &S,
737 const Expr *ArgExpr,
738 SourceLocation CallSiteLoc) {
739 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000740 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
741}
742
Ted Kremenek2bc73332014-01-17 06:24:43 +0000743static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000744 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000745 const Expr * const *ExprArgs,
746 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000747 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000748 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000749 for (const auto &Val : NonNull->args())
750 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000751 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000752
753 // Check the attributes on the parameters.
754 ArrayRef<ParmVarDecl*> parms;
755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
756 parms = FD->parameters();
757 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
758 parms = MD->parameters();
759
760 unsigned argIndex = 0;
761 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
762 I != E; ++I, ++argIndex) {
763 const ParmVarDecl *PVD = *I;
764 if (PVD->hasAttr<NonNullAttr>())
765 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
766 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000767}
768
Richard Smith55ce3522012-06-25 20:30:08 +0000769/// Handles the checks for format strings, non-POD arguments to vararg
770/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000771void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
772 unsigned NumParams, bool IsMemberFunction,
773 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000774 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000775 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000776 if (CurContext->isDependentContext())
777 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000778
Ted Kremenekb8176da2010-09-09 04:33:05 +0000779 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000780 llvm::SmallBitVector CheckedVarArgs;
781 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000782 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000783 // Only create vector if there are format attributes.
784 CheckedVarArgs.resize(Args.size());
785
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000786 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000787 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000788 }
Richard Smithd7293d72013-08-05 18:49:43 +0000789 }
Richard Smith55ce3522012-06-25 20:30:08 +0000790
791 // Refuse POD arguments that weren't caught by the format string
792 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000793 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000795 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000796 if (const Expr *Arg = Args[ArgIdx]) {
797 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
798 checkVariadicArgument(Arg, CallType);
799 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000800 }
Richard Smithd7293d72013-08-05 18:49:43 +0000801 }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Richard Trieu41bc0992013-06-22 00:20:41 +0000803 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000804 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000805
Richard Trieu41bc0992013-06-22 00:20:41 +0000806 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000807 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
808 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000809 }
Richard Smith55ce3522012-06-25 20:30:08 +0000810}
811
812/// CheckConstructorCall - Check a constructor call for correctness and safety
813/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000814void Sema::CheckConstructorCall(FunctionDecl *FDecl,
815 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000816 const FunctionProtoType *Proto,
817 SourceLocation Loc) {
818 VariadicCallType CallType =
819 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000820 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000821 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
822}
823
824/// CheckFunctionCall - Check a direct function call for various correctness
825/// and safety properties not strictly enforced by the C type system.
826bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
827 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000828 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
829 isa<CXXMethodDecl>(FDecl);
830 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
831 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000832 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
833 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000834 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000835 Expr** Args = TheCall->getArgs();
836 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000837 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000838 // If this is a call to a member operator, hide the first argument
839 // from checkCall.
840 // FIXME: Our choice of AST representation here is less than ideal.
841 ++Args;
842 --NumArgs;
843 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000844 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000845 IsMemberFunction, TheCall->getRParenLoc(),
846 TheCall->getCallee()->getSourceRange(), CallType);
847
848 IdentifierInfo *FnInfo = FDecl->getIdentifier();
849 // None of the checks below are needed for functions that don't have
850 // simple names (e.g., C++ conversion functions).
851 if (!FnInfo)
852 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000853
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000854 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
855
Anna Zaks22122702012-01-17 00:37:07 +0000856 unsigned CMId = FDecl->getMemoryFunctionKind();
857 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000858 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000859
Anna Zaks201d4892012-01-13 21:52:01 +0000860 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000861 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000862 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000863 else if (CMId == Builtin::BIstrncat)
864 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000865 else
Anna Zaks22122702012-01-17 00:37:07 +0000866 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000867
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000868 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000869}
870
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000871bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000872 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000873 VariadicCallType CallType =
874 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000875
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000876 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000877 /*IsMemberFunction=*/false,
878 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000879
880 return false;
881}
882
Richard Trieu664c4c62013-06-20 21:03:13 +0000883bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
884 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000885 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
886 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000887 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000888
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000889 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000890 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Richard Trieu664c4c62013-06-20 21:03:13 +0000893 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000894 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000895 CallType = VariadicDoesNotApply;
896 } else if (Ty->isBlockPointerType()) {
897 CallType = VariadicBlock;
898 } else { // Ty->isFunctionPointerType()
899 CallType = VariadicFunction;
900 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000901 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000902
Alp Toker9cacbab2014-01-20 20:26:09 +0000903 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
904 TheCall->getNumArgs()),
905 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000906 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000907
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000908 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000909}
910
Richard Trieu41bc0992013-06-22 00:20:41 +0000911/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
912/// such as function pointers returned from functions.
913bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000914 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000915 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000916 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000917
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 checkCall(/*FDecl=*/nullptr,
919 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
920 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000921 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000922 TheCall->getCallee()->getSourceRange(), CallType);
923
924 return false;
925}
926
Tim Northovere94a34c2014-03-11 10:49:14 +0000927static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
928 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
929 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
930 return false;
931
932 switch (Op) {
933 case AtomicExpr::AO__c11_atomic_init:
934 llvm_unreachable("There is no ordering argument for an init");
935
936 case AtomicExpr::AO__c11_atomic_load:
937 case AtomicExpr::AO__atomic_load_n:
938 case AtomicExpr::AO__atomic_load:
939 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
940 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
941
942 case AtomicExpr::AO__c11_atomic_store:
943 case AtomicExpr::AO__atomic_store:
944 case AtomicExpr::AO__atomic_store_n:
945 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
946 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
947 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
948
949 default:
950 return true;
951 }
952}
953
Richard Smithfeea8832012-04-12 05:08:17 +0000954ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
955 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000956 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
957 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000958
Richard Smithfeea8832012-04-12 05:08:17 +0000959 // All these operations take one of the following forms:
960 enum {
961 // C __c11_atomic_init(A *, C)
962 Init,
963 // C __c11_atomic_load(A *, int)
964 Load,
965 // void __atomic_load(A *, CP, int)
966 Copy,
967 // C __c11_atomic_add(A *, M, int)
968 Arithmetic,
969 // C __atomic_exchange_n(A *, CP, int)
970 Xchg,
971 // void __atomic_exchange(A *, C *, CP, int)
972 GNUXchg,
973 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
974 C11CmpXchg,
975 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
976 GNUCmpXchg
977 } Form = Init;
978 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
979 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
980 // where:
981 // C is an appropriate type,
982 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
983 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
984 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
985 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000986
Richard Smithfeea8832012-04-12 05:08:17 +0000987 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
988 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
989 && "need to update code for modified C11 atomics");
990 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
991 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
992 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
993 Op == AtomicExpr::AO__atomic_store_n ||
994 Op == AtomicExpr::AO__atomic_exchange_n ||
995 Op == AtomicExpr::AO__atomic_compare_exchange_n;
996 bool IsAddSub = false;
997
998 switch (Op) {
999 case AtomicExpr::AO__c11_atomic_init:
1000 Form = Init;
1001 break;
1002
1003 case AtomicExpr::AO__c11_atomic_load:
1004 case AtomicExpr::AO__atomic_load_n:
1005 Form = Load;
1006 break;
1007
1008 case AtomicExpr::AO__c11_atomic_store:
1009 case AtomicExpr::AO__atomic_load:
1010 case AtomicExpr::AO__atomic_store:
1011 case AtomicExpr::AO__atomic_store_n:
1012 Form = Copy;
1013 break;
1014
1015 case AtomicExpr::AO__c11_atomic_fetch_add:
1016 case AtomicExpr::AO__c11_atomic_fetch_sub:
1017 case AtomicExpr::AO__atomic_fetch_add:
1018 case AtomicExpr::AO__atomic_fetch_sub:
1019 case AtomicExpr::AO__atomic_add_fetch:
1020 case AtomicExpr::AO__atomic_sub_fetch:
1021 IsAddSub = true;
1022 // Fall through.
1023 case AtomicExpr::AO__c11_atomic_fetch_and:
1024 case AtomicExpr::AO__c11_atomic_fetch_or:
1025 case AtomicExpr::AO__c11_atomic_fetch_xor:
1026 case AtomicExpr::AO__atomic_fetch_and:
1027 case AtomicExpr::AO__atomic_fetch_or:
1028 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001029 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001030 case AtomicExpr::AO__atomic_and_fetch:
1031 case AtomicExpr::AO__atomic_or_fetch:
1032 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001033 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001034 Form = Arithmetic;
1035 break;
1036
1037 case AtomicExpr::AO__c11_atomic_exchange:
1038 case AtomicExpr::AO__atomic_exchange_n:
1039 Form = Xchg;
1040 break;
1041
1042 case AtomicExpr::AO__atomic_exchange:
1043 Form = GNUXchg;
1044 break;
1045
1046 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1047 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1048 Form = C11CmpXchg;
1049 break;
1050
1051 case AtomicExpr::AO__atomic_compare_exchange:
1052 case AtomicExpr::AO__atomic_compare_exchange_n:
1053 Form = GNUCmpXchg;
1054 break;
1055 }
1056
1057 // Check we have the right number of arguments.
1058 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001059 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001060 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001061 << TheCall->getCallee()->getSourceRange();
1062 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001063 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1064 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001065 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001066 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001067 << TheCall->getCallee()->getSourceRange();
1068 return ExprError();
1069 }
1070
Richard Smithfeea8832012-04-12 05:08:17 +00001071 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001072 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001073 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1074 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1075 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001076 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001077 << Ptr->getType() << Ptr->getSourceRange();
1078 return ExprError();
1079 }
1080
Richard Smithfeea8832012-04-12 05:08:17 +00001081 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1082 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1083 QualType ValType = AtomTy; // 'C'
1084 if (IsC11) {
1085 if (!AtomTy->isAtomicType()) {
1086 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1087 << Ptr->getType() << Ptr->getSourceRange();
1088 return ExprError();
1089 }
Richard Smithe00921a2012-09-15 06:09:58 +00001090 if (AtomTy.isConstQualified()) {
1091 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1092 << Ptr->getType() << Ptr->getSourceRange();
1093 return ExprError();
1094 }
Richard Smithfeea8832012-04-12 05:08:17 +00001095 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001096 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001097
Richard Smithfeea8832012-04-12 05:08:17 +00001098 // For an arithmetic operation, the implied arithmetic must be well-formed.
1099 if (Form == Arithmetic) {
1100 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1101 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1102 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1103 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1104 return ExprError();
1105 }
1106 if (!IsAddSub && !ValType->isIntegerType()) {
1107 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1108 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1109 return ExprError();
1110 }
1111 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1112 // For __atomic_*_n operations, the value type must be a scalar integral or
1113 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001114 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001115 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1116 return ExprError();
1117 }
1118
Eli Friedmanaa769812013-09-11 03:49:34 +00001119 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1120 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001121 // For GNU atomics, require a trivially-copyable type. This is not part of
1122 // the GNU atomics specification, but we enforce it for sanity.
1123 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001124 << Ptr->getType() << Ptr->getSourceRange();
1125 return ExprError();
1126 }
1127
Richard Smithfeea8832012-04-12 05:08:17 +00001128 // FIXME: For any builtin other than a load, the ValType must not be
1129 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001130
1131 switch (ValType.getObjCLifetime()) {
1132 case Qualifiers::OCL_None:
1133 case Qualifiers::OCL_ExplicitNone:
1134 // okay
1135 break;
1136
1137 case Qualifiers::OCL_Weak:
1138 case Qualifiers::OCL_Strong:
1139 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001140 // FIXME: Can this happen? By this point, ValType should be known
1141 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001142 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1143 << ValType << Ptr->getSourceRange();
1144 return ExprError();
1145 }
1146
1147 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001148 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001149 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001150 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001151 ResultType = Context.BoolTy;
1152
Richard Smithfeea8832012-04-12 05:08:17 +00001153 // The type of a parameter passed 'by value'. In the GNU atomics, such
1154 // arguments are actually passed as pointers.
1155 QualType ByValType = ValType; // 'CP'
1156 if (!IsC11 && !IsN)
1157 ByValType = Ptr->getType();
1158
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001159 // The first argument --- the pointer --- has a fixed type; we
1160 // deduce the types of the rest of the arguments accordingly. Walk
1161 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001162 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001163 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001164 if (i < NumVals[Form] + 1) {
1165 switch (i) {
1166 case 1:
1167 // The second argument is the non-atomic operand. For arithmetic, this
1168 // is always passed by value, and for a compare_exchange it is always
1169 // passed by address. For the rest, GNU uses by-address and C11 uses
1170 // by-value.
1171 assert(Form != Load);
1172 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1173 Ty = ValType;
1174 else if (Form == Copy || Form == Xchg)
1175 Ty = ByValType;
1176 else if (Form == Arithmetic)
1177 Ty = Context.getPointerDiffType();
1178 else
1179 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1180 break;
1181 case 2:
1182 // The third argument to compare_exchange / GNU exchange is a
1183 // (pointer to a) desired value.
1184 Ty = ByValType;
1185 break;
1186 case 3:
1187 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1188 Ty = Context.BoolTy;
1189 break;
1190 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001191 } else {
1192 // The order(s) are always converted to int.
1193 Ty = Context.IntTy;
1194 }
Richard Smithfeea8832012-04-12 05:08:17 +00001195
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001196 InitializedEntity Entity =
1197 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001198 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001199 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1200 if (Arg.isInvalid())
1201 return true;
1202 TheCall->setArg(i, Arg.get());
1203 }
1204
Richard Smithfeea8832012-04-12 05:08:17 +00001205 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001206 SmallVector<Expr*, 5> SubExprs;
1207 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001208 switch (Form) {
1209 case Init:
1210 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001211 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001212 break;
1213 case Load:
1214 SubExprs.push_back(TheCall->getArg(1)); // Order
1215 break;
1216 case Copy:
1217 case Arithmetic:
1218 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001219 SubExprs.push_back(TheCall->getArg(2)); // Order
1220 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001221 break;
1222 case GNUXchg:
1223 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1224 SubExprs.push_back(TheCall->getArg(3)); // Order
1225 SubExprs.push_back(TheCall->getArg(1)); // Val1
1226 SubExprs.push_back(TheCall->getArg(2)); // Val2
1227 break;
1228 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001229 SubExprs.push_back(TheCall->getArg(3)); // Order
1230 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001231 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001232 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001233 break;
1234 case GNUCmpXchg:
1235 SubExprs.push_back(TheCall->getArg(4)); // Order
1236 SubExprs.push_back(TheCall->getArg(1)); // Val1
1237 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1238 SubExprs.push_back(TheCall->getArg(2)); // Val2
1239 SubExprs.push_back(TheCall->getArg(3)); // Weak
1240 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001241 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001242
1243 if (SubExprs.size() >= 2 && Form != Init) {
1244 llvm::APSInt Result(32);
1245 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1246 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001247 Diag(SubExprs[1]->getLocStart(),
1248 diag::warn_atomic_op_has_invalid_memory_order)
1249 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001250 }
1251
Fariborz Jahanian615de762013-05-28 17:37:39 +00001252 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1253 SubExprs, ResultType, Op,
1254 TheCall->getRParenLoc());
1255
1256 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1257 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1258 Context.AtomicUsesUnsupportedLibcall(AE))
1259 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1260 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001261
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001262 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001263}
1264
1265
John McCall29ad95b2011-08-27 01:09:30 +00001266/// checkBuiltinArgument - Given a call to a builtin function, perform
1267/// normal type-checking on the given argument, updating the call in
1268/// place. This is useful when a builtin function requires custom
1269/// type-checking for some of its arguments but not necessarily all of
1270/// them.
1271///
1272/// Returns true on error.
1273static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1274 FunctionDecl *Fn = E->getDirectCallee();
1275 assert(Fn && "builtin call without direct callee!");
1276
1277 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1278 InitializedEntity Entity =
1279 InitializedEntity::InitializeParameter(S.Context, Param);
1280
1281 ExprResult Arg = E->getArg(0);
1282 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1283 if (Arg.isInvalid())
1284 return true;
1285
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001286 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001287 return false;
1288}
1289
Chris Lattnerdc046542009-05-08 06:58:22 +00001290/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1291/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1292/// type of its first argument. The main ActOnCallExpr routines have already
1293/// promoted the types of arguments because all of these calls are prototyped as
1294/// void(...).
1295///
1296/// This function goes through and does final semantic checking for these
1297/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001298ExprResult
1299Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001300 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001301 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1302 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1303
1304 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001305 if (TheCall->getNumArgs() < 1) {
1306 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1307 << 0 << 1 << TheCall->getNumArgs()
1308 << TheCall->getCallee()->getSourceRange();
1309 return ExprError();
1310 }
Mike Stump11289f42009-09-09 15:08:12 +00001311
Chris Lattnerdc046542009-05-08 06:58:22 +00001312 // Inspect the first argument of the atomic builtin. This should always be
1313 // a pointer type, whose element is an integral scalar or pointer type.
1314 // Because it is a pointer type, we don't have to worry about any implicit
1315 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001316 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001317 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001318 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1319 if (FirstArgResult.isInvalid())
1320 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001321 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001322 TheCall->setArg(0, FirstArg);
1323
John McCall31168b02011-06-15 23:02:42 +00001324 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1325 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001326 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1327 << FirstArg->getType() << FirstArg->getSourceRange();
1328 return ExprError();
1329 }
Mike Stump11289f42009-09-09 15:08:12 +00001330
John McCall31168b02011-06-15 23:02:42 +00001331 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001332 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001333 !ValType->isBlockPointerType()) {
1334 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1335 << FirstArg->getType() << FirstArg->getSourceRange();
1336 return ExprError();
1337 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001338
John McCall31168b02011-06-15 23:02:42 +00001339 switch (ValType.getObjCLifetime()) {
1340 case Qualifiers::OCL_None:
1341 case Qualifiers::OCL_ExplicitNone:
1342 // okay
1343 break;
1344
1345 case Qualifiers::OCL_Weak:
1346 case Qualifiers::OCL_Strong:
1347 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001348 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001349 << ValType << FirstArg->getSourceRange();
1350 return ExprError();
1351 }
1352
John McCallb50451a2011-10-05 07:41:44 +00001353 // Strip any qualifiers off ValType.
1354 ValType = ValType.getUnqualifiedType();
1355
Chandler Carruth3973af72010-07-18 20:54:12 +00001356 // The majority of builtins return a value, but a few have special return
1357 // types, so allow them to override appropriately below.
1358 QualType ResultType = ValType;
1359
Chris Lattnerdc046542009-05-08 06:58:22 +00001360 // We need to figure out which concrete builtin this maps onto. For example,
1361 // __sync_fetch_and_add with a 2 byte object turns into
1362 // __sync_fetch_and_add_2.
1363#define BUILTIN_ROW(x) \
1364 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1365 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattnerdc046542009-05-08 06:58:22 +00001367 static const unsigned BuiltinIndices[][5] = {
1368 BUILTIN_ROW(__sync_fetch_and_add),
1369 BUILTIN_ROW(__sync_fetch_and_sub),
1370 BUILTIN_ROW(__sync_fetch_and_or),
1371 BUILTIN_ROW(__sync_fetch_and_and),
1372 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001373
Chris Lattnerdc046542009-05-08 06:58:22 +00001374 BUILTIN_ROW(__sync_add_and_fetch),
1375 BUILTIN_ROW(__sync_sub_and_fetch),
1376 BUILTIN_ROW(__sync_and_and_fetch),
1377 BUILTIN_ROW(__sync_or_and_fetch),
1378 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001379
Chris Lattnerdc046542009-05-08 06:58:22 +00001380 BUILTIN_ROW(__sync_val_compare_and_swap),
1381 BUILTIN_ROW(__sync_bool_compare_and_swap),
1382 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001383 BUILTIN_ROW(__sync_lock_release),
1384 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001385 };
Mike Stump11289f42009-09-09 15:08:12 +00001386#undef BUILTIN_ROW
1387
Chris Lattnerdc046542009-05-08 06:58:22 +00001388 // Determine the index of the size.
1389 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001390 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001391 case 1: SizeIndex = 0; break;
1392 case 2: SizeIndex = 1; break;
1393 case 4: SizeIndex = 2; break;
1394 case 8: SizeIndex = 3; break;
1395 case 16: SizeIndex = 4; break;
1396 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001397 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1398 << FirstArg->getType() << FirstArg->getSourceRange();
1399 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001400 }
Mike Stump11289f42009-09-09 15:08:12 +00001401
Chris Lattnerdc046542009-05-08 06:58:22 +00001402 // Each of these builtins has one pointer argument, followed by some number of
1403 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1404 // that we ignore. Find out which row of BuiltinIndices to read from as well
1405 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001406 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001407 unsigned BuiltinIndex, NumFixed = 1;
1408 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001409 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001410 case Builtin::BI__sync_fetch_and_add:
1411 case Builtin::BI__sync_fetch_and_add_1:
1412 case Builtin::BI__sync_fetch_and_add_2:
1413 case Builtin::BI__sync_fetch_and_add_4:
1414 case Builtin::BI__sync_fetch_and_add_8:
1415 case Builtin::BI__sync_fetch_and_add_16:
1416 BuiltinIndex = 0;
1417 break;
1418
1419 case Builtin::BI__sync_fetch_and_sub:
1420 case Builtin::BI__sync_fetch_and_sub_1:
1421 case Builtin::BI__sync_fetch_and_sub_2:
1422 case Builtin::BI__sync_fetch_and_sub_4:
1423 case Builtin::BI__sync_fetch_and_sub_8:
1424 case Builtin::BI__sync_fetch_and_sub_16:
1425 BuiltinIndex = 1;
1426 break;
1427
1428 case Builtin::BI__sync_fetch_and_or:
1429 case Builtin::BI__sync_fetch_and_or_1:
1430 case Builtin::BI__sync_fetch_and_or_2:
1431 case Builtin::BI__sync_fetch_and_or_4:
1432 case Builtin::BI__sync_fetch_and_or_8:
1433 case Builtin::BI__sync_fetch_and_or_16:
1434 BuiltinIndex = 2;
1435 break;
1436
1437 case Builtin::BI__sync_fetch_and_and:
1438 case Builtin::BI__sync_fetch_and_and_1:
1439 case Builtin::BI__sync_fetch_and_and_2:
1440 case Builtin::BI__sync_fetch_and_and_4:
1441 case Builtin::BI__sync_fetch_and_and_8:
1442 case Builtin::BI__sync_fetch_and_and_16:
1443 BuiltinIndex = 3;
1444 break;
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregor73722482011-11-28 16:30:08 +00001446 case Builtin::BI__sync_fetch_and_xor:
1447 case Builtin::BI__sync_fetch_and_xor_1:
1448 case Builtin::BI__sync_fetch_and_xor_2:
1449 case Builtin::BI__sync_fetch_and_xor_4:
1450 case Builtin::BI__sync_fetch_and_xor_8:
1451 case Builtin::BI__sync_fetch_and_xor_16:
1452 BuiltinIndex = 4;
1453 break;
1454
1455 case Builtin::BI__sync_add_and_fetch:
1456 case Builtin::BI__sync_add_and_fetch_1:
1457 case Builtin::BI__sync_add_and_fetch_2:
1458 case Builtin::BI__sync_add_and_fetch_4:
1459 case Builtin::BI__sync_add_and_fetch_8:
1460 case Builtin::BI__sync_add_and_fetch_16:
1461 BuiltinIndex = 5;
1462 break;
1463
1464 case Builtin::BI__sync_sub_and_fetch:
1465 case Builtin::BI__sync_sub_and_fetch_1:
1466 case Builtin::BI__sync_sub_and_fetch_2:
1467 case Builtin::BI__sync_sub_and_fetch_4:
1468 case Builtin::BI__sync_sub_and_fetch_8:
1469 case Builtin::BI__sync_sub_and_fetch_16:
1470 BuiltinIndex = 6;
1471 break;
1472
1473 case Builtin::BI__sync_and_and_fetch:
1474 case Builtin::BI__sync_and_and_fetch_1:
1475 case Builtin::BI__sync_and_and_fetch_2:
1476 case Builtin::BI__sync_and_and_fetch_4:
1477 case Builtin::BI__sync_and_and_fetch_8:
1478 case Builtin::BI__sync_and_and_fetch_16:
1479 BuiltinIndex = 7;
1480 break;
1481
1482 case Builtin::BI__sync_or_and_fetch:
1483 case Builtin::BI__sync_or_and_fetch_1:
1484 case Builtin::BI__sync_or_and_fetch_2:
1485 case Builtin::BI__sync_or_and_fetch_4:
1486 case Builtin::BI__sync_or_and_fetch_8:
1487 case Builtin::BI__sync_or_and_fetch_16:
1488 BuiltinIndex = 8;
1489 break;
1490
1491 case Builtin::BI__sync_xor_and_fetch:
1492 case Builtin::BI__sync_xor_and_fetch_1:
1493 case Builtin::BI__sync_xor_and_fetch_2:
1494 case Builtin::BI__sync_xor_and_fetch_4:
1495 case Builtin::BI__sync_xor_and_fetch_8:
1496 case Builtin::BI__sync_xor_and_fetch_16:
1497 BuiltinIndex = 9;
1498 break;
Mike Stump11289f42009-09-09 15:08:12 +00001499
Chris Lattnerdc046542009-05-08 06:58:22 +00001500 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001501 case Builtin::BI__sync_val_compare_and_swap_1:
1502 case Builtin::BI__sync_val_compare_and_swap_2:
1503 case Builtin::BI__sync_val_compare_and_swap_4:
1504 case Builtin::BI__sync_val_compare_and_swap_8:
1505 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001506 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001507 NumFixed = 2;
1508 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001509
Chris Lattnerdc046542009-05-08 06:58:22 +00001510 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001511 case Builtin::BI__sync_bool_compare_and_swap_1:
1512 case Builtin::BI__sync_bool_compare_and_swap_2:
1513 case Builtin::BI__sync_bool_compare_and_swap_4:
1514 case Builtin::BI__sync_bool_compare_and_swap_8:
1515 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001516 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001517 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001518 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001519 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001520
1521 case Builtin::BI__sync_lock_test_and_set:
1522 case Builtin::BI__sync_lock_test_and_set_1:
1523 case Builtin::BI__sync_lock_test_and_set_2:
1524 case Builtin::BI__sync_lock_test_and_set_4:
1525 case Builtin::BI__sync_lock_test_and_set_8:
1526 case Builtin::BI__sync_lock_test_and_set_16:
1527 BuiltinIndex = 12;
1528 break;
1529
Chris Lattnerdc046542009-05-08 06:58:22 +00001530 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001531 case Builtin::BI__sync_lock_release_1:
1532 case Builtin::BI__sync_lock_release_2:
1533 case Builtin::BI__sync_lock_release_4:
1534 case Builtin::BI__sync_lock_release_8:
1535 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001536 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001537 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001538 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001539 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001540
1541 case Builtin::BI__sync_swap:
1542 case Builtin::BI__sync_swap_1:
1543 case Builtin::BI__sync_swap_2:
1544 case Builtin::BI__sync_swap_4:
1545 case Builtin::BI__sync_swap_8:
1546 case Builtin::BI__sync_swap_16:
1547 BuiltinIndex = 14;
1548 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001549 }
Mike Stump11289f42009-09-09 15:08:12 +00001550
Chris Lattnerdc046542009-05-08 06:58:22 +00001551 // Now that we know how many fixed arguments we expect, first check that we
1552 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001553 if (TheCall->getNumArgs() < 1+NumFixed) {
1554 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1555 << 0 << 1+NumFixed << TheCall->getNumArgs()
1556 << TheCall->getCallee()->getSourceRange();
1557 return ExprError();
1558 }
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattner5b9241b2009-05-08 15:36:58 +00001560 // Get the decl for the concrete builtin from this, we can tell what the
1561 // concrete integer type we should convert to is.
1562 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1563 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001564 FunctionDecl *NewBuiltinDecl;
1565 if (NewBuiltinID == BuiltinID)
1566 NewBuiltinDecl = FDecl;
1567 else {
1568 // Perform builtin lookup to avoid redeclaring it.
1569 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1570 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1571 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1572 assert(Res.getFoundDecl());
1573 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001574 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001575 return ExprError();
1576 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001577
John McCallcf142162010-08-07 06:22:56 +00001578 // The first argument --- the pointer --- has a fixed type; we
1579 // deduce the types of the rest of the arguments accordingly. Walk
1580 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001581 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001582 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001583
Chris Lattnerdc046542009-05-08 06:58:22 +00001584 // GCC does an implicit conversion to the pointer or integer ValType. This
1585 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001586 // Initialize the argument.
1587 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1588 ValType, /*consume*/ false);
1589 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001590 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001591 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001592
Chris Lattnerdc046542009-05-08 06:58:22 +00001593 // Okay, we have something that *can* be converted to the right type. Check
1594 // to see if there is a potentially weird extension going on here. This can
1595 // happen when you do an atomic operation on something like an char* and
1596 // pass in 42. The 42 gets converted to char. This is even more strange
1597 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001598 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001599 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001600 }
Mike Stump11289f42009-09-09 15:08:12 +00001601
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001602 ASTContext& Context = this->getASTContext();
1603
1604 // Create a new DeclRefExpr to refer to the new decl.
1605 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1606 Context,
1607 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001608 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001609 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001610 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001611 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001612 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001613 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001614
Chris Lattnerdc046542009-05-08 06:58:22 +00001615 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001616 // FIXME: This loses syntactic information.
1617 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1618 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1619 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001620 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001621
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001622 // Change the result type of the call to match the original value type. This
1623 // is arbitrary, but the codegen for these builtins ins design to handle it
1624 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001625 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001626
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001627 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001628}
1629
Chris Lattner6436fb62009-02-18 06:01:06 +00001630/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001631/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001632/// Note: It might also make sense to do the UTF-16 conversion here (would
1633/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001634bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001635 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001636 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1637
Douglas Gregorfb65e592011-07-27 05:40:30 +00001638 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001639 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1640 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001641 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001642 }
Mike Stump11289f42009-09-09 15:08:12 +00001643
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001644 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001645 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001646 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001647 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001648 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001649 UTF16 *ToPtr = &ToBuf[0];
1650
1651 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1652 &ToPtr, ToPtr + NumBytes,
1653 strictConversion);
1654 // Check for conversion failure.
1655 if (Result != conversionOK)
1656 Diag(Arg->getLocStart(),
1657 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1658 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001659 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001660}
1661
Chris Lattnere202e6a2007-12-20 00:05:45 +00001662/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1663/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001664bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1665 Expr *Fn = TheCall->getCallee();
1666 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001667 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001668 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001669 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1670 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001671 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001672 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001673 return true;
1674 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001675
1676 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001677 return Diag(TheCall->getLocEnd(),
1678 diag::err_typecheck_call_too_few_args_at_least)
1679 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001680 }
1681
John McCall29ad95b2011-08-27 01:09:30 +00001682 // Type-check the first argument normally.
1683 if (checkBuiltinArgument(*this, TheCall, 0))
1684 return true;
1685
Chris Lattnere202e6a2007-12-20 00:05:45 +00001686 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001687 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001688 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001689 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001690 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001691 else if (FunctionDecl *FD = getCurFunctionDecl())
1692 isVariadic = FD->isVariadic();
1693 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001694 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattnere202e6a2007-12-20 00:05:45 +00001696 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001697 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1698 return true;
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Chris Lattner43be2e62007-12-19 23:59:04 +00001701 // Verify that the second argument to the builtin is the last argument of the
1702 // current function or method.
1703 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001704 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001705
Nico Weber9eea7642013-05-24 23:31:57 +00001706 // These are valid if SecondArgIsLastNamedArgument is false after the next
1707 // block.
1708 QualType Type;
1709 SourceLocation ParamLoc;
1710
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001711 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1712 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001713 // FIXME: This isn't correct for methods (results in bogus warning).
1714 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001715 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001716 if (CurBlock)
1717 LastArg = *(CurBlock->TheDecl->param_end()-1);
1718 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001719 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001720 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001721 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001722 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001723
1724 Type = PV->getType();
1725 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001726 }
1727 }
Mike Stump11289f42009-09-09 15:08:12 +00001728
Chris Lattner43be2e62007-12-19 23:59:04 +00001729 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001730 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001731 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001732 else if (Type->isReferenceType()) {
1733 Diag(Arg->getLocStart(),
1734 diag::warn_va_start_of_reference_type_is_undefined);
1735 Diag(ParamLoc, diag::note_parameter_type) << Type;
1736 }
1737
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001738 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001739 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001740}
Chris Lattner43be2e62007-12-19 23:59:04 +00001741
Chris Lattner2da14fb2007-12-20 00:26:33 +00001742/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1743/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001744bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1745 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001746 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001747 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001748 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001749 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001750 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001751 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001752 << SourceRange(TheCall->getArg(2)->getLocStart(),
1753 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001754
John Wiegley01296292011-04-08 18:41:53 +00001755 ExprResult OrigArg0 = TheCall->getArg(0);
1756 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001757
Chris Lattner2da14fb2007-12-20 00:26:33 +00001758 // Do standard promotions between the two arguments, returning their common
1759 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001760 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001761 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1762 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001763
1764 // Make sure any conversions are pushed back into the call; this is
1765 // type safe since unordered compare builtins are declared as "_Bool
1766 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001767 TheCall->setArg(0, OrigArg0.get());
1768 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001769
John Wiegley01296292011-04-08 18:41:53 +00001770 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001771 return false;
1772
Chris Lattner2da14fb2007-12-20 00:26:33 +00001773 // If the common type isn't a real floating type, then the arguments were
1774 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001775 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001776 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001777 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001778 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1779 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001780
Chris Lattner2da14fb2007-12-20 00:26:33 +00001781 return false;
1782}
1783
Benjamin Kramer634fc102010-02-15 22:42:31 +00001784/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1785/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001786/// to check everything. We expect the last argument to be a floating point
1787/// value.
1788bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1789 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001790 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001791 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001792 if (TheCall->getNumArgs() > NumArgs)
1793 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001794 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001795 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001796 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001797 (*(TheCall->arg_end()-1))->getLocEnd());
1798
Benjamin Kramer64aae502010-02-16 10:07:31 +00001799 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001800
Eli Friedman7e4faac2009-08-31 20:06:00 +00001801 if (OrigArg->isTypeDependent())
1802 return false;
1803
Chris Lattner68784ef2010-05-06 05:50:07 +00001804 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001805 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001806 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001807 diag::err_typecheck_call_invalid_unary_fp)
1808 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001809
Chris Lattner68784ef2010-05-06 05:50:07 +00001810 // If this is an implicit conversion from float -> double, remove it.
1811 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1812 Expr *CastArg = Cast->getSubExpr();
1813 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1814 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1815 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001816 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001817 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001818 }
1819 }
1820
Eli Friedman7e4faac2009-08-31 20:06:00 +00001821 return false;
1822}
1823
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001824/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1825// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001826ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001827 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001828 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001829 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001830 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1831 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001832
Nate Begemana0110022010-06-08 00:16:34 +00001833 // Determine which of the following types of shufflevector we're checking:
1834 // 1) unary, vector mask: (lhs, mask)
1835 // 2) binary, vector mask: (lhs, rhs, mask)
1836 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1837 QualType resType = TheCall->getArg(0)->getType();
1838 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001839
Douglas Gregorc25f7662009-05-19 22:10:17 +00001840 if (!TheCall->getArg(0)->isTypeDependent() &&
1841 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001842 QualType LHSType = TheCall->getArg(0)->getType();
1843 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001844
Craig Topperbaca3892013-07-29 06:47:04 +00001845 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1846 return ExprError(Diag(TheCall->getLocStart(),
1847 diag::err_shufflevector_non_vector)
1848 << SourceRange(TheCall->getArg(0)->getLocStart(),
1849 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001850
Nate Begemana0110022010-06-08 00:16:34 +00001851 numElements = LHSType->getAs<VectorType>()->getNumElements();
1852 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001853
Nate Begemana0110022010-06-08 00:16:34 +00001854 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1855 // with mask. If so, verify that RHS is an integer vector type with the
1856 // same number of elts as lhs.
1857 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001858 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001859 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001860 return ExprError(Diag(TheCall->getLocStart(),
1861 diag::err_shufflevector_incompatible_vector)
1862 << SourceRange(TheCall->getArg(1)->getLocStart(),
1863 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001864 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001865 return ExprError(Diag(TheCall->getLocStart(),
1866 diag::err_shufflevector_incompatible_vector)
1867 << SourceRange(TheCall->getArg(0)->getLocStart(),
1868 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001869 } else if (numElements != numResElements) {
1870 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001871 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001872 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001873 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001874 }
1875
1876 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001877 if (TheCall->getArg(i)->isTypeDependent() ||
1878 TheCall->getArg(i)->isValueDependent())
1879 continue;
1880
Nate Begemana0110022010-06-08 00:16:34 +00001881 llvm::APSInt Result(32);
1882 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1883 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001884 diag::err_shufflevector_nonconstant_argument)
1885 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001886
Craig Topper50ad5b72013-08-03 17:40:38 +00001887 // Allow -1 which will be translated to undef in the IR.
1888 if (Result.isSigned() && Result.isAllOnesValue())
1889 continue;
1890
Chris Lattner7ab824e2008-08-10 02:05:13 +00001891 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001892 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001893 diag::err_shufflevector_argument_too_large)
1894 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001895 }
1896
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001897 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001898
Chris Lattner7ab824e2008-08-10 02:05:13 +00001899 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001900 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001901 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001902 }
1903
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001904 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1905 TheCall->getCallee()->getLocStart(),
1906 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001907}
Chris Lattner43be2e62007-12-19 23:59:04 +00001908
Hal Finkelc4d7c822013-09-18 03:29:45 +00001909/// SemaConvertVectorExpr - Handle __builtin_convertvector
1910ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1911 SourceLocation BuiltinLoc,
1912 SourceLocation RParenLoc) {
1913 ExprValueKind VK = VK_RValue;
1914 ExprObjectKind OK = OK_Ordinary;
1915 QualType DstTy = TInfo->getType();
1916 QualType SrcTy = E->getType();
1917
1918 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1919 return ExprError(Diag(BuiltinLoc,
1920 diag::err_convertvector_non_vector)
1921 << E->getSourceRange());
1922 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1923 return ExprError(Diag(BuiltinLoc,
1924 diag::err_convertvector_non_vector_type));
1925
1926 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1927 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1928 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1929 if (SrcElts != DstElts)
1930 return ExprError(Diag(BuiltinLoc,
1931 diag::err_convertvector_incompatible_vector)
1932 << E->getSourceRange());
1933 }
1934
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001935 return new (Context)
1936 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001937}
1938
Daniel Dunbarb7257262008-07-21 22:59:13 +00001939/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1940// This is declared to take (const void*, ...) and can take two
1941// optional constant int args.
1942bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001943 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001944
Chris Lattner3b054132008-11-19 05:08:23 +00001945 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001946 return Diag(TheCall->getLocEnd(),
1947 diag::err_typecheck_call_too_many_args_at_most)
1948 << 0 /*function call*/ << 3 << NumArgs
1949 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001950
1951 // Argument 0 is checked for us and the remaining arguments must be
1952 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001953 for (unsigned i = 1; i != NumArgs; ++i)
1954 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001955 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001956
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001957 return false;
1958}
1959
Hal Finkelf0417332014-07-17 14:25:55 +00001960/// SemaBuiltinAssume - Handle __assume (MS Extension).
1961// __assume does not evaluate its arguments, and should warn if its argument
1962// has side effects.
1963bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
1964 Expr *Arg = TheCall->getArg(0);
1965 if (Arg->isInstantiationDependent()) return false;
1966
1967 if (Arg->HasSideEffects(Context))
1968 return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
1969 << Arg->getSourceRange();
1970
1971 return false;
1972}
1973
Eric Christopher8d0c6212010-04-17 02:26:23 +00001974/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1975/// TheCall is a constant expression.
1976bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1977 llvm::APSInt &Result) {
1978 Expr *Arg = TheCall->getArg(ArgNum);
1979 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1980 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1981
1982 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1983
1984 if (!Arg->isIntegerConstantExpr(Result, Context))
1985 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001986 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001987
Chris Lattnerd545ad12009-09-23 06:06:36 +00001988 return false;
1989}
1990
Richard Sandiford28940af2014-04-16 08:47:51 +00001991/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1992/// TheCall is a constant expression in the range [Low, High].
1993bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1994 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001995 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001996
1997 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001998 Expr *Arg = TheCall->getArg(ArgNum);
1999 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002000 return false;
2001
Eric Christopher8d0c6212010-04-17 02:26:23 +00002002 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002003 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002004 return true;
2005
Richard Sandiford28940af2014-04-16 08:47:51 +00002006 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002007 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002008 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002009
2010 return false;
2011}
2012
Eli Friedmanc97d0142009-05-03 06:04:26 +00002013/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002014/// This checks that val is a constant 1.
2015bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2016 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002017 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002018
Eric Christopher8d0c6212010-04-17 02:26:23 +00002019 // TODO: This is less than ideal. Overload this to take a value.
2020 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2021 return true;
2022
2023 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002024 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2025 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2026
2027 return false;
2028}
2029
Richard Smithd7293d72013-08-05 18:49:43 +00002030namespace {
2031enum StringLiteralCheckType {
2032 SLCT_NotALiteral,
2033 SLCT_UncheckedLiteral,
2034 SLCT_CheckedLiteral
2035};
2036}
2037
Richard Smith55ce3522012-06-25 20:30:08 +00002038// Determine if an expression is a string literal or constant string.
2039// If this function returns false on the arguments to a function expecting a
2040// format string, we will usually need to emit a warning.
2041// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002042static StringLiteralCheckType
2043checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2044 bool HasVAListArg, unsigned format_idx,
2045 unsigned firstDataArg, Sema::FormatStringType Type,
2046 Sema::VariadicCallType CallType, bool InFunctionCall,
2047 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002048 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002049 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002050 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002051
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002052 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002053
Richard Smithd7293d72013-08-05 18:49:43 +00002054 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002055 // Technically -Wformat-nonliteral does not warn about this case.
2056 // The behavior of printf and friends in this case is implementation
2057 // dependent. Ideally if the format string cannot be null then
2058 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002059 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002060
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002061 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002062 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002063 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002064 // The expression is a literal if both sub-expressions were, and it was
2065 // completely checked only if both sub-expressions were checked.
2066 const AbstractConditionalOperator *C =
2067 cast<AbstractConditionalOperator>(E);
2068 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002069 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002070 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002071 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002072 if (Left == SLCT_NotALiteral)
2073 return SLCT_NotALiteral;
2074 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002075 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002076 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002077 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002078 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002079 }
2080
2081 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002082 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2083 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002084 }
2085
John McCallc07a0c72011-02-17 10:25:35 +00002086 case Stmt::OpaqueValueExprClass:
2087 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2088 E = src;
2089 goto tryAgain;
2090 }
Richard Smith55ce3522012-06-25 20:30:08 +00002091 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002092
Ted Kremeneka8890832011-02-24 23:03:04 +00002093 case Stmt::PredefinedExprClass:
2094 // While __func__, etc., are technically not string literals, they
2095 // cannot contain format specifiers and thus are not a security
2096 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002097 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002098
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002099 case Stmt::DeclRefExprClass: {
2100 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002101
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002102 // As an exception, do not flag errors for variables binding to
2103 // const string literals.
2104 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2105 bool isConstant = false;
2106 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002107
Richard Smithd7293d72013-08-05 18:49:43 +00002108 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2109 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002110 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002111 isConstant = T.isConstant(S.Context) &&
2112 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002113 } else if (T->isObjCObjectPointerType()) {
2114 // In ObjC, there is usually no "const ObjectPointer" type,
2115 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002116 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002117 }
Mike Stump11289f42009-09-09 15:08:12 +00002118
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002119 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002120 if (const Expr *Init = VD->getAnyInitializer()) {
2121 // Look through initializers like const char c[] = { "foo" }
2122 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2123 if (InitList->isStringLiteralInit())
2124 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2125 }
Richard Smithd7293d72013-08-05 18:49:43 +00002126 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002127 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002128 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002129 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002130 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002131 }
Mike Stump11289f42009-09-09 15:08:12 +00002132
Anders Carlssonb012ca92009-06-28 19:55:58 +00002133 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2134 // special check to see if the format string is a function parameter
2135 // of the function calling the printf function. If the function
2136 // has an attribute indicating it is a printf-like function, then we
2137 // should suppress warnings concerning non-literals being used in a call
2138 // to a vprintf function. For example:
2139 //
2140 // void
2141 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2142 // va_list ap;
2143 // va_start(ap, fmt);
2144 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2145 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002146 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002147 if (HasVAListArg) {
2148 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2149 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2150 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002151 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002152 // adjust for implicit parameter
2153 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2154 if (MD->isInstance())
2155 ++PVIndex;
2156 // We also check if the formats are compatible.
2157 // We can't pass a 'scanf' string to a 'printf' function.
2158 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002159 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002160 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002161 }
2162 }
2163 }
2164 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002165 }
Mike Stump11289f42009-09-09 15:08:12 +00002166
Richard Smith55ce3522012-06-25 20:30:08 +00002167 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002168 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002169
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002170 case Stmt::CallExprClass:
2171 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002172 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002173 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2174 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2175 unsigned ArgIndex = FA->getFormatIdx();
2176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2177 if (MD->isInstance())
2178 --ArgIndex;
2179 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002180
Richard Smithd7293d72013-08-05 18:49:43 +00002181 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002182 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002183 Type, CallType, InFunctionCall,
2184 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002185 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2186 unsigned BuiltinID = FD->getBuiltinID();
2187 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2188 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2189 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002190 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002191 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002192 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002193 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002194 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002195 }
2196 }
Mike Stump11289f42009-09-09 15:08:12 +00002197
Richard Smith55ce3522012-06-25 20:30:08 +00002198 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002199 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002200 case Stmt::ObjCStringLiteralClass:
2201 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002202 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002203
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002204 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002205 StrE = ObjCFExpr->getString();
2206 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002207 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002208
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002209 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002210 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2211 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002212 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002213 }
Mike Stump11289f42009-09-09 15:08:12 +00002214
Richard Smith55ce3522012-06-25 20:30:08 +00002215 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002216 }
Mike Stump11289f42009-09-09 15:08:12 +00002217
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002218 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002219 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002220 }
2221}
2222
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002223Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002224 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002225 .Case("scanf", FST_Scanf)
2226 .Cases("printf", "printf0", FST_Printf)
2227 .Cases("NSString", "CFString", FST_NSString)
2228 .Case("strftime", FST_Strftime)
2229 .Case("strfmon", FST_Strfmon)
2230 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2231 .Default(FST_Unknown);
2232}
2233
Jordan Rose3e0ec582012-07-19 18:10:23 +00002234/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002235/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002236/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002237bool Sema::CheckFormatArguments(const FormatAttr *Format,
2238 ArrayRef<const Expr *> Args,
2239 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002240 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002241 SourceLocation Loc, SourceRange Range,
2242 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002243 FormatStringInfo FSI;
2244 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002245 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002246 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002247 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002248 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002249}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002250
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002251bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002252 bool HasVAListArg, unsigned format_idx,
2253 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002254 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002255 SourceLocation Loc, SourceRange Range,
2256 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002257 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002258 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002259 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002260 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002261 }
Mike Stump11289f42009-09-09 15:08:12 +00002262
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002263 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002264
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002265 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002266 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002267 // Dynamically generated format strings are difficult to
2268 // automatically vet at compile time. Requiring that format strings
2269 // are string literals: (1) permits the checking of format strings by
2270 // the compiler and thereby (2) can practically remove the source of
2271 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002272
Mike Stump11289f42009-09-09 15:08:12 +00002273 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002274 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002275 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002276 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002277 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002278 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2279 format_idx, firstDataArg, Type, CallType,
2280 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002281 if (CT != SLCT_NotALiteral)
2282 // Literal format string found, check done!
2283 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002284
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002285 // Strftime is particular as it always uses a single 'time' argument,
2286 // so it is safe to pass a non-literal string.
2287 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002288 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002289
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002290 // Do not emit diag when the string param is a macro expansion and the
2291 // format is either NSString or CFString. This is a hack to prevent
2292 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2293 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002294 if (Type == FST_NSString &&
2295 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002296 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002297
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002298 // If there are no arguments specified, warn with -Wformat-security, otherwise
2299 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002300 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002301 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002302 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002303 << OrigFormatExpr->getSourceRange();
2304 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002305 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002306 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002307 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002308 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002309}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002310
Ted Kremenekab278de2010-01-28 23:39:18 +00002311namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002312class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2313protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002314 Sema &S;
2315 const StringLiteral *FExpr;
2316 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002317 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002318 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002319 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002320 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002321 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002322 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002323 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002324 bool usesPositionalArgs;
2325 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002326 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002327 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002328 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002329public:
Ted Kremenek02087932010-07-16 02:11:22 +00002330 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002331 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002332 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002333 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002334 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002335 Sema::VariadicCallType callType,
2336 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002337 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002338 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2339 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002340 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002341 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002342 inFunctionCall(inFunctionCall), CallType(callType),
2343 CheckedVarArgs(CheckedVarArgs) {
2344 CoveredArgs.resize(numDataArgs);
2345 CoveredArgs.reset();
2346 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002347
Ted Kremenek019d2242010-01-29 01:50:07 +00002348 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002349
Ted Kremenek02087932010-07-16 02:11:22 +00002350 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002351 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002352
Jordan Rose92303592012-09-08 04:00:03 +00002353 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002354 const analyze_format_string::FormatSpecifier &FS,
2355 const analyze_format_string::ConversionSpecifier &CS,
2356 const char *startSpecifier, unsigned specifierLen,
2357 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002358
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002359 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002360 const analyze_format_string::FormatSpecifier &FS,
2361 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002362
2363 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002364 const analyze_format_string::ConversionSpecifier &CS,
2365 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002366
Craig Toppere14c0f82014-03-12 04:55:44 +00002367 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002368
Craig Toppere14c0f82014-03-12 04:55:44 +00002369 void HandleInvalidPosition(const char *startSpecifier,
2370 unsigned specifierLen,
2371 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002372
Craig Toppere14c0f82014-03-12 04:55:44 +00002373 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002374
Craig Toppere14c0f82014-03-12 04:55:44 +00002375 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002376
Richard Trieu03cf7b72011-10-28 00:41:25 +00002377 template <typename Range>
2378 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2379 const Expr *ArgumentExpr,
2380 PartialDiagnostic PDiag,
2381 SourceLocation StringLoc,
2382 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002383 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002384
Ted Kremenek02087932010-07-16 02:11:22 +00002385protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002386 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2387 const char *startSpec,
2388 unsigned specifierLen,
2389 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002390
2391 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2392 const char *startSpec,
2393 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002394
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002395 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002396 CharSourceRange getSpecifierRange(const char *startSpecifier,
2397 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002398 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002399
Ted Kremenek5739de72010-01-29 01:06:55 +00002400 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002401
2402 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2403 const analyze_format_string::ConversionSpecifier &CS,
2404 const char *startSpecifier, unsigned specifierLen,
2405 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002406
2407 template <typename Range>
2408 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2409 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002410 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002411};
2412}
2413
Ted Kremenek02087932010-07-16 02:11:22 +00002414SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002415 return OrigFormatExpr->getSourceRange();
2416}
2417
Ted Kremenek02087932010-07-16 02:11:22 +00002418CharSourceRange CheckFormatHandler::
2419getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002420 SourceLocation Start = getLocationOfByte(startSpecifier);
2421 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2422
2423 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002424 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002425
2426 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002427}
2428
Ted Kremenek02087932010-07-16 02:11:22 +00002429SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002430 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002431}
2432
Ted Kremenek02087932010-07-16 02:11:22 +00002433void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2434 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002435 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2436 getLocationOfByte(startSpecifier),
2437 /*IsStringLocation*/true,
2438 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002439}
2440
Jordan Rose92303592012-09-08 04:00:03 +00002441void CheckFormatHandler::HandleInvalidLengthModifier(
2442 const analyze_format_string::FormatSpecifier &FS,
2443 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002444 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002445 using namespace analyze_format_string;
2446
2447 const LengthModifier &LM = FS.getLengthModifier();
2448 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2449
2450 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002451 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002452 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002453 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002454 getLocationOfByte(LM.getStart()),
2455 /*IsStringLocation*/true,
2456 getSpecifierRange(startSpecifier, specifierLen));
2457
2458 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2459 << FixedLM->toString()
2460 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2461
2462 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002463 FixItHint Hint;
2464 if (DiagID == diag::warn_format_nonsensical_length)
2465 Hint = FixItHint::CreateRemoval(LMRange);
2466
2467 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002468 getLocationOfByte(LM.getStart()),
2469 /*IsStringLocation*/true,
2470 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002471 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002472 }
2473}
2474
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002475void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002476 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002477 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002478 using namespace analyze_format_string;
2479
2480 const LengthModifier &LM = FS.getLengthModifier();
2481 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2482
2483 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002484 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002485 if (FixedLM) {
2486 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2487 << LM.toString() << 0,
2488 getLocationOfByte(LM.getStart()),
2489 /*IsStringLocation*/true,
2490 getSpecifierRange(startSpecifier, specifierLen));
2491
2492 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2493 << FixedLM->toString()
2494 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2495
2496 } else {
2497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2498 << LM.toString() << 0,
2499 getLocationOfByte(LM.getStart()),
2500 /*IsStringLocation*/true,
2501 getSpecifierRange(startSpecifier, specifierLen));
2502 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002503}
2504
2505void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2506 const analyze_format_string::ConversionSpecifier &CS,
2507 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002508 using namespace analyze_format_string;
2509
2510 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002511 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002512 if (FixedCS) {
2513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2514 << CS.toString() << /*conversion specifier*/1,
2515 getLocationOfByte(CS.getStart()),
2516 /*IsStringLocation*/true,
2517 getSpecifierRange(startSpecifier, specifierLen));
2518
2519 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2520 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2521 << FixedCS->toString()
2522 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2523 } else {
2524 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2525 << CS.toString() << /*conversion specifier*/1,
2526 getLocationOfByte(CS.getStart()),
2527 /*IsStringLocation*/true,
2528 getSpecifierRange(startSpecifier, specifierLen));
2529 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002530}
2531
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002532void CheckFormatHandler::HandlePosition(const char *startPos,
2533 unsigned posLen) {
2534 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2535 getLocationOfByte(startPos),
2536 /*IsStringLocation*/true,
2537 getSpecifierRange(startPos, posLen));
2538}
2539
Ted Kremenekd1668192010-02-27 01:41:03 +00002540void
Ted Kremenek02087932010-07-16 02:11:22 +00002541CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2542 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002543 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2544 << (unsigned) p,
2545 getLocationOfByte(startPos), /*IsStringLocation*/true,
2546 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002547}
2548
Ted Kremenek02087932010-07-16 02:11:22 +00002549void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002550 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002551 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2552 getLocationOfByte(startPos),
2553 /*IsStringLocation*/true,
2554 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002555}
2556
Ted Kremenek02087932010-07-16 02:11:22 +00002557void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002558 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002559 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002560 EmitFormatDiagnostic(
2561 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2562 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2563 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002564 }
Ted Kremenek02087932010-07-16 02:11:22 +00002565}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002566
Jordan Rose58bbe422012-07-19 18:10:08 +00002567// Note that this may return NULL if there was an error parsing or building
2568// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002569const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002570 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002571}
2572
2573void CheckFormatHandler::DoneProcessing() {
2574 // Does the number of data arguments exceed the number of
2575 // format conversions in the format string?
2576 if (!HasVAListArg) {
2577 // Find any arguments that weren't covered.
2578 CoveredArgs.flip();
2579 signed notCoveredArg = CoveredArgs.find_first();
2580 if (notCoveredArg >= 0) {
2581 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002582 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2583 SourceLocation Loc = E->getLocStart();
2584 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2585 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2586 Loc, /*IsStringLocation*/false,
2587 getFormatStringRange());
2588 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002589 }
Ted Kremenek02087932010-07-16 02:11:22 +00002590 }
2591 }
2592}
2593
Ted Kremenekce815422010-07-19 21:25:57 +00002594bool
2595CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2596 SourceLocation Loc,
2597 const char *startSpec,
2598 unsigned specifierLen,
2599 const char *csStart,
2600 unsigned csLen) {
2601
2602 bool keepGoing = true;
2603 if (argIndex < NumDataArgs) {
2604 // Consider the argument coverered, even though the specifier doesn't
2605 // make sense.
2606 CoveredArgs.set(argIndex);
2607 }
2608 else {
2609 // If argIndex exceeds the number of data arguments we
2610 // don't issue a warning because that is just a cascade of warnings (and
2611 // they may have intended '%%' anyway). We don't want to continue processing
2612 // the format string after this point, however, as we will like just get
2613 // gibberish when trying to match arguments.
2614 keepGoing = false;
2615 }
2616
Richard Trieu03cf7b72011-10-28 00:41:25 +00002617 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2618 << StringRef(csStart, csLen),
2619 Loc, /*IsStringLocation*/true,
2620 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002621
2622 return keepGoing;
2623}
2624
Richard Trieu03cf7b72011-10-28 00:41:25 +00002625void
2626CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2627 const char *startSpec,
2628 unsigned specifierLen) {
2629 EmitFormatDiagnostic(
2630 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2631 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2632}
2633
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002634bool
2635CheckFormatHandler::CheckNumArgs(
2636 const analyze_format_string::FormatSpecifier &FS,
2637 const analyze_format_string::ConversionSpecifier &CS,
2638 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2639
2640 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002641 PartialDiagnostic PDiag = FS.usesPositionalArg()
2642 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2643 << (argIndex+1) << NumDataArgs)
2644 : S.PDiag(diag::warn_printf_insufficient_data_args);
2645 EmitFormatDiagnostic(
2646 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2647 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002648 return false;
2649 }
2650 return true;
2651}
2652
Richard Trieu03cf7b72011-10-28 00:41:25 +00002653template<typename Range>
2654void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2655 SourceLocation Loc,
2656 bool IsStringLocation,
2657 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002658 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002659 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002660 Loc, IsStringLocation, StringRange, FixIt);
2661}
2662
2663/// \brief If the format string is not within the funcion call, emit a note
2664/// so that the function call and string are in diagnostic messages.
2665///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002666/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002667/// call and only one diagnostic message will be produced. Otherwise, an
2668/// extra note will be emitted pointing to location of the format string.
2669///
2670/// \param ArgumentExpr the expression that is passed as the format string
2671/// argument in the function call. Used for getting locations when two
2672/// diagnostics are emitted.
2673///
2674/// \param PDiag the callee should already have provided any strings for the
2675/// diagnostic message. This function only adds locations and fixits
2676/// to diagnostics.
2677///
2678/// \param Loc primary location for diagnostic. If two diagnostics are
2679/// required, one will be at Loc and a new SourceLocation will be created for
2680/// the other one.
2681///
2682/// \param IsStringLocation if true, Loc points to the format string should be
2683/// used for the note. Otherwise, Loc points to the argument list and will
2684/// be used with PDiag.
2685///
2686/// \param StringRange some or all of the string to highlight. This is
2687/// templated so it can accept either a CharSourceRange or a SourceRange.
2688///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002689/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002690template<typename Range>
2691void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2692 const Expr *ArgumentExpr,
2693 PartialDiagnostic PDiag,
2694 SourceLocation Loc,
2695 bool IsStringLocation,
2696 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002697 ArrayRef<FixItHint> FixIt) {
2698 if (InFunctionCall) {
2699 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2700 D << StringRange;
2701 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2702 I != E; ++I) {
2703 D << *I;
2704 }
2705 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002706 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2707 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002708
2709 const Sema::SemaDiagnosticBuilder &Note =
2710 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2711 diag::note_format_string_defined);
2712
2713 Note << StringRange;
2714 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2715 I != E; ++I) {
2716 Note << *I;
2717 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002718 }
2719}
2720
Ted Kremenek02087932010-07-16 02:11:22 +00002721//===--- CHECK: Printf format string checking ------------------------------===//
2722
2723namespace {
2724class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002725 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002726public:
2727 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2728 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002729 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002730 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002731 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002732 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002733 Sema::VariadicCallType CallType,
2734 llvm::SmallBitVector &CheckedVarArgs)
2735 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2736 numDataArgs, beg, hasVAListArg, Args,
2737 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2738 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002739 {}
2740
Craig Toppere14c0f82014-03-12 04:55:44 +00002741
Ted Kremenek02087932010-07-16 02:11:22 +00002742 bool HandleInvalidPrintfConversionSpecifier(
2743 const analyze_printf::PrintfSpecifier &FS,
2744 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002745 unsigned specifierLen) override;
2746
Ted Kremenek02087932010-07-16 02:11:22 +00002747 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2748 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002749 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002750 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2751 const char *StartSpecifier,
2752 unsigned SpecifierLen,
2753 const Expr *E);
2754
Ted Kremenek02087932010-07-16 02:11:22 +00002755 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2756 const char *startSpecifier, unsigned specifierLen);
2757 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2758 const analyze_printf::OptionalAmount &Amt,
2759 unsigned type,
2760 const char *startSpecifier, unsigned specifierLen);
2761 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2762 const analyze_printf::OptionalFlag &flag,
2763 const char *startSpecifier, unsigned specifierLen);
2764 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2765 const analyze_printf::OptionalFlag &ignoredFlag,
2766 const analyze_printf::OptionalFlag &flag,
2767 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002768 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002769 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002770
Ted Kremenek02087932010-07-16 02:11:22 +00002771};
2772}
2773
2774bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2775 const analyze_printf::PrintfSpecifier &FS,
2776 const char *startSpecifier,
2777 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002778 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002779 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002780
Ted Kremenekce815422010-07-19 21:25:57 +00002781 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2782 getLocationOfByte(CS.getStart()),
2783 startSpecifier, specifierLen,
2784 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002785}
2786
Ted Kremenek02087932010-07-16 02:11:22 +00002787bool CheckPrintfHandler::HandleAmount(
2788 const analyze_format_string::OptionalAmount &Amt,
2789 unsigned k, const char *startSpecifier,
2790 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002791
2792 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002793 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002794 unsigned argIndex = Amt.getArgIndex();
2795 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002796 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2797 << k,
2798 getLocationOfByte(Amt.getStart()),
2799 /*IsStringLocation*/true,
2800 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002801 // Don't do any more checking. We will just emit
2802 // spurious errors.
2803 return false;
2804 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002805
Ted Kremenek5739de72010-01-29 01:06:55 +00002806 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002807 // Although not in conformance with C99, we also allow the argument to be
2808 // an 'unsigned int' as that is a reasonably safe case. GCC also
2809 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002810 CoveredArgs.set(argIndex);
2811 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002812 if (!Arg)
2813 return false;
2814
Ted Kremenek5739de72010-01-29 01:06:55 +00002815 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002816
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002817 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2818 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002819
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002820 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002821 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002822 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002823 << T << Arg->getSourceRange(),
2824 getLocationOfByte(Amt.getStart()),
2825 /*IsStringLocation*/true,
2826 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002827 // Don't do any more checking. We will just emit
2828 // spurious errors.
2829 return false;
2830 }
2831 }
2832 }
2833 return true;
2834}
Ted Kremenek5739de72010-01-29 01:06:55 +00002835
Tom Careb49ec692010-06-17 19:00:27 +00002836void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002837 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002838 const analyze_printf::OptionalAmount &Amt,
2839 unsigned type,
2840 const char *startSpecifier,
2841 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002842 const analyze_printf::PrintfConversionSpecifier &CS =
2843 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002844
Richard Trieu03cf7b72011-10-28 00:41:25 +00002845 FixItHint fixit =
2846 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2847 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2848 Amt.getConstantLength()))
2849 : FixItHint();
2850
2851 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2852 << type << CS.toString(),
2853 getLocationOfByte(Amt.getStart()),
2854 /*IsStringLocation*/true,
2855 getSpecifierRange(startSpecifier, specifierLen),
2856 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002857}
2858
Ted Kremenek02087932010-07-16 02:11:22 +00002859void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002860 const analyze_printf::OptionalFlag &flag,
2861 const char *startSpecifier,
2862 unsigned specifierLen) {
2863 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002864 const analyze_printf::PrintfConversionSpecifier &CS =
2865 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002866 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2867 << flag.toString() << CS.toString(),
2868 getLocationOfByte(flag.getPosition()),
2869 /*IsStringLocation*/true,
2870 getSpecifierRange(startSpecifier, specifierLen),
2871 FixItHint::CreateRemoval(
2872 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002873}
2874
2875void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002876 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002877 const analyze_printf::OptionalFlag &ignoredFlag,
2878 const analyze_printf::OptionalFlag &flag,
2879 const char *startSpecifier,
2880 unsigned specifierLen) {
2881 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002882 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2883 << ignoredFlag.toString() << flag.toString(),
2884 getLocationOfByte(ignoredFlag.getPosition()),
2885 /*IsStringLocation*/true,
2886 getSpecifierRange(startSpecifier, specifierLen),
2887 FixItHint::CreateRemoval(
2888 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002889}
2890
Richard Smith55ce3522012-06-25 20:30:08 +00002891// Determines if the specified is a C++ class or struct containing
2892// a member with the specified name and kind (e.g. a CXXMethodDecl named
2893// "c_str()").
2894template<typename MemberKind>
2895static llvm::SmallPtrSet<MemberKind*, 1>
2896CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2897 const RecordType *RT = Ty->getAs<RecordType>();
2898 llvm::SmallPtrSet<MemberKind*, 1> Results;
2899
2900 if (!RT)
2901 return Results;
2902 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002903 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002904 return Results;
2905
Alp Tokerb6cc5922014-05-03 03:45:55 +00002906 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002907 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002908 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002909
2910 // We just need to include all members of the right kind turned up by the
2911 // filter, at this point.
2912 if (S.LookupQualifiedName(R, RT->getDecl()))
2913 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2914 NamedDecl *decl = (*I)->getUnderlyingDecl();
2915 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2916 Results.insert(FK);
2917 }
2918 return Results;
2919}
2920
Richard Smith2868a732014-02-28 01:36:39 +00002921/// Check if we could call '.c_str()' on an object.
2922///
2923/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2924/// allow the call, or if it would be ambiguous).
2925bool Sema::hasCStrMethod(const Expr *E) {
2926 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2927 MethodSet Results =
2928 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2929 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2930 MI != ME; ++MI)
2931 if ((*MI)->getMinRequiredArguments() == 0)
2932 return true;
2933 return false;
2934}
2935
Richard Smith55ce3522012-06-25 20:30:08 +00002936// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002937// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002938// Returns true when a c_str() conversion method is found.
2939bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002940 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002941 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2942
2943 MethodSet Results =
2944 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2945
2946 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2947 MI != ME; ++MI) {
2948 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002949 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002950 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002951 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002952 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002953 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2954 << "c_str()"
2955 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2956 return true;
2957 }
2958 }
2959
2960 return false;
2961}
2962
Ted Kremenekab278de2010-01-28 23:39:18 +00002963bool
Ted Kremenek02087932010-07-16 02:11:22 +00002964CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002965 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002966 const char *startSpecifier,
2967 unsigned specifierLen) {
2968
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002969 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002970 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002971 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002972
Ted Kremenek6cd69422010-07-19 22:01:06 +00002973 if (FS.consumesDataArgument()) {
2974 if (atFirstArg) {
2975 atFirstArg = false;
2976 usesPositionalArgs = FS.usesPositionalArg();
2977 }
2978 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002979 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2980 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002981 return false;
2982 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002983 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002984
Ted Kremenekd1668192010-02-27 01:41:03 +00002985 // First check if the field width, precision, and conversion specifier
2986 // have matching data arguments.
2987 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2988 startSpecifier, specifierLen)) {
2989 return false;
2990 }
2991
2992 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2993 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002994 return false;
2995 }
2996
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002997 if (!CS.consumesDataArgument()) {
2998 // FIXME: Technically specifying a precision or field width here
2999 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003000 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003001 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003002
Ted Kremenek4a49d982010-02-26 19:18:41 +00003003 // Consume the argument.
3004 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003005 if (argIndex < NumDataArgs) {
3006 // The check to see if the argIndex is valid will come later.
3007 // We set the bit here because we may exit early from this
3008 // function if we encounter some other error.
3009 CoveredArgs.set(argIndex);
3010 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003011
3012 // Check for using an Objective-C specific conversion specifier
3013 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003014 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003015 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3016 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003017 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003018
Tom Careb49ec692010-06-17 19:00:27 +00003019 // Check for invalid use of field width
3020 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003021 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003022 startSpecifier, specifierLen);
3023 }
3024
3025 // Check for invalid use of precision
3026 if (!FS.hasValidPrecision()) {
3027 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3028 startSpecifier, specifierLen);
3029 }
3030
3031 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003032 if (!FS.hasValidThousandsGroupingPrefix())
3033 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003034 if (!FS.hasValidLeadingZeros())
3035 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3036 if (!FS.hasValidPlusPrefix())
3037 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003038 if (!FS.hasValidSpacePrefix())
3039 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003040 if (!FS.hasValidAlternativeForm())
3041 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3042 if (!FS.hasValidLeftJustified())
3043 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3044
3045 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003046 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3047 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3048 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003049 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3050 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3051 startSpecifier, specifierLen);
3052
3053 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003054 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003055 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3056 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003057 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003058 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003059 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003060 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3061 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003062
Jordan Rose92303592012-09-08 04:00:03 +00003063 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3064 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3065
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003066 // The remaining checks depend on the data arguments.
3067 if (HasVAListArg)
3068 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003069
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003070 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003071 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003072
Jordan Rose58bbe422012-07-19 18:10:08 +00003073 const Expr *Arg = getDataArg(argIndex);
3074 if (!Arg)
3075 return true;
3076
3077 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003078}
3079
Jordan Roseaee34382012-09-05 22:56:26 +00003080static bool requiresParensToAddCast(const Expr *E) {
3081 // FIXME: We should have a general way to reason about operator
3082 // precedence and whether parens are actually needed here.
3083 // Take care of a few common cases where they aren't.
3084 const Expr *Inside = E->IgnoreImpCasts();
3085 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3086 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3087
3088 switch (Inside->getStmtClass()) {
3089 case Stmt::ArraySubscriptExprClass:
3090 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003091 case Stmt::CharacterLiteralClass:
3092 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003093 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003094 case Stmt::FloatingLiteralClass:
3095 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003096 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003097 case Stmt::ObjCArrayLiteralClass:
3098 case Stmt::ObjCBoolLiteralExprClass:
3099 case Stmt::ObjCBoxedExprClass:
3100 case Stmt::ObjCDictionaryLiteralClass:
3101 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003102 case Stmt::ObjCIvarRefExprClass:
3103 case Stmt::ObjCMessageExprClass:
3104 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003105 case Stmt::ObjCStringLiteralClass:
3106 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003107 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003108 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003109 case Stmt::UnaryOperatorClass:
3110 return false;
3111 default:
3112 return true;
3113 }
3114}
3115
Richard Smith55ce3522012-06-25 20:30:08 +00003116bool
3117CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3118 const char *StartSpecifier,
3119 unsigned SpecifierLen,
3120 const Expr *E) {
3121 using namespace analyze_format_string;
3122 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003123 // Now type check the data expression that matches the
3124 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003125 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3126 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003127 if (!AT.isValid())
3128 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003129
Jordan Rose598ec092012-12-05 18:44:40 +00003130 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003131 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3132 ExprTy = TET->getUnderlyingExpr()->getType();
3133 }
3134
Jordan Rose598ec092012-12-05 18:44:40 +00003135 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003136 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003137
Jordan Rose22b74712012-09-05 22:56:19 +00003138 // Look through argument promotions for our error message's reported type.
3139 // This includes the integral and floating promotions, but excludes array
3140 // and function pointer decay; seeing that an argument intended to be a
3141 // string has type 'char [6]' is probably more confusing than 'char *'.
3142 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3143 if (ICE->getCastKind() == CK_IntegralCast ||
3144 ICE->getCastKind() == CK_FloatingCast) {
3145 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003146 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003147
3148 // Check if we didn't match because of an implicit cast from a 'char'
3149 // or 'short' to an 'int'. This is done because printf is a varargs
3150 // function.
3151 if (ICE->getType() == S.Context.IntTy ||
3152 ICE->getType() == S.Context.UnsignedIntTy) {
3153 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003154 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003155 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003156 }
Jordan Rose98709982012-06-04 22:48:57 +00003157 }
Jordan Rose598ec092012-12-05 18:44:40 +00003158 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3159 // Special case for 'a', which has type 'int' in C.
3160 // Note, however, that we do /not/ want to treat multibyte constants like
3161 // 'MooV' as characters! This form is deprecated but still exists.
3162 if (ExprTy == S.Context.IntTy)
3163 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3164 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003165 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003166
Jordan Rosebc53ed12014-05-31 04:12:14 +00003167 // Look through enums to their underlying type.
3168 bool IsEnum = false;
3169 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3170 ExprTy = EnumTy->getDecl()->getIntegerType();
3171 IsEnum = true;
3172 }
3173
Jordan Rose0e5badd2012-12-05 18:44:49 +00003174 // %C in an Objective-C context prints a unichar, not a wchar_t.
3175 // If the argument is an integer of some kind, believe the %C and suggest
3176 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003177 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003178 if (ObjCContext &&
3179 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3180 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3181 !ExprTy->isCharType()) {
3182 // 'unichar' is defined as a typedef of unsigned short, but we should
3183 // prefer using the typedef if it is visible.
3184 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003185
3186 // While we are here, check if the value is an IntegerLiteral that happens
3187 // to be within the valid range.
3188 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3189 const llvm::APInt &V = IL->getValue();
3190 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3191 return true;
3192 }
3193
Jordan Rose0e5badd2012-12-05 18:44:49 +00003194 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3195 Sema::LookupOrdinaryName);
3196 if (S.LookupName(Result, S.getCurScope())) {
3197 NamedDecl *ND = Result.getFoundDecl();
3198 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3199 if (TD->getUnderlyingType() == IntendedTy)
3200 IntendedTy = S.Context.getTypedefType(TD);
3201 }
3202 }
3203 }
3204
3205 // Special-case some of Darwin's platform-independence types by suggesting
3206 // casts to primitive types that are known to be large enough.
3207 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003208 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003209 // Use a 'while' to peel off layers of typedefs.
3210 QualType TyTy = IntendedTy;
3211 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003212 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003213 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003214 .Case("NSInteger", S.Context.LongTy)
3215 .Case("NSUInteger", S.Context.UnsignedLongTy)
3216 .Case("SInt32", S.Context.IntTy)
3217 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003218 .Default(QualType());
3219
3220 if (!CastTy.isNull()) {
3221 ShouldNotPrintDirectly = true;
3222 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003223 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003224 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003225 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003226 }
3227 }
3228
Jordan Rose22b74712012-09-05 22:56:19 +00003229 // We may be able to offer a FixItHint if it is a supported type.
3230 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003231 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003232 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003233
Jordan Rose22b74712012-09-05 22:56:19 +00003234 if (success) {
3235 // Get the fix string from the fixed format specifier
3236 SmallString<16> buf;
3237 llvm::raw_svector_ostream os(buf);
3238 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003239
Jordan Roseaee34382012-09-05 22:56:26 +00003240 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3241
Jordan Rose0e5badd2012-12-05 18:44:49 +00003242 if (IntendedTy == ExprTy) {
3243 // In this case, the specifier is wrong and should be changed to match
3244 // the argument.
3245 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003246 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3247 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003248 << E->getSourceRange(),
3249 E->getLocStart(),
3250 /*IsStringLocation*/false,
3251 SpecRange,
3252 FixItHint::CreateReplacement(SpecRange, os.str()));
3253
3254 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003255 // The canonical type for formatting this value is different from the
3256 // actual type of the expression. (This occurs, for example, with Darwin's
3257 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3258 // should be printed as 'long' for 64-bit compatibility.)
3259 // Rather than emitting a normal format/argument mismatch, we want to
3260 // add a cast to the recommended type (and correct the format string
3261 // if necessary).
3262 SmallString<16> CastBuf;
3263 llvm::raw_svector_ostream CastFix(CastBuf);
3264 CastFix << "(";
3265 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3266 CastFix << ")";
3267
3268 SmallVector<FixItHint,4> Hints;
3269 if (!AT.matchesType(S.Context, IntendedTy))
3270 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3271
3272 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3273 // If there's already a cast present, just replace it.
3274 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3275 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3276
3277 } else if (!requiresParensToAddCast(E)) {
3278 // If the expression has high enough precedence,
3279 // just write the C-style cast.
3280 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3281 CastFix.str()));
3282 } else {
3283 // Otherwise, add parens around the expression as well as the cast.
3284 CastFix << "(";
3285 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3286 CastFix.str()));
3287
Alp Tokerb6cc5922014-05-03 03:45:55 +00003288 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003289 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3290 }
3291
Jordan Rose0e5badd2012-12-05 18:44:49 +00003292 if (ShouldNotPrintDirectly) {
3293 // The expression has a type that should not be printed directly.
3294 // We extract the name from the typedef because we don't want to show
3295 // the underlying type in the diagnostic.
3296 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003297
Jordan Rose0e5badd2012-12-05 18:44:49 +00003298 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003299 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation=*/false,
3302 SpecRange, Hints);
3303 } else {
3304 // In this case, the expression could be printed using a different
3305 // specifier, but we've decided that the specifier is probably correct
3306 // and we should cast instead. Just use the normal warning message.
3307 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003308 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3309 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003310 << E->getSourceRange(),
3311 E->getLocStart(), /*IsStringLocation*/false,
3312 SpecRange, Hints);
3313 }
Jordan Roseaee34382012-09-05 22:56:26 +00003314 }
Jordan Rose22b74712012-09-05 22:56:19 +00003315 } else {
3316 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3317 SpecifierLen);
3318 // Since the warning for passing non-POD types to variadic functions
3319 // was deferred until now, we emit a warning for non-POD
3320 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003321 switch (S.isValidVarArgType(ExprTy)) {
3322 case Sema::VAK_Valid:
3323 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003324 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003325 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3326 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003327 << CSR
3328 << E->getSourceRange(),
3329 E->getLocStart(), /*IsStringLocation*/false, CSR);
3330 break;
3331
3332 case Sema::VAK_Undefined:
3333 EmitFormatDiagnostic(
3334 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003335 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003336 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003337 << CallType
3338 << AT.getRepresentativeTypeName(S.Context)
3339 << CSR
3340 << E->getSourceRange(),
3341 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003342 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003343 break;
3344
3345 case Sema::VAK_Invalid:
3346 if (ExprTy->isObjCObjectType())
3347 EmitFormatDiagnostic(
3348 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3349 << S.getLangOpts().CPlusPlus11
3350 << ExprTy
3351 << CallType
3352 << AT.getRepresentativeTypeName(S.Context)
3353 << CSR
3354 << E->getSourceRange(),
3355 E->getLocStart(), /*IsStringLocation*/false, CSR);
3356 else
3357 // FIXME: If this is an initializer list, suggest removing the braces
3358 // or inserting a cast to the target type.
3359 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3360 << isa<InitListExpr>(E) << ExprTy << CallType
3361 << AT.getRepresentativeTypeName(S.Context)
3362 << E->getSourceRange();
3363 break;
3364 }
3365
3366 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3367 "format string specifier index out of range");
3368 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003369 }
3370
Ted Kremenekab278de2010-01-28 23:39:18 +00003371 return true;
3372}
3373
Ted Kremenek02087932010-07-16 02:11:22 +00003374//===--- CHECK: Scanf format string checking ------------------------------===//
3375
3376namespace {
3377class CheckScanfHandler : public CheckFormatHandler {
3378public:
3379 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3380 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003381 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003382 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003383 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003384 Sema::VariadicCallType CallType,
3385 llvm::SmallBitVector &CheckedVarArgs)
3386 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3387 numDataArgs, beg, hasVAListArg,
3388 Args, formatIdx, inFunctionCall, CallType,
3389 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003390 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003391
3392 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3393 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003394 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003395
3396 bool HandleInvalidScanfConversionSpecifier(
3397 const analyze_scanf::ScanfSpecifier &FS,
3398 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003399 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003400
Craig Toppere14c0f82014-03-12 04:55:44 +00003401 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003402};
Ted Kremenek019d2242010-01-29 01:50:07 +00003403}
Ted Kremenekab278de2010-01-28 23:39:18 +00003404
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003405void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3406 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003407 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3408 getLocationOfByte(end), /*IsStringLocation*/true,
3409 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003410}
3411
Ted Kremenekce815422010-07-19 21:25:57 +00003412bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3413 const analyze_scanf::ScanfSpecifier &FS,
3414 const char *startSpecifier,
3415 unsigned specifierLen) {
3416
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003417 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003418 FS.getConversionSpecifier();
3419
3420 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3421 getLocationOfByte(CS.getStart()),
3422 startSpecifier, specifierLen,
3423 CS.getStart(), CS.getLength());
3424}
3425
Ted Kremenek02087932010-07-16 02:11:22 +00003426bool CheckScanfHandler::HandleScanfSpecifier(
3427 const analyze_scanf::ScanfSpecifier &FS,
3428 const char *startSpecifier,
3429 unsigned specifierLen) {
3430
3431 using namespace analyze_scanf;
3432 using namespace analyze_format_string;
3433
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003434 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003435
Ted Kremenek6cd69422010-07-19 22:01:06 +00003436 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3437 // be used to decide if we are using positional arguments consistently.
3438 if (FS.consumesDataArgument()) {
3439 if (atFirstArg) {
3440 atFirstArg = false;
3441 usesPositionalArgs = FS.usesPositionalArg();
3442 }
3443 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003444 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3445 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003446 return false;
3447 }
Ted Kremenek02087932010-07-16 02:11:22 +00003448 }
3449
3450 // Check if the field with is non-zero.
3451 const OptionalAmount &Amt = FS.getFieldWidth();
3452 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3453 if (Amt.getConstantAmount() == 0) {
3454 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3455 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003456 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3457 getLocationOfByte(Amt.getStart()),
3458 /*IsStringLocation*/true, R,
3459 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003460 }
3461 }
3462
3463 if (!FS.consumesDataArgument()) {
3464 // FIXME: Technically specifying a precision or field width here
3465 // makes no sense. Worth issuing a warning at some point.
3466 return true;
3467 }
3468
3469 // Consume the argument.
3470 unsigned argIndex = FS.getArgIndex();
3471 if (argIndex < NumDataArgs) {
3472 // The check to see if the argIndex is valid will come later.
3473 // We set the bit here because we may exit early from this
3474 // function if we encounter some other error.
3475 CoveredArgs.set(argIndex);
3476 }
3477
Ted Kremenek4407ea42010-07-20 20:04:47 +00003478 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003479 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003480 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3481 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003482 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003483 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003484 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003485 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3486 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003487
Jordan Rose92303592012-09-08 04:00:03 +00003488 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3489 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3490
Ted Kremenek02087932010-07-16 02:11:22 +00003491 // The remaining checks depend on the data arguments.
3492 if (HasVAListArg)
3493 return true;
3494
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003495 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003496 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003497
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003498 // Check that the argument type matches the format specifier.
3499 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003500 if (!Ex)
3501 return true;
3502
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003503 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3504 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003505 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003506 bool success = fixedFS.fixType(Ex->getType(),
3507 Ex->IgnoreImpCasts()->getType(),
3508 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003509
3510 if (success) {
3511 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003512 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003513 llvm::raw_svector_ostream os(buf);
3514 fixedFS.toString(os);
3515
3516 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003517 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3518 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003519 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003520 Ex->getLocStart(),
3521 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003522 getSpecifierRange(startSpecifier, specifierLen),
3523 FixItHint::CreateReplacement(
3524 getSpecifierRange(startSpecifier, specifierLen),
3525 os.str()));
3526 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003527 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003528 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3529 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003530 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003531 Ex->getLocStart(),
3532 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003533 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003534 }
3535 }
3536
Ted Kremenek02087932010-07-16 02:11:22 +00003537 return true;
3538}
3539
3540void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003541 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003542 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003543 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003544 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003545 bool inFunctionCall, VariadicCallType CallType,
3546 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003547
Ted Kremenekab278de2010-01-28 23:39:18 +00003548 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003549 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003550 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003551 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003552 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3553 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003554 return;
3555 }
Ted Kremenek02087932010-07-16 02:11:22 +00003556
Ted Kremenekab278de2010-01-28 23:39:18 +00003557 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003558 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003559 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003560 // Account for cases where the string literal is truncated in a declaration.
3561 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3562 assert(T && "String literal not of constant array type!");
3563 size_t TypeSize = T->getSize().getZExtValue();
3564 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003565 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003566
3567 // Emit a warning if the string literal is truncated and does not contain an
3568 // embedded null character.
3569 if (TypeSize <= StrRef.size() &&
3570 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3571 CheckFormatHandler::EmitFormatDiagnostic(
3572 *this, inFunctionCall, Args[format_idx],
3573 PDiag(diag::warn_printf_format_string_not_null_terminated),
3574 FExpr->getLocStart(),
3575 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3576 return;
3577 }
3578
Ted Kremenekab278de2010-01-28 23:39:18 +00003579 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003580 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003581 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003582 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003583 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3584 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003585 return;
3586 }
Ted Kremenek02087932010-07-16 02:11:22 +00003587
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003588 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003589 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003590 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003591 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003592 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003593
Hans Wennborg23926bd2011-12-15 10:25:47 +00003594 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003595 getLangOpts(),
3596 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003597 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003598 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003599 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003600 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003601 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003602
Hans Wennborg23926bd2011-12-15 10:25:47 +00003603 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003604 getLangOpts(),
3605 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003606 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003607 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003608}
3609
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003610//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3611
3612// Returns the related absolute value function that is larger, of 0 if one
3613// does not exist.
3614static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3615 switch (AbsFunction) {
3616 default:
3617 return 0;
3618
3619 case Builtin::BI__builtin_abs:
3620 return Builtin::BI__builtin_labs;
3621 case Builtin::BI__builtin_labs:
3622 return Builtin::BI__builtin_llabs;
3623 case Builtin::BI__builtin_llabs:
3624 return 0;
3625
3626 case Builtin::BI__builtin_fabsf:
3627 return Builtin::BI__builtin_fabs;
3628 case Builtin::BI__builtin_fabs:
3629 return Builtin::BI__builtin_fabsl;
3630 case Builtin::BI__builtin_fabsl:
3631 return 0;
3632
3633 case Builtin::BI__builtin_cabsf:
3634 return Builtin::BI__builtin_cabs;
3635 case Builtin::BI__builtin_cabs:
3636 return Builtin::BI__builtin_cabsl;
3637 case Builtin::BI__builtin_cabsl:
3638 return 0;
3639
3640 case Builtin::BIabs:
3641 return Builtin::BIlabs;
3642 case Builtin::BIlabs:
3643 return Builtin::BIllabs;
3644 case Builtin::BIllabs:
3645 return 0;
3646
3647 case Builtin::BIfabsf:
3648 return Builtin::BIfabs;
3649 case Builtin::BIfabs:
3650 return Builtin::BIfabsl;
3651 case Builtin::BIfabsl:
3652 return 0;
3653
3654 case Builtin::BIcabsf:
3655 return Builtin::BIcabs;
3656 case Builtin::BIcabs:
3657 return Builtin::BIcabsl;
3658 case Builtin::BIcabsl:
3659 return 0;
3660 }
3661}
3662
3663// Returns the argument type of the absolute value function.
3664static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3665 unsigned AbsType) {
3666 if (AbsType == 0)
3667 return QualType();
3668
3669 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3670 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3671 if (Error != ASTContext::GE_None)
3672 return QualType();
3673
3674 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3675 if (!FT)
3676 return QualType();
3677
3678 if (FT->getNumParams() != 1)
3679 return QualType();
3680
3681 return FT->getParamType(0);
3682}
3683
3684// Returns the best absolute value function, or zero, based on type and
3685// current absolute value function.
3686static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3687 unsigned AbsFunctionKind) {
3688 unsigned BestKind = 0;
3689 uint64_t ArgSize = Context.getTypeSize(ArgType);
3690 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3691 Kind = getLargerAbsoluteValueFunction(Kind)) {
3692 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3693 if (Context.getTypeSize(ParamType) >= ArgSize) {
3694 if (BestKind == 0)
3695 BestKind = Kind;
3696 else if (Context.hasSameType(ParamType, ArgType)) {
3697 BestKind = Kind;
3698 break;
3699 }
3700 }
3701 }
3702 return BestKind;
3703}
3704
3705enum AbsoluteValueKind {
3706 AVK_Integer,
3707 AVK_Floating,
3708 AVK_Complex
3709};
3710
3711static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3712 if (T->isIntegralOrEnumerationType())
3713 return AVK_Integer;
3714 if (T->isRealFloatingType())
3715 return AVK_Floating;
3716 if (T->isAnyComplexType())
3717 return AVK_Complex;
3718
3719 llvm_unreachable("Type not integer, floating, or complex");
3720}
3721
3722// Changes the absolute value function to a different type. Preserves whether
3723// the function is a builtin.
3724static unsigned changeAbsFunction(unsigned AbsKind,
3725 AbsoluteValueKind ValueKind) {
3726 switch (ValueKind) {
3727 case AVK_Integer:
3728 switch (AbsKind) {
3729 default:
3730 return 0;
3731 case Builtin::BI__builtin_fabsf:
3732 case Builtin::BI__builtin_fabs:
3733 case Builtin::BI__builtin_fabsl:
3734 case Builtin::BI__builtin_cabsf:
3735 case Builtin::BI__builtin_cabs:
3736 case Builtin::BI__builtin_cabsl:
3737 return Builtin::BI__builtin_abs;
3738 case Builtin::BIfabsf:
3739 case Builtin::BIfabs:
3740 case Builtin::BIfabsl:
3741 case Builtin::BIcabsf:
3742 case Builtin::BIcabs:
3743 case Builtin::BIcabsl:
3744 return Builtin::BIabs;
3745 }
3746 case AVK_Floating:
3747 switch (AbsKind) {
3748 default:
3749 return 0;
3750 case Builtin::BI__builtin_abs:
3751 case Builtin::BI__builtin_labs:
3752 case Builtin::BI__builtin_llabs:
3753 case Builtin::BI__builtin_cabsf:
3754 case Builtin::BI__builtin_cabs:
3755 case Builtin::BI__builtin_cabsl:
3756 return Builtin::BI__builtin_fabsf;
3757 case Builtin::BIabs:
3758 case Builtin::BIlabs:
3759 case Builtin::BIllabs:
3760 case Builtin::BIcabsf:
3761 case Builtin::BIcabs:
3762 case Builtin::BIcabsl:
3763 return Builtin::BIfabsf;
3764 }
3765 case AVK_Complex:
3766 switch (AbsKind) {
3767 default:
3768 return 0;
3769 case Builtin::BI__builtin_abs:
3770 case Builtin::BI__builtin_labs:
3771 case Builtin::BI__builtin_llabs:
3772 case Builtin::BI__builtin_fabsf:
3773 case Builtin::BI__builtin_fabs:
3774 case Builtin::BI__builtin_fabsl:
3775 return Builtin::BI__builtin_cabsf;
3776 case Builtin::BIabs:
3777 case Builtin::BIlabs:
3778 case Builtin::BIllabs:
3779 case Builtin::BIfabsf:
3780 case Builtin::BIfabs:
3781 case Builtin::BIfabsl:
3782 return Builtin::BIcabsf;
3783 }
3784 }
3785 llvm_unreachable("Unable to convert function");
3786}
3787
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003788static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003789 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3790 if (!FnInfo)
3791 return 0;
3792
3793 switch (FDecl->getBuiltinID()) {
3794 default:
3795 return 0;
3796 case Builtin::BI__builtin_abs:
3797 case Builtin::BI__builtin_fabs:
3798 case Builtin::BI__builtin_fabsf:
3799 case Builtin::BI__builtin_fabsl:
3800 case Builtin::BI__builtin_labs:
3801 case Builtin::BI__builtin_llabs:
3802 case Builtin::BI__builtin_cabs:
3803 case Builtin::BI__builtin_cabsf:
3804 case Builtin::BI__builtin_cabsl:
3805 case Builtin::BIabs:
3806 case Builtin::BIlabs:
3807 case Builtin::BIllabs:
3808 case Builtin::BIfabs:
3809 case Builtin::BIfabsf:
3810 case Builtin::BIfabsl:
3811 case Builtin::BIcabs:
3812 case Builtin::BIcabsf:
3813 case Builtin::BIcabsl:
3814 return FDecl->getBuiltinID();
3815 }
3816 llvm_unreachable("Unknown Builtin type");
3817}
3818
3819// If the replacement is valid, emit a note with replacement function.
3820// Additionally, suggest including the proper header if not already included.
3821static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003822 unsigned AbsKind, QualType ArgType) {
3823 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003824 const char *HeaderName = nullptr;
3825 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003826 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3827 FunctionName = "std::abs";
3828 if (ArgType->isIntegralOrEnumerationType()) {
3829 HeaderName = "cstdlib";
3830 } else if (ArgType->isRealFloatingType()) {
3831 HeaderName = "cmath";
3832 } else {
3833 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003834 }
Richard Trieubeffb832014-04-15 23:47:53 +00003835
3836 // Lookup all std::abs
3837 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003838 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003839 R.suppressDiagnostics();
3840 S.LookupQualifiedName(R, Std);
3841
3842 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003843 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003844 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3845 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3846 } else {
3847 FDecl = dyn_cast<FunctionDecl>(I);
3848 }
3849 if (!FDecl)
3850 continue;
3851
3852 // Found std::abs(), check that they are the right ones.
3853 if (FDecl->getNumParams() != 1)
3854 continue;
3855
3856 // Check that the parameter type can handle the argument.
3857 QualType ParamType = FDecl->getParamDecl(0)->getType();
3858 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3859 S.Context.getTypeSize(ArgType) <=
3860 S.Context.getTypeSize(ParamType)) {
3861 // Found a function, don't need the header hint.
3862 EmitHeaderHint = false;
3863 break;
3864 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003865 }
Richard Trieubeffb832014-04-15 23:47:53 +00003866 }
3867 } else {
3868 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3869 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3870
3871 if (HeaderName) {
3872 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3873 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3874 R.suppressDiagnostics();
3875 S.LookupName(R, S.getCurScope());
3876
3877 if (R.isSingleResult()) {
3878 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3879 if (FD && FD->getBuiltinID() == AbsKind) {
3880 EmitHeaderHint = false;
3881 } else {
3882 return;
3883 }
3884 } else if (!R.empty()) {
3885 return;
3886 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003887 }
3888 }
3889
3890 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003891 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003892
Richard Trieubeffb832014-04-15 23:47:53 +00003893 if (!HeaderName)
3894 return;
3895
3896 if (!EmitHeaderHint)
3897 return;
3898
Alp Toker5d96e0a2014-07-11 20:53:51 +00003899 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
3900 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00003901}
3902
3903static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3904 if (!FDecl)
3905 return false;
3906
3907 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3908 return false;
3909
3910 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3911
3912 while (ND && ND->isInlineNamespace()) {
3913 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003914 }
Richard Trieubeffb832014-04-15 23:47:53 +00003915
3916 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3917 return false;
3918
3919 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3920 return false;
3921
3922 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003923}
3924
3925// Warn when using the wrong abs() function.
3926void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3927 const FunctionDecl *FDecl,
3928 IdentifierInfo *FnInfo) {
3929 if (Call->getNumArgs() != 1)
3930 return;
3931
3932 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003933 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3934 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003935 return;
3936
3937 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3938 QualType ParamType = Call->getArg(0)->getType();
3939
Alp Toker5d96e0a2014-07-11 20:53:51 +00003940 // Unsigned types cannot be negative. Suggest removing the absolute value
3941 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003942 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003943 const char *FunctionName =
3944 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003945 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3946 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003947 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003948 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3949 return;
3950 }
3951
Richard Trieubeffb832014-04-15 23:47:53 +00003952 // std::abs has overloads which prevent most of the absolute value problems
3953 // from occurring.
3954 if (IsStdAbs)
3955 return;
3956
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003957 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3958 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3959
3960 // The argument and parameter are the same kind. Check if they are the right
3961 // size.
3962 if (ArgValueKind == ParamValueKind) {
3963 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3964 return;
3965
3966 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3967 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3968 << FDecl << ArgType << ParamType;
3969
3970 if (NewAbsKind == 0)
3971 return;
3972
3973 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003974 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003975 return;
3976 }
3977
3978 // ArgValueKind != ParamValueKind
3979 // The wrong type of absolute value function was used. Attempt to find the
3980 // proper one.
3981 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3982 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3983 if (NewAbsKind == 0)
3984 return;
3985
3986 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3987 << FDecl << ParamValueKind << ArgValueKind;
3988
3989 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003990 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003991 return;
3992}
3993
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003994//===--- CHECK: Standard memory functions ---------------------------------===//
3995
Nico Weber0e6daef2013-12-26 23:38:39 +00003996/// \brief Takes the expression passed to the size_t parameter of functions
3997/// such as memcmp, strncat, etc and warns if it's a comparison.
3998///
3999/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4000static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4001 IdentifierInfo *FnName,
4002 SourceLocation FnLoc,
4003 SourceLocation RParenLoc) {
4004 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4005 if (!Size)
4006 return false;
4007
4008 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4009 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4010 return false;
4011
Nico Weber0e6daef2013-12-26 23:38:39 +00004012 SourceRange SizeRange = Size->getSourceRange();
4013 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4014 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004015 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004016 << FnName << FixItHint::CreateInsertion(
4017 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004018 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004019 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004020 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004021 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4022 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004023
4024 return true;
4025}
4026
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004027/// \brief Determine whether the given type is or contains a dynamic class type
4028/// (e.g., whether it has a vtable).
4029static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4030 bool &IsContained) {
4031 // Look through array types while ignoring qualifiers.
4032 const Type *Ty = T->getBaseElementTypeUnsafe();
4033 IsContained = false;
4034
4035 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4036 RD = RD ? RD->getDefinition() : nullptr;
4037 if (!RD)
4038 return nullptr;
4039
4040 if (RD->isDynamicClass())
4041 return RD;
4042
4043 // Check all the fields. If any bases were dynamic, the class is dynamic.
4044 // It's impossible for a class to transitively contain itself by value, so
4045 // infinite recursion is impossible.
4046 for (auto *FD : RD->fields()) {
4047 bool SubContained;
4048 if (const CXXRecordDecl *ContainedRD =
4049 getContainedDynamicClass(FD->getType(), SubContained)) {
4050 IsContained = true;
4051 return ContainedRD;
4052 }
4053 }
4054
4055 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004056}
4057
Chandler Carruth889ed862011-06-21 23:04:20 +00004058/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004059/// otherwise returns NULL.
4060static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004061 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004062 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4063 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4064 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004065
Craig Topperc3ec1492014-05-26 06:22:03 +00004066 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004067}
4068
Chandler Carruth889ed862011-06-21 23:04:20 +00004069/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004070static QualType getSizeOfArgType(const Expr* E) {
4071 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4072 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4073 if (SizeOf->getKind() == clang::UETT_SizeOf)
4074 return SizeOf->getTypeOfArgument();
4075
4076 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004077}
4078
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004079/// \brief Check for dangerous or invalid arguments to memset().
4080///
Chandler Carruthac687262011-06-03 06:23:57 +00004081/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004082/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4083/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004084///
4085/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004086void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004087 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004088 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004089 assert(BId != 0);
4090
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004091 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004092 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004093 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004094 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004095 return;
4096
Anna Zaks22122702012-01-17 00:37:07 +00004097 unsigned LastArg = (BId == Builtin::BImemset ||
4098 BId == Builtin::BIstrndup ? 1 : 2);
4099 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004100 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004101
Nico Weber0e6daef2013-12-26 23:38:39 +00004102 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4103 Call->getLocStart(), Call->getRParenLoc()))
4104 return;
4105
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004106 // We have special checking when the length is a sizeof expression.
4107 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4108 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4109 llvm::FoldingSetNodeID SizeOfArgID;
4110
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004111 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4112 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004113 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004114
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004115 QualType DestTy = Dest->getType();
4116 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4117 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004118
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004119 // Never warn about void type pointers. This can be used to suppress
4120 // false positives.
4121 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004122 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004123
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004124 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4125 // actually comparing the expressions for equality. Because computing the
4126 // expression IDs can be expensive, we only do this if the diagnostic is
4127 // enabled.
4128 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004129 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4130 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004131 // We only compute IDs for expressions if the warning is enabled, and
4132 // cache the sizeof arg's ID.
4133 if (SizeOfArgID == llvm::FoldingSetNodeID())
4134 SizeOfArg->Profile(SizeOfArgID, Context, true);
4135 llvm::FoldingSetNodeID DestID;
4136 Dest->Profile(DestID, Context, true);
4137 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004138 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4139 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004140 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004141 StringRef ReadableName = FnName->getName();
4142
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004143 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004144 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004145 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004146 if (!PointeeTy->isIncompleteType() &&
4147 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004148 ActionIdx = 2; // If the pointee's size is sizeof(char),
4149 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004150
4151 // If the function is defined as a builtin macro, do not show macro
4152 // expansion.
4153 SourceLocation SL = SizeOfArg->getExprLoc();
4154 SourceRange DSR = Dest->getSourceRange();
4155 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004156 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004157
4158 if (SM.isMacroArgExpansion(SL)) {
4159 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4160 SL = SM.getSpellingLoc(SL);
4161 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4162 SM.getSpellingLoc(DSR.getEnd()));
4163 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4164 SM.getSpellingLoc(SSR.getEnd()));
4165 }
4166
Anna Zaksd08d9152012-05-30 23:14:52 +00004167 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004168 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004169 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004170 << PointeeTy
4171 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004172 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004173 << SSR);
4174 DiagRuntimeBehavior(SL, SizeOfArg,
4175 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4176 << ActionIdx
4177 << SSR);
4178
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004179 break;
4180 }
4181 }
4182
4183 // Also check for cases where the sizeof argument is the exact same
4184 // type as the memory argument, and where it points to a user-defined
4185 // record type.
4186 if (SizeOfArgTy != QualType()) {
4187 if (PointeeTy->isRecordType() &&
4188 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4189 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4190 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4191 << FnName << SizeOfArgTy << ArgIdx
4192 << PointeeTy << Dest->getSourceRange()
4193 << LenExpr->getSourceRange());
4194 break;
4195 }
Nico Weberc5e73862011-06-14 16:14:58 +00004196 }
4197
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004198 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004199 bool IsContained;
4200 if (const CXXRecordDecl *ContainedRD =
4201 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004202
4203 unsigned OperationType = 0;
4204 // "overwritten" if we're warning about the destination for any call
4205 // but memcmp; otherwise a verb appropriate to the call.
4206 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4207 if (BId == Builtin::BImemcpy)
4208 OperationType = 1;
4209 else if(BId == Builtin::BImemmove)
4210 OperationType = 2;
4211 else if (BId == Builtin::BImemcmp)
4212 OperationType = 3;
4213 }
4214
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004215 DiagRuntimeBehavior(
4216 Dest->getExprLoc(), Dest,
4217 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004218 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004219 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004220 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004221 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4222 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004223 DiagRuntimeBehavior(
4224 Dest->getExprLoc(), Dest,
4225 PDiag(diag::warn_arc_object_memaccess)
4226 << ArgIdx << FnName << PointeeTy
4227 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004228 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004229 continue;
John McCall31168b02011-06-15 23:02:42 +00004230
4231 DiagRuntimeBehavior(
4232 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004233 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004234 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4235 break;
4236 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004237 }
4238}
4239
Ted Kremenek6865f772011-08-18 20:55:45 +00004240// A little helper routine: ignore addition and subtraction of integer literals.
4241// This intentionally does not ignore all integer constant expressions because
4242// we don't want to remove sizeof().
4243static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4244 Ex = Ex->IgnoreParenCasts();
4245
4246 for (;;) {
4247 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4248 if (!BO || !BO->isAdditiveOp())
4249 break;
4250
4251 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4252 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4253
4254 if (isa<IntegerLiteral>(RHS))
4255 Ex = LHS;
4256 else if (isa<IntegerLiteral>(LHS))
4257 Ex = RHS;
4258 else
4259 break;
4260 }
4261
4262 return Ex;
4263}
4264
Anna Zaks13b08572012-08-08 21:42:23 +00004265static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4266 ASTContext &Context) {
4267 // Only handle constant-sized or VLAs, but not flexible members.
4268 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4269 // Only issue the FIXIT for arrays of size > 1.
4270 if (CAT->getSize().getSExtValue() <= 1)
4271 return false;
4272 } else if (!Ty->isVariableArrayType()) {
4273 return false;
4274 }
4275 return true;
4276}
4277
Ted Kremenek6865f772011-08-18 20:55:45 +00004278// Warn if the user has made the 'size' argument to strlcpy or strlcat
4279// be the size of the source, instead of the destination.
4280void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4281 IdentifierInfo *FnName) {
4282
4283 // Don't crash if the user has the wrong number of arguments
4284 if (Call->getNumArgs() != 3)
4285 return;
4286
4287 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4288 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004289 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004290
4291 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4292 Call->getLocStart(), Call->getRParenLoc()))
4293 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004294
4295 // Look for 'strlcpy(dst, x, sizeof(x))'
4296 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4297 CompareWithSrc = Ex;
4298 else {
4299 // Look for 'strlcpy(dst, x, strlen(x))'
4300 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004301 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4302 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004303 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4304 }
4305 }
4306
4307 if (!CompareWithSrc)
4308 return;
4309
4310 // Determine if the argument to sizeof/strlen is equal to the source
4311 // argument. In principle there's all kinds of things you could do
4312 // here, for instance creating an == expression and evaluating it with
4313 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4314 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4315 if (!SrcArgDRE)
4316 return;
4317
4318 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4319 if (!CompareWithSrcDRE ||
4320 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4321 return;
4322
4323 const Expr *OriginalSizeArg = Call->getArg(2);
4324 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4325 << OriginalSizeArg->getSourceRange() << FnName;
4326
4327 // Output a FIXIT hint if the destination is an array (rather than a
4328 // pointer to an array). This could be enhanced to handle some
4329 // pointers if we know the actual size, like if DstArg is 'array+2'
4330 // we could say 'sizeof(array)-2'.
4331 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004332 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004333 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004334
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004335 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004336 llvm::raw_svector_ostream OS(sizeString);
4337 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004338 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004339 OS << ")";
4340
4341 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4342 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4343 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004344}
4345
Anna Zaks314cd092012-02-01 19:08:57 +00004346/// Check if two expressions refer to the same declaration.
4347static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4348 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4349 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4350 return D1->getDecl() == D2->getDecl();
4351 return false;
4352}
4353
4354static const Expr *getStrlenExprArg(const Expr *E) {
4355 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4356 const FunctionDecl *FD = CE->getDirectCallee();
4357 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004358 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004359 return CE->getArg(0)->IgnoreParenCasts();
4360 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004361 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004362}
4363
4364// Warn on anti-patterns as the 'size' argument to strncat.
4365// The correct size argument should look like following:
4366// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4367void Sema::CheckStrncatArguments(const CallExpr *CE,
4368 IdentifierInfo *FnName) {
4369 // Don't crash if the user has the wrong number of arguments.
4370 if (CE->getNumArgs() < 3)
4371 return;
4372 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4373 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4374 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4375
Nico Weber0e6daef2013-12-26 23:38:39 +00004376 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4377 CE->getRParenLoc()))
4378 return;
4379
Anna Zaks314cd092012-02-01 19:08:57 +00004380 // Identify common expressions, which are wrongly used as the size argument
4381 // to strncat and may lead to buffer overflows.
4382 unsigned PatternType = 0;
4383 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4384 // - sizeof(dst)
4385 if (referToTheSameDecl(SizeOfArg, DstArg))
4386 PatternType = 1;
4387 // - sizeof(src)
4388 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4389 PatternType = 2;
4390 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4391 if (BE->getOpcode() == BO_Sub) {
4392 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4393 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4394 // - sizeof(dst) - strlen(dst)
4395 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4396 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4397 PatternType = 1;
4398 // - sizeof(src) - (anything)
4399 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4400 PatternType = 2;
4401 }
4402 }
4403
4404 if (PatternType == 0)
4405 return;
4406
Anna Zaks5069aa32012-02-03 01:27:37 +00004407 // Generate the diagnostic.
4408 SourceLocation SL = LenArg->getLocStart();
4409 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004410 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004411
4412 // If the function is defined as a builtin macro, do not show macro expansion.
4413 if (SM.isMacroArgExpansion(SL)) {
4414 SL = SM.getSpellingLoc(SL);
4415 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4416 SM.getSpellingLoc(SR.getEnd()));
4417 }
4418
Anna Zaks13b08572012-08-08 21:42:23 +00004419 // Check if the destination is an array (rather than a pointer to an array).
4420 QualType DstTy = DstArg->getType();
4421 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4422 Context);
4423 if (!isKnownSizeArray) {
4424 if (PatternType == 1)
4425 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4426 else
4427 Diag(SL, diag::warn_strncat_src_size) << SR;
4428 return;
4429 }
4430
Anna Zaks314cd092012-02-01 19:08:57 +00004431 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004432 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004433 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004434 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004435
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004436 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004437 llvm::raw_svector_ostream OS(sizeString);
4438 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004439 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004440 OS << ") - ";
4441 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004442 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004443 OS << ") - 1";
4444
Anna Zaks5069aa32012-02-03 01:27:37 +00004445 Diag(SL, diag::note_strncat_wrong_size)
4446 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004447}
4448
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004449//===--- CHECK: Return Address of Stack Variable --------------------------===//
4450
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004451static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4452 Decl *ParentDecl);
4453static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4454 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004455
4456/// CheckReturnStackAddr - Check if a return statement returns the address
4457/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004458static void
4459CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4460 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004461
Craig Topperc3ec1492014-05-26 06:22:03 +00004462 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004463 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004464
4465 // Perform checking for returned stack addresses, local blocks,
4466 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004467 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004468 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004469 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004470 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004471 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004472 }
4473
Craig Topperc3ec1492014-05-26 06:22:03 +00004474 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004475 return; // Nothing suspicious was found.
4476
4477 SourceLocation diagLoc;
4478 SourceRange diagRange;
4479 if (refVars.empty()) {
4480 diagLoc = stackE->getLocStart();
4481 diagRange = stackE->getSourceRange();
4482 } else {
4483 // We followed through a reference variable. 'stackE' contains the
4484 // problematic expression but we will warn at the return statement pointing
4485 // at the reference variable. We will later display the "trail" of
4486 // reference variables using notes.
4487 diagLoc = refVars[0]->getLocStart();
4488 diagRange = refVars[0]->getSourceRange();
4489 }
4490
4491 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004492 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004493 : diag::warn_ret_stack_addr)
4494 << DR->getDecl()->getDeclName() << diagRange;
4495 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004496 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004497 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004498 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004499 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004500 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4501 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004502 << diagRange;
4503 }
4504
4505 // Display the "trail" of reference variables that we followed until we
4506 // found the problematic expression using notes.
4507 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4508 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4509 // If this var binds to another reference var, show the range of the next
4510 // var, otherwise the var binds to the problematic expression, in which case
4511 // show the range of the expression.
4512 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4513 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004514 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4515 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004516 }
4517}
4518
4519/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4520/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004521/// to a location on the stack, a local block, an address of a label, or a
4522/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004523/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004524/// encounter a subexpression that (1) clearly does not lead to one of the
4525/// above problematic expressions (2) is something we cannot determine leads to
4526/// a problematic expression based on such local checking.
4527///
4528/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4529/// the expression that they point to. Such variables are added to the
4530/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004531///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004532/// EvalAddr processes expressions that are pointers that are used as
4533/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004534/// At the base case of the recursion is a check for the above problematic
4535/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004536///
4537/// This implementation handles:
4538///
4539/// * pointer-to-pointer casts
4540/// * implicit conversions from array references to pointers
4541/// * taking the address of fields
4542/// * arbitrary interplay between "&" and "*" operators
4543/// * pointer arithmetic from an address of a stack variable
4544/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004545static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4546 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004547 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004548 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004549
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004550 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004551 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004552 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004553 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004554 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004555
Peter Collingbourne91147592011-04-15 00:35:48 +00004556 E = E->IgnoreParens();
4557
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004558 // Our "symbolic interpreter" is just a dispatch off the currently
4559 // viewed AST node. We then recursively traverse the AST by calling
4560 // EvalAddr and EvalVal appropriately.
4561 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004562 case Stmt::DeclRefExprClass: {
4563 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4564
Richard Smith40f08eb2014-01-30 22:05:38 +00004565 // If we leave the immediate function, the lifetime isn't about to end.
4566 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004568
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004569 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4570 // If this is a reference variable, follow through to the expression that
4571 // it points to.
4572 if (V->hasLocalStorage() &&
4573 V->getType()->isReferenceType() && V->hasInit()) {
4574 // Add the reference variable to the "trail".
4575 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004576 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004577 }
4578
Craig Topperc3ec1492014-05-26 06:22:03 +00004579 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004580 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004581
Chris Lattner934edb22007-12-28 05:31:15 +00004582 case Stmt::UnaryOperatorClass: {
4583 // The only unary operator that make sense to handle here
4584 // is AddrOf. All others don't make sense as pointers.
4585 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004586
John McCalle3027922010-08-25 11:45:40 +00004587 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004588 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004589 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004590 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004591 }
Mike Stump11289f42009-09-09 15:08:12 +00004592
Chris Lattner934edb22007-12-28 05:31:15 +00004593 case Stmt::BinaryOperatorClass: {
4594 // Handle pointer arithmetic. All other binary operators are not valid
4595 // in this context.
4596 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004597 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004598
John McCalle3027922010-08-25 11:45:40 +00004599 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004600 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004601
Chris Lattner934edb22007-12-28 05:31:15 +00004602 Expr *Base = B->getLHS();
4603
4604 // Determine which argument is the real pointer base. It could be
4605 // the RHS argument instead of the LHS.
4606 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004607
Chris Lattner934edb22007-12-28 05:31:15 +00004608 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004609 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004610 }
Steve Naroff2752a172008-09-10 19:17:48 +00004611
Chris Lattner934edb22007-12-28 05:31:15 +00004612 // For conditional operators we need to see if either the LHS or RHS are
4613 // valid DeclRefExpr*s. If one of them is valid, we return it.
4614 case Stmt::ConditionalOperatorClass: {
4615 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004616
Chris Lattner934edb22007-12-28 05:31:15 +00004617 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004618 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4619 if (Expr *LHSExpr = C->getLHS()) {
4620 // In C++, we can have a throw-expression, which has 'void' type.
4621 if (!LHSExpr->getType()->isVoidType())
4622 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004623 return LHS;
4624 }
Chris Lattner934edb22007-12-28 05:31:15 +00004625
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004626 // In C++, we can have a throw-expression, which has 'void' type.
4627 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004628 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004629
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004630 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004631 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004632
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004633 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004634 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004635 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004636 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004637
4638 case Stmt::AddrLabelExprClass:
4639 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004640
John McCall28fc7092011-11-10 05:35:25 +00004641 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004642 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4643 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004644
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004645 // For casts, we need to handle conversions from arrays to
4646 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004647 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004648 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004649 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004650 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004651 case Stmt::CXXStaticCastExprClass:
4652 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004653 case Stmt::CXXConstCastExprClass:
4654 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004655 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4656 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00004657 case CK_LValueToRValue:
4658 case CK_NoOp:
4659 case CK_BaseToDerived:
4660 case CK_DerivedToBase:
4661 case CK_UncheckedDerivedToBase:
4662 case CK_Dynamic:
4663 case CK_CPointerToObjCPointerCast:
4664 case CK_BlockPointerToObjCPointerCast:
4665 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004666 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004667
4668 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004669 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004670
Richard Trieudadefde2014-07-02 04:39:38 +00004671 case CK_BitCast:
4672 if (SubExpr->getType()->isAnyPointerType() ||
4673 SubExpr->getType()->isBlockPointerType() ||
4674 SubExpr->getType()->isObjCQualifiedIdType())
4675 return EvalAddr(SubExpr, refVars, ParentDecl);
4676 else
4677 return nullptr;
4678
Eli Friedman8195ad72012-02-23 23:04:32 +00004679 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004680 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004681 }
Chris Lattner934edb22007-12-28 05:31:15 +00004682 }
Mike Stump11289f42009-09-09 15:08:12 +00004683
Douglas Gregorfe314812011-06-21 17:03:29 +00004684 case Stmt::MaterializeTemporaryExprClass:
4685 if (Expr *Result = EvalAddr(
4686 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004687 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004688 return Result;
4689
4690 return E;
4691
Chris Lattner934edb22007-12-28 05:31:15 +00004692 // Everything else: we simply don't reason about them.
4693 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004694 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004695 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004696}
Mike Stump11289f42009-09-09 15:08:12 +00004697
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004698
4699/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4700/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004701static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4702 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004703do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004704 // We should only be called for evaluating non-pointer expressions, or
4705 // expressions with a pointer type that are not used as references but instead
4706 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004707
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004708 // Our "symbolic interpreter" is just a dispatch off the currently
4709 // viewed AST node. We then recursively traverse the AST by calling
4710 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004711
4712 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004713 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004714 case Stmt::ImplicitCastExprClass: {
4715 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004716 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004717 E = IE->getSubExpr();
4718 continue;
4719 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004720 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004721 }
4722
John McCall28fc7092011-11-10 05:35:25 +00004723 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004724 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004725
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004726 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004727 // When we hit a DeclRefExpr we are looking at code that refers to a
4728 // variable's name. If it's not a reference variable we check if it has
4729 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004730 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004731
Richard Smith40f08eb2014-01-30 22:05:38 +00004732 // If we leave the immediate function, the lifetime isn't about to end.
4733 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004734 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004735
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004736 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4737 // Check if it refers to itself, e.g. "int& i = i;".
4738 if (V == ParentDecl)
4739 return DR;
4740
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004741 if (V->hasLocalStorage()) {
4742 if (!V->getType()->isReferenceType())
4743 return DR;
4744
4745 // Reference variable, follow through to the expression that
4746 // it points to.
4747 if (V->hasInit()) {
4748 // Add the reference variable to the "trail".
4749 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004750 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004751 }
4752 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004753 }
Mike Stump11289f42009-09-09 15:08:12 +00004754
Craig Topperc3ec1492014-05-26 06:22:03 +00004755 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004756 }
Mike Stump11289f42009-09-09 15:08:12 +00004757
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004758 case Stmt::UnaryOperatorClass: {
4759 // The only unary operator that make sense to handle here
4760 // is Deref. All others don't resolve to a "name." This includes
4761 // handling all sorts of rvalues passed to a unary operator.
4762 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004763
John McCalle3027922010-08-25 11:45:40 +00004764 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004765 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004766
Craig Topperc3ec1492014-05-26 06:22:03 +00004767 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004768 }
Mike Stump11289f42009-09-09 15:08:12 +00004769
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004770 case Stmt::ArraySubscriptExprClass: {
4771 // Array subscripts are potential references to data on the stack. We
4772 // retrieve the DeclRefExpr* for the array variable if it indeed
4773 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004774 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004775 }
Mike Stump11289f42009-09-09 15:08:12 +00004776
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004777 case Stmt::ConditionalOperatorClass: {
4778 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004779 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004780 ConditionalOperator *C = cast<ConditionalOperator>(E);
4781
Anders Carlsson801c5c72007-11-30 19:04:31 +00004782 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004783 if (Expr *LHSExpr = C->getLHS()) {
4784 // In C++, we can have a throw-expression, which has 'void' type.
4785 if (!LHSExpr->getType()->isVoidType())
4786 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4787 return LHS;
4788 }
4789
4790 // In C++, we can have a throw-expression, which has 'void' type.
4791 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004792 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004793
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004794 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004795 }
Mike Stump11289f42009-09-09 15:08:12 +00004796
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004797 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004798 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004799 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004800
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004801 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004802 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004803 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004804
4805 // Check whether the member type is itself a reference, in which case
4806 // we're not going to refer to the member, but to what the member refers to.
4807 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004808 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004809
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004810 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004811 }
Mike Stump11289f42009-09-09 15:08:12 +00004812
Douglas Gregorfe314812011-06-21 17:03:29 +00004813 case Stmt::MaterializeTemporaryExprClass:
4814 if (Expr *Result = EvalVal(
4815 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004816 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004817 return Result;
4818
4819 return E;
4820
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004821 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004822 // Check that we don't return or take the address of a reference to a
4823 // temporary. This is only useful in C++.
4824 if (!E->isTypeDependent() && E->isRValue())
4825 return E;
4826
4827 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004828 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004829 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004830} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004831}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004832
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004833void
4834Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4835 SourceLocation ReturnLoc,
4836 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004837 const AttrVec *Attrs,
4838 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004839 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4840
4841 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004842 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4843 CheckNonNullExpr(*this, RetValExp))
4844 Diag(ReturnLoc, diag::warn_null_ret)
4845 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004846
4847 // C++11 [basic.stc.dynamic.allocation]p4:
4848 // If an allocation function declared with a non-throwing
4849 // exception-specification fails to allocate storage, it shall return
4850 // a null pointer. Any other allocation function that fails to allocate
4851 // storage shall indicate failure only by throwing an exception [...]
4852 if (FD) {
4853 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4854 if (Op == OO_New || Op == OO_Array_New) {
4855 const FunctionProtoType *Proto
4856 = FD->getType()->castAs<FunctionProtoType>();
4857 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4858 CheckNonNullExpr(*this, RetValExp))
4859 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4860 << FD << getLangOpts().CPlusPlus11;
4861 }
4862 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004863}
4864
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004865//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4866
4867/// Check for comparisons of floating point operands using != and ==.
4868/// Issue a warning if these are no self-comparisons, as they are not likely
4869/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004870void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004871 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4872 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004873
4874 // Special case: check for x == x (which is OK).
4875 // Do not emit warnings for such cases.
4876 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4877 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4878 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004879 return;
Mike Stump11289f42009-09-09 15:08:12 +00004880
4881
Ted Kremenekeda40e22007-11-29 00:59:04 +00004882 // Special case: check for comparisons against literals that can be exactly
4883 // represented by APFloat. In such cases, do not emit a warning. This
4884 // is a heuristic: often comparison against such literals are used to
4885 // detect if a value in a variable has not changed. This clearly can
4886 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004887 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4888 if (FLL->isExact())
4889 return;
4890 } else
4891 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4892 if (FLR->isExact())
4893 return;
Mike Stump11289f42009-09-09 15:08:12 +00004894
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004895 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004896 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004897 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004898 return;
Mike Stump11289f42009-09-09 15:08:12 +00004899
David Blaikie1f4ff152012-07-16 20:47:22 +00004900 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004901 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004902 return;
Mike Stump11289f42009-09-09 15:08:12 +00004903
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004904 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004905 Diag(Loc, diag::warn_floatingpoint_eq)
4906 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004907}
John McCallca01b222010-01-04 23:21:16 +00004908
John McCall70aa5392010-01-06 05:24:50 +00004909//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4910//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004911
John McCall70aa5392010-01-06 05:24:50 +00004912namespace {
John McCallca01b222010-01-04 23:21:16 +00004913
John McCall70aa5392010-01-06 05:24:50 +00004914/// Structure recording the 'active' range of an integer-valued
4915/// expression.
4916struct IntRange {
4917 /// The number of bits active in the int.
4918 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004919
John McCall70aa5392010-01-06 05:24:50 +00004920 /// True if the int is known not to have negative values.
4921 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004922
John McCall70aa5392010-01-06 05:24:50 +00004923 IntRange(unsigned Width, bool NonNegative)
4924 : Width(Width), NonNegative(NonNegative)
4925 {}
John McCallca01b222010-01-04 23:21:16 +00004926
John McCall817d4af2010-11-10 23:38:19 +00004927 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004928 static IntRange forBoolType() {
4929 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004930 }
4931
John McCall817d4af2010-11-10 23:38:19 +00004932 /// Returns the range of an opaque value of the given integral type.
4933 static IntRange forValueOfType(ASTContext &C, QualType T) {
4934 return forValueOfCanonicalType(C,
4935 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004936 }
4937
John McCall817d4af2010-11-10 23:38:19 +00004938 /// Returns the range of an opaque value of a canonical integral type.
4939 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004940 assert(T->isCanonicalUnqualified());
4941
4942 if (const VectorType *VT = dyn_cast<VectorType>(T))
4943 T = VT->getElementType().getTypePtr();
4944 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4945 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00004946 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
4947 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004948
David Majnemer6a426652013-06-07 22:07:20 +00004949 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004950 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004951 EnumDecl *Enum = ET->getDecl();
4952 if (!Enum->isCompleteDefinition())
4953 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004954
David Majnemer6a426652013-06-07 22:07:20 +00004955 unsigned NumPositive = Enum->getNumPositiveBits();
4956 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004957
David Majnemer6a426652013-06-07 22:07:20 +00004958 if (NumNegative == 0)
4959 return IntRange(NumPositive, true/*NonNegative*/);
4960 else
4961 return IntRange(std::max(NumPositive + 1, NumNegative),
4962 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004963 }
John McCall70aa5392010-01-06 05:24:50 +00004964
4965 const BuiltinType *BT = cast<BuiltinType>(T);
4966 assert(BT->isInteger());
4967
4968 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4969 }
4970
John McCall817d4af2010-11-10 23:38:19 +00004971 /// Returns the "target" range of a canonical integral type, i.e.
4972 /// the range of values expressible in the type.
4973 ///
4974 /// This matches forValueOfCanonicalType except that enums have the
4975 /// full range of their type, not the range of their enumerators.
4976 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4977 assert(T->isCanonicalUnqualified());
4978
4979 if (const VectorType *VT = dyn_cast<VectorType>(T))
4980 T = VT->getElementType().getTypePtr();
4981 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4982 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00004983 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
4984 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004985 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004986 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004987
4988 const BuiltinType *BT = cast<BuiltinType>(T);
4989 assert(BT->isInteger());
4990
4991 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4992 }
4993
4994 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004995 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004996 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004997 L.NonNegative && R.NonNegative);
4998 }
4999
John McCall817d4af2010-11-10 23:38:19 +00005000 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005001 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005002 return IntRange(std::min(L.Width, R.Width),
5003 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005004 }
5005};
5006
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005007static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5008 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005009 if (value.isSigned() && value.isNegative())
5010 return IntRange(value.getMinSignedBits(), false);
5011
5012 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005013 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005014
5015 // isNonNegative() just checks the sign bit without considering
5016 // signedness.
5017 return IntRange(value.getActiveBits(), true);
5018}
5019
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005020static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5021 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005022 if (result.isInt())
5023 return GetValueRange(C, result.getInt(), MaxWidth);
5024
5025 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005026 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5027 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5028 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5029 R = IntRange::join(R, El);
5030 }
John McCall70aa5392010-01-06 05:24:50 +00005031 return R;
5032 }
5033
5034 if (result.isComplexInt()) {
5035 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5036 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5037 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005038 }
5039
5040 // This can happen with lossless casts to intptr_t of "based" lvalues.
5041 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005042 // FIXME: The only reason we need to pass the type in here is to get
5043 // the sign right on this one case. It would be nice if APValue
5044 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005045 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005046 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005047}
John McCall70aa5392010-01-06 05:24:50 +00005048
Eli Friedmane6d33952013-07-08 20:20:06 +00005049static QualType GetExprType(Expr *E) {
5050 QualType Ty = E->getType();
5051 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5052 Ty = AtomicRHS->getValueType();
5053 return Ty;
5054}
5055
John McCall70aa5392010-01-06 05:24:50 +00005056/// Pseudo-evaluate the given integer expression, estimating the
5057/// range of values it might take.
5058///
5059/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005060static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005061 E = E->IgnoreParens();
5062
5063 // Try a full evaluation first.
5064 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005065 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005066 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005067
5068 // I think we only want to look through implicit casts here; if the
5069 // user has an explicit widening cast, we should treat the value as
5070 // being of the new, wider type.
5071 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005072 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005073 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5074
Eli Friedmane6d33952013-07-08 20:20:06 +00005075 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005076
John McCalle3027922010-08-25 11:45:40 +00005077 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005078
John McCall70aa5392010-01-06 05:24:50 +00005079 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005080 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005081 return OutputTypeRange;
5082
5083 IntRange SubRange
5084 = GetExprRange(C, CE->getSubExpr(),
5085 std::min(MaxWidth, OutputTypeRange.Width));
5086
5087 // Bail out if the subexpr's range is as wide as the cast type.
5088 if (SubRange.Width >= OutputTypeRange.Width)
5089 return OutputTypeRange;
5090
5091 // Otherwise, we take the smaller width, and we're non-negative if
5092 // either the output type or the subexpr is.
5093 return IntRange(SubRange.Width,
5094 SubRange.NonNegative || OutputTypeRange.NonNegative);
5095 }
5096
5097 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5098 // If we can fold the condition, just take that operand.
5099 bool CondResult;
5100 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5101 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5102 : CO->getFalseExpr(),
5103 MaxWidth);
5104
5105 // Otherwise, conservatively merge.
5106 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5107 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5108 return IntRange::join(L, R);
5109 }
5110
5111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5112 switch (BO->getOpcode()) {
5113
5114 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005115 case BO_LAnd:
5116 case BO_LOr:
5117 case BO_LT:
5118 case BO_GT:
5119 case BO_LE:
5120 case BO_GE:
5121 case BO_EQ:
5122 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005123 return IntRange::forBoolType();
5124
John McCallc3688382011-07-13 06:35:24 +00005125 // The type of the assignments is the type of the LHS, so the RHS
5126 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005127 case BO_MulAssign:
5128 case BO_DivAssign:
5129 case BO_RemAssign:
5130 case BO_AddAssign:
5131 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005132 case BO_XorAssign:
5133 case BO_OrAssign:
5134 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005135 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005136
John McCallc3688382011-07-13 06:35:24 +00005137 // Simple assignments just pass through the RHS, which will have
5138 // been coerced to the LHS type.
5139 case BO_Assign:
5140 // TODO: bitfields?
5141 return GetExprRange(C, BO->getRHS(), MaxWidth);
5142
John McCall70aa5392010-01-06 05:24:50 +00005143 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005144 case BO_PtrMemD:
5145 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005146 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005147
John McCall2ce81ad2010-01-06 22:07:33 +00005148 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005149 case BO_And:
5150 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005151 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5152 GetExprRange(C, BO->getRHS(), MaxWidth));
5153
John McCall70aa5392010-01-06 05:24:50 +00005154 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005155 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005156 // ...except that we want to treat '1 << (blah)' as logically
5157 // positive. It's an important idiom.
5158 if (IntegerLiteral *I
5159 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5160 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005161 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005162 return IntRange(R.Width, /*NonNegative*/ true);
5163 }
5164 }
5165 // fallthrough
5166
John McCalle3027922010-08-25 11:45:40 +00005167 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005168 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005169
John McCall2ce81ad2010-01-06 22:07:33 +00005170 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005171 case BO_Shr:
5172 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005173 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5174
5175 // If the shift amount is a positive constant, drop the width by
5176 // that much.
5177 llvm::APSInt shift;
5178 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5179 shift.isNonNegative()) {
5180 unsigned zext = shift.getZExtValue();
5181 if (zext >= L.Width)
5182 L.Width = (L.NonNegative ? 0 : 1);
5183 else
5184 L.Width -= zext;
5185 }
5186
5187 return L;
5188 }
5189
5190 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005191 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005192 return GetExprRange(C, BO->getRHS(), MaxWidth);
5193
John McCall2ce81ad2010-01-06 22:07:33 +00005194 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005195 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005196 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005197 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005198 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005199
John McCall51431812011-07-14 22:39:48 +00005200 // The width of a division result is mostly determined by the size
5201 // of the LHS.
5202 case BO_Div: {
5203 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005204 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005205 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5206
5207 // If the divisor is constant, use that.
5208 llvm::APSInt divisor;
5209 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5210 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5211 if (log2 >= L.Width)
5212 L.Width = (L.NonNegative ? 0 : 1);
5213 else
5214 L.Width = std::min(L.Width - log2, MaxWidth);
5215 return L;
5216 }
5217
5218 // Otherwise, just use the LHS's width.
5219 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5220 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5221 }
5222
5223 // The result of a remainder can't be larger than the result of
5224 // either side.
5225 case BO_Rem: {
5226 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005227 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005228 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5229 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5230
5231 IntRange meet = IntRange::meet(L, R);
5232 meet.Width = std::min(meet.Width, MaxWidth);
5233 return meet;
5234 }
5235
5236 // The default behavior is okay for these.
5237 case BO_Mul:
5238 case BO_Add:
5239 case BO_Xor:
5240 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005241 break;
5242 }
5243
John McCall51431812011-07-14 22:39:48 +00005244 // The default case is to treat the operation as if it were closed
5245 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005246 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5247 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5248 return IntRange::join(L, R);
5249 }
5250
5251 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5252 switch (UO->getOpcode()) {
5253 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005254 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005255 return IntRange::forBoolType();
5256
5257 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005258 case UO_Deref:
5259 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005260 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005261
5262 default:
5263 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5264 }
5265 }
5266
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005267 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5268 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5269
John McCalld25db7e2013-05-06 21:39:12 +00005270 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005271 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005272 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005273
Eli Friedmane6d33952013-07-08 20:20:06 +00005274 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005275}
John McCall263a48b2010-01-04 23:31:57 +00005276
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005277static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005278 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005279}
5280
John McCall263a48b2010-01-04 23:31:57 +00005281/// Checks whether the given value, which currently has the given
5282/// source semantics, has the same value when coerced through the
5283/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005284static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5285 const llvm::fltSemantics &Src,
5286 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005287 llvm::APFloat truncated = value;
5288
5289 bool ignored;
5290 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5291 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5292
5293 return truncated.bitwiseIsEqual(value);
5294}
5295
5296/// Checks whether the given value, which currently has the given
5297/// source semantics, has the same value when coerced through the
5298/// target semantics.
5299///
5300/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005301static bool IsSameFloatAfterCast(const APValue &value,
5302 const llvm::fltSemantics &Src,
5303 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005304 if (value.isFloat())
5305 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5306
5307 if (value.isVector()) {
5308 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5309 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5310 return false;
5311 return true;
5312 }
5313
5314 assert(value.isComplexFloat());
5315 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5316 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5317}
5318
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005319static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005320
Ted Kremenek6274be42010-09-23 21:43:44 +00005321static bool IsZero(Sema &S, Expr *E) {
5322 // Suppress cases where we are comparing against an enum constant.
5323 if (const DeclRefExpr *DR =
5324 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5325 if (isa<EnumConstantDecl>(DR->getDecl()))
5326 return false;
5327
5328 // Suppress cases where the '0' value is expanded from a macro.
5329 if (E->getLocStart().isMacroID())
5330 return false;
5331
John McCallcc7e5bf2010-05-06 08:58:33 +00005332 llvm::APSInt Value;
5333 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5334}
5335
John McCall2551c1b2010-10-06 00:25:24 +00005336static bool HasEnumType(Expr *E) {
5337 // Strip off implicit integral promotions.
5338 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005339 if (ICE->getCastKind() != CK_IntegralCast &&
5340 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005341 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005342 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005343 }
5344
5345 return E->getType()->isEnumeralType();
5346}
5347
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005348static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005349 // Disable warning in template instantiations.
5350 if (!S.ActiveTemplateInstantiations.empty())
5351 return;
5352
John McCalle3027922010-08-25 11:45:40 +00005353 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005354 if (E->isValueDependent())
5355 return;
5356
John McCalle3027922010-08-25 11:45:40 +00005357 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005358 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005359 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005360 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005361 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005362 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005363 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005364 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005365 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005366 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005367 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005368 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005369 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005370 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005371 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005372 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5373 }
5374}
5375
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005376static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005377 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005378 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005379 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005380 // Disable warning in template instantiations.
5381 if (!S.ActiveTemplateInstantiations.empty())
5382 return;
5383
Richard Trieu0f097742014-04-04 04:13:47 +00005384 // TODO: Investigate using GetExprRange() to get tighter bounds
5385 // on the bit ranges.
5386 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005387 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5388 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005389 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5390 unsigned OtherWidth = OtherRange.Width;
5391
5392 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5393
Richard Trieu560910c2012-11-14 22:50:24 +00005394 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005395 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005396 return;
5397
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005398 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005399 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005400
Richard Trieu0f097742014-04-04 04:13:47 +00005401 // Used for diagnostic printout.
5402 enum {
5403 LiteralConstant = 0,
5404 CXXBoolLiteralTrue,
5405 CXXBoolLiteralFalse
5406 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005407
Richard Trieu0f097742014-04-04 04:13:47 +00005408 if (!OtherIsBooleanType) {
5409 QualType ConstantT = Constant->getType();
5410 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005411
Richard Trieu0f097742014-04-04 04:13:47 +00005412 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5413 return;
5414 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5415 "comparison with non-integer type");
5416
5417 bool ConstantSigned = ConstantT->isSignedIntegerType();
5418 bool CommonSigned = CommonT->isSignedIntegerType();
5419
5420 bool EqualityOnly = false;
5421
5422 if (CommonSigned) {
5423 // The common type is signed, therefore no signed to unsigned conversion.
5424 if (!OtherRange.NonNegative) {
5425 // Check that the constant is representable in type OtherT.
5426 if (ConstantSigned) {
5427 if (OtherWidth >= Value.getMinSignedBits())
5428 return;
5429 } else { // !ConstantSigned
5430 if (OtherWidth >= Value.getActiveBits() + 1)
5431 return;
5432 }
5433 } else { // !OtherSigned
5434 // Check that the constant is representable in type OtherT.
5435 // Negative values are out of range.
5436 if (ConstantSigned) {
5437 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5438 return;
5439 } else { // !ConstantSigned
5440 if (OtherWidth >= Value.getActiveBits())
5441 return;
5442 }
Richard Trieu560910c2012-11-14 22:50:24 +00005443 }
Richard Trieu0f097742014-04-04 04:13:47 +00005444 } else { // !CommonSigned
5445 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005446 if (OtherWidth >= Value.getActiveBits())
5447 return;
Craig Toppercf360162014-06-18 05:13:11 +00005448 } else { // OtherSigned
5449 assert(!ConstantSigned &&
5450 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005451 // Check to see if the constant is representable in OtherT.
5452 if (OtherWidth > Value.getActiveBits())
5453 return;
5454 // Check to see if the constant is equivalent to a negative value
5455 // cast to CommonT.
5456 if (S.Context.getIntWidth(ConstantT) ==
5457 S.Context.getIntWidth(CommonT) &&
5458 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5459 return;
5460 // The constant value rests between values that OtherT can represent
5461 // after conversion. Relational comparison still works, but equality
5462 // comparisons will be tautological.
5463 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005464 }
5465 }
Richard Trieu0f097742014-04-04 04:13:47 +00005466
5467 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5468
5469 if (op == BO_EQ || op == BO_NE) {
5470 IsTrue = op == BO_NE;
5471 } else if (EqualityOnly) {
5472 return;
5473 } else if (RhsConstant) {
5474 if (op == BO_GT || op == BO_GE)
5475 IsTrue = !PositiveConstant;
5476 else // op == BO_LT || op == BO_LE
5477 IsTrue = PositiveConstant;
5478 } else {
5479 if (op == BO_LT || op == BO_LE)
5480 IsTrue = !PositiveConstant;
5481 else // op == BO_GT || op == BO_GE
5482 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005483 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005484 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005485 // Other isKnownToHaveBooleanValue
5486 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5487 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5488 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5489
5490 static const struct LinkedConditions {
5491 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5492 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5493 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5494 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5495 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5496 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5497
5498 } TruthTable = {
5499 // Constant on LHS. | Constant on RHS. |
5500 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5501 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5502 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5503 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5504 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5505 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5506 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5507 };
5508
5509 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5510
5511 enum ConstantValue ConstVal = Zero;
5512 if (Value.isUnsigned() || Value.isNonNegative()) {
5513 if (Value == 0) {
5514 LiteralOrBoolConstant =
5515 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5516 ConstVal = Zero;
5517 } else if (Value == 1) {
5518 LiteralOrBoolConstant =
5519 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5520 ConstVal = One;
5521 } else {
5522 LiteralOrBoolConstant = LiteralConstant;
5523 ConstVal = GT_One;
5524 }
5525 } else {
5526 ConstVal = LT_Zero;
5527 }
5528
5529 CompareBoolWithConstantResult CmpRes;
5530
5531 switch (op) {
5532 case BO_LT:
5533 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5534 break;
5535 case BO_GT:
5536 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5537 break;
5538 case BO_LE:
5539 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5540 break;
5541 case BO_GE:
5542 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5543 break;
5544 case BO_EQ:
5545 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5546 break;
5547 case BO_NE:
5548 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5549 break;
5550 default:
5551 CmpRes = Unkwn;
5552 break;
5553 }
5554
5555 if (CmpRes == AFals) {
5556 IsTrue = false;
5557 } else if (CmpRes == ATrue) {
5558 IsTrue = true;
5559 } else {
5560 return;
5561 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005562 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005563
5564 // If this is a comparison to an enum constant, include that
5565 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005566 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005567 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5568 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5569
5570 SmallString<64> PrettySourceValue;
5571 llvm::raw_svector_ostream OS(PrettySourceValue);
5572 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005573 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005574 else
5575 OS << Value;
5576
Richard Trieu0f097742014-04-04 04:13:47 +00005577 S.DiagRuntimeBehavior(
5578 E->getOperatorLoc(), E,
5579 S.PDiag(diag::warn_out_of_range_compare)
5580 << OS.str() << LiteralOrBoolConstant
5581 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5582 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005583}
5584
John McCallcc7e5bf2010-05-06 08:58:33 +00005585/// Analyze the operands of the given comparison. Implements the
5586/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005587static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005588 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5589 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005590}
John McCall263a48b2010-01-04 23:31:57 +00005591
John McCallca01b222010-01-04 23:21:16 +00005592/// \brief Implements -Wsign-compare.
5593///
Richard Trieu82402a02011-09-15 21:56:47 +00005594/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005595static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005596 // The type the comparison is being performed in.
5597 QualType T = E->getLHS()->getType();
5598 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5599 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005600 if (E->isValueDependent())
5601 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005602
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005603 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5604 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005605
5606 bool IsComparisonConstant = false;
5607
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005608 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005609 // of 'true' or 'false'.
5610 if (T->isIntegralType(S.Context)) {
5611 llvm::APSInt RHSValue;
5612 bool IsRHSIntegralLiteral =
5613 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5614 llvm::APSInt LHSValue;
5615 bool IsLHSIntegralLiteral =
5616 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5617 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5618 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5619 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5620 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5621 else
5622 IsComparisonConstant =
5623 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005624 } else if (!T->hasUnsignedIntegerRepresentation())
5625 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005626
John McCallcc7e5bf2010-05-06 08:58:33 +00005627 // We don't do anything special if this isn't an unsigned integral
5628 // comparison: we're only interested in integral comparisons, and
5629 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005630 //
5631 // We also don't care about value-dependent expressions or expressions
5632 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005633 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005634 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005635
John McCallcc7e5bf2010-05-06 08:58:33 +00005636 // Check to see if one of the (unmodified) operands is of different
5637 // signedness.
5638 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005639 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5640 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005641 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005642 signedOperand = LHS;
5643 unsignedOperand = RHS;
5644 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5645 signedOperand = RHS;
5646 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005647 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005648 CheckTrivialUnsignedComparison(S, E);
5649 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005650 }
5651
John McCallcc7e5bf2010-05-06 08:58:33 +00005652 // Otherwise, calculate the effective range of the signed operand.
5653 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005654
John McCallcc7e5bf2010-05-06 08:58:33 +00005655 // Go ahead and analyze implicit conversions in the operands. Note
5656 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005657 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5658 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005659
John McCallcc7e5bf2010-05-06 08:58:33 +00005660 // If the signed range is non-negative, -Wsign-compare won't fire,
5661 // but we should still check for comparisons which are always true
5662 // or false.
5663 if (signedRange.NonNegative)
5664 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005665
5666 // For (in)equality comparisons, if the unsigned operand is a
5667 // constant which cannot collide with a overflowed signed operand,
5668 // then reinterpreting the signed operand as unsigned will not
5669 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005670 if (E->isEqualityOp()) {
5671 unsigned comparisonWidth = S.Context.getIntWidth(T);
5672 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005673
John McCallcc7e5bf2010-05-06 08:58:33 +00005674 // We should never be unable to prove that the unsigned operand is
5675 // non-negative.
5676 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5677
5678 if (unsignedRange.Width < comparisonWidth)
5679 return;
5680 }
5681
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005682 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5683 S.PDiag(diag::warn_mixed_sign_comparison)
5684 << LHS->getType() << RHS->getType()
5685 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005686}
5687
John McCall1f425642010-11-11 03:21:53 +00005688/// Analyzes an attempt to assign the given value to a bitfield.
5689///
5690/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005691static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5692 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005693 assert(Bitfield->isBitField());
5694 if (Bitfield->isInvalidDecl())
5695 return false;
5696
John McCalldeebbcf2010-11-11 05:33:51 +00005697 // White-list bool bitfields.
5698 if (Bitfield->getType()->isBooleanType())
5699 return false;
5700
Douglas Gregor789adec2011-02-04 13:09:01 +00005701 // Ignore value- or type-dependent expressions.
5702 if (Bitfield->getBitWidth()->isValueDependent() ||
5703 Bitfield->getBitWidth()->isTypeDependent() ||
5704 Init->isValueDependent() ||
5705 Init->isTypeDependent())
5706 return false;
5707
John McCall1f425642010-11-11 03:21:53 +00005708 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5709
Richard Smith5fab0c92011-12-28 19:48:30 +00005710 llvm::APSInt Value;
5711 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005712 return false;
5713
John McCall1f425642010-11-11 03:21:53 +00005714 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005715 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005716
5717 if (OriginalWidth <= FieldWidth)
5718 return false;
5719
Eli Friedmanc267a322012-01-26 23:11:39 +00005720 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005721 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005722 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005723
Eli Friedmanc267a322012-01-26 23:11:39 +00005724 // Check whether the stored value is equal to the original value.
5725 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005726 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005727 return false;
5728
Eli Friedmanc267a322012-01-26 23:11:39 +00005729 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005730 // therefore don't strictly fit into a signed bitfield of width 1.
5731 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005732 return false;
5733
John McCall1f425642010-11-11 03:21:53 +00005734 std::string PrettyValue = Value.toString(10);
5735 std::string PrettyTrunc = TruncatedValue.toString(10);
5736
5737 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5738 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5739 << Init->getSourceRange();
5740
5741 return true;
5742}
5743
John McCalld2a53122010-11-09 23:24:47 +00005744/// Analyze the given simple or compound assignment for warning-worthy
5745/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005746static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005747 // Just recurse on the LHS.
5748 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5749
5750 // We want to recurse on the RHS as normal unless we're assigning to
5751 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005752 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005753 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005754 E->getOperatorLoc())) {
5755 // Recurse, ignoring any implicit conversions on the RHS.
5756 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5757 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005758 }
5759 }
5760
5761 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5762}
5763
John McCall263a48b2010-01-04 23:31:57 +00005764/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005765static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005766 SourceLocation CContext, unsigned diag,
5767 bool pruneControlFlow = false) {
5768 if (pruneControlFlow) {
5769 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5770 S.PDiag(diag)
5771 << SourceType << T << E->getSourceRange()
5772 << SourceRange(CContext));
5773 return;
5774 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005775 S.Diag(E->getExprLoc(), diag)
5776 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5777}
5778
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005779/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005780static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005781 SourceLocation CContext, unsigned diag,
5782 bool pruneControlFlow = false) {
5783 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005784}
5785
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005786/// Diagnose an implicit cast from a literal expression. Does not warn when the
5787/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005788void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5789 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005790 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005791 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005792 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005793 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5794 T->hasUnsignedIntegerRepresentation());
5795 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005796 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005797 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005798 return;
5799
Eli Friedman07185912013-08-29 23:44:43 +00005800 // FIXME: Force the precision of the source value down so we don't print
5801 // digits which are usually useless (we don't really care here if we
5802 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5803 // would automatically print the shortest representation, but it's a bit
5804 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005805 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005806 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5807 precision = (precision * 59 + 195) / 196;
5808 Value.toString(PrettySourceValue, precision);
5809
David Blaikie9b88cc02012-05-15 17:18:27 +00005810 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005811 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5812 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5813 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005814 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005815
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005816 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005817 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5818 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005819}
5820
John McCall18a2c2c2010-11-09 22:22:12 +00005821std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5822 if (!Range.Width) return "0";
5823
5824 llvm::APSInt ValueInRange = Value;
5825 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005826 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005827 return ValueInRange.toString(10);
5828}
5829
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005830static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5831 if (!isa<ImplicitCastExpr>(Ex))
5832 return false;
5833
5834 Expr *InnerE = Ex->IgnoreParenImpCasts();
5835 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5836 const Type *Source =
5837 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5838 if (Target->isDependentType())
5839 return false;
5840
5841 const BuiltinType *FloatCandidateBT =
5842 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5843 const Type *BoolCandidateType = ToBool ? Target : Source;
5844
5845 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5846 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5847}
5848
5849void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5850 SourceLocation CC) {
5851 unsigned NumArgs = TheCall->getNumArgs();
5852 for (unsigned i = 0; i < NumArgs; ++i) {
5853 Expr *CurrA = TheCall->getArg(i);
5854 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5855 continue;
5856
5857 bool IsSwapped = ((i > 0) &&
5858 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5859 IsSwapped |= ((i < (NumArgs - 1)) &&
5860 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5861 if (IsSwapped) {
5862 // Warn on this floating-point to bool conversion.
5863 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5864 CurrA->getType(), CC,
5865 diag::warn_impcast_floating_point_to_bool);
5866 }
5867 }
5868}
5869
John McCallcc7e5bf2010-05-06 08:58:33 +00005870void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005871 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005872 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005873
John McCallcc7e5bf2010-05-06 08:58:33 +00005874 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5875 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5876 if (Source == Target) return;
5877 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005878
Chandler Carruthc22845a2011-07-26 05:40:03 +00005879 // If the conversion context location is invalid don't complain. We also
5880 // don't want to emit a warning if the issue occurs from the expansion of
5881 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5882 // delay this check as long as possible. Once we detect we are in that
5883 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005884 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005885 return;
5886
Richard Trieu021baa32011-09-23 20:10:00 +00005887 // Diagnose implicit casts to bool.
5888 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5889 if (isa<StringLiteral>(E))
5890 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005891 // and expressions, for instance, assert(0 && "error here"), are
5892 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005893 return DiagnoseImpCast(S, E, T, CC,
5894 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005895 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5896 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5897 // This covers the literal expressions that evaluate to Objective-C
5898 // objects.
5899 return DiagnoseImpCast(S, E, T, CC,
5900 diag::warn_impcast_objective_c_literal_to_bool);
5901 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005902 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5903 // Warn on pointer to bool conversion that is always true.
5904 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5905 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005906 }
Richard Trieu021baa32011-09-23 20:10:00 +00005907 }
John McCall263a48b2010-01-04 23:31:57 +00005908
5909 // Strip vector types.
5910 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005911 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005912 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005913 return;
John McCallacf0ee52010-10-08 02:01:28 +00005914 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005915 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005916
5917 // If the vector cast is cast between two vectors of the same size, it is
5918 // a bitcast, not a conversion.
5919 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5920 return;
John McCall263a48b2010-01-04 23:31:57 +00005921
5922 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5923 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5924 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005925 if (auto VecTy = dyn_cast<VectorType>(Target))
5926 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005927
5928 // Strip complex types.
5929 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005930 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005931 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005932 return;
5933
John McCallacf0ee52010-10-08 02:01:28 +00005934 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005935 }
John McCall263a48b2010-01-04 23:31:57 +00005936
5937 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5938 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5939 }
5940
5941 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5942 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5943
5944 // If the source is floating point...
5945 if (SourceBT && SourceBT->isFloatingPoint()) {
5946 // ...and the target is floating point...
5947 if (TargetBT && TargetBT->isFloatingPoint()) {
5948 // ...then warn if we're dropping FP rank.
5949
5950 // Builtin FP kinds are ordered by increasing FP rank.
5951 if (SourceBT->getKind() > TargetBT->getKind()) {
5952 // Don't warn about float constants that are precisely
5953 // representable in the target type.
5954 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005955 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005956 // Value might be a float, a float vector, or a float complex.
5957 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005958 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5959 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005960 return;
5961 }
5962
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005963 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005964 return;
5965
John McCallacf0ee52010-10-08 02:01:28 +00005966 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005967 }
5968 return;
5969 }
5970
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005971 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005972 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005973 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005974 return;
5975
Chandler Carruth22c7a792011-02-17 11:05:49 +00005976 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005977 // We also want to warn on, e.g., "int i = -1.234"
5978 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5979 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5980 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5981
Chandler Carruth016ef402011-04-10 08:36:24 +00005982 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5983 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005984 } else {
5985 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5986 }
5987 }
John McCall263a48b2010-01-04 23:31:57 +00005988
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005989 // If the target is bool, warn if expr is a function or method call.
5990 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5991 isa<CallExpr>(E)) {
5992 // Check last argument of function call to see if it is an
5993 // implicit cast from a type matching the type the result
5994 // is being cast to.
5995 CallExpr *CEx = cast<CallExpr>(E);
5996 unsigned NumArgs = CEx->getNumArgs();
5997 if (NumArgs > 0) {
5998 Expr *LastA = CEx->getArg(NumArgs - 1);
5999 Expr *InnerE = LastA->IgnoreParenImpCasts();
6000 const Type *InnerType =
6001 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6002 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6003 // Warn on this floating-point to bool conversion
6004 DiagnoseImpCast(S, E, T, CC,
6005 diag::warn_impcast_floating_point_to_bool);
6006 }
6007 }
6008 }
John McCall263a48b2010-01-04 23:31:57 +00006009 return;
6010 }
6011
Richard Trieubeaf3452011-05-29 19:59:02 +00006012 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00006013 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00006014 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00006015 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00006016 SourceLocation Loc = E->getSourceRange().getBegin();
6017 if (Loc.isMacroID())
6018 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00006019 if (!Loc.isMacroID() || CC.isMacroID())
6020 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6021 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00006022 << FixItHint::CreateReplacement(Loc,
6023 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00006024 }
6025
David Blaikie9366d2b2012-06-19 21:19:06 +00006026 if (!Source->isIntegerType() || !Target->isIntegerType())
6027 return;
6028
David Blaikie7555b6a2012-05-15 16:56:36 +00006029 // TODO: remove this early return once the false positives for constant->bool
6030 // in templates, macros, etc, are reduced or removed.
6031 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6032 return;
6033
John McCallcc7e5bf2010-05-06 08:58:33 +00006034 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006035 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006036
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006037 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006038 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006039 // TODO: this should happen for bitfield stores, too.
6040 llvm::APSInt Value(32);
6041 if (E->isIntegerConstantExpr(Value, S.Context)) {
6042 if (S.SourceMgr.isInSystemMacro(CC))
6043 return;
6044
John McCall18a2c2c2010-11-09 22:22:12 +00006045 std::string PrettySourceValue = Value.toString(10);
6046 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006047
Ted Kremenek33ba9952011-10-22 02:37:33 +00006048 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6049 S.PDiag(diag::warn_impcast_integer_precision_constant)
6050 << PrettySourceValue << PrettyTargetValue
6051 << E->getType() << T << E->getSourceRange()
6052 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006053 return;
6054 }
6055
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006056 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6057 if (S.SourceMgr.isInSystemMacro(CC))
6058 return;
6059
David Blaikie9455da02012-04-12 22:40:54 +00006060 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006061 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6062 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006063 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006064 }
6065
6066 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6067 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6068 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006069
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006070 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006071 return;
6072
John McCallcc7e5bf2010-05-06 08:58:33 +00006073 unsigned DiagID = diag::warn_impcast_integer_sign;
6074
6075 // Traditionally, gcc has warned about this under -Wsign-compare.
6076 // We also want to warn about it in -Wconversion.
6077 // So if -Wconversion is off, use a completely identical diagnostic
6078 // in the sign-compare group.
6079 // The conditional-checking code will
6080 if (ICContext) {
6081 DiagID = diag::warn_impcast_integer_sign_conditional;
6082 *ICContext = true;
6083 }
6084
John McCallacf0ee52010-10-08 02:01:28 +00006085 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006086 }
6087
Douglas Gregora78f1932011-02-22 02:45:07 +00006088 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006089 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6090 // type, to give us better diagnostics.
6091 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006092 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006093 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6094 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6095 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6096 SourceType = S.Context.getTypeDeclType(Enum);
6097 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6098 }
6099 }
6100
Douglas Gregora78f1932011-02-22 02:45:07 +00006101 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6102 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006103 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6104 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006105 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006106 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006107 return;
6108
Douglas Gregor364f7db2011-03-12 00:14:31 +00006109 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006110 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006111 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006112
John McCall263a48b2010-01-04 23:31:57 +00006113 return;
6114}
6115
David Blaikie18e9ac72012-05-15 21:57:38 +00006116void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6117 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006118
6119void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006120 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006121 E = E->IgnoreParenImpCasts();
6122
6123 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006124 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006125
John McCallacf0ee52010-10-08 02:01:28 +00006126 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006127 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006128 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006129 return;
6130}
6131
David Blaikie18e9ac72012-05-15 21:57:38 +00006132void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6133 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006134 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006135
6136 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006137 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6138 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006139
6140 // If -Wconversion would have warned about either of the candidates
6141 // for a signedness conversion to the context type...
6142 if (!Suspicious) return;
6143
6144 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006145 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006146 return;
6147
John McCallcc7e5bf2010-05-06 08:58:33 +00006148 // ...then check whether it would have warned about either of the
6149 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006150 if (E->getType() == T) return;
6151
6152 Suspicious = false;
6153 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6154 E->getType(), CC, &Suspicious);
6155 if (!Suspicious)
6156 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006157 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006158}
6159
6160/// AnalyzeImplicitConversions - Find and report any interesting
6161/// implicit conversions in the given expression. There are a couple
6162/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006163void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006164 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006165 Expr *E = OrigE->IgnoreParenImpCasts();
6166
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006167 if (E->isTypeDependent() || E->isValueDependent())
6168 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006169
John McCallcc7e5bf2010-05-06 08:58:33 +00006170 // For conditional operators, we analyze the arguments as if they
6171 // were being fed directly into the output.
6172 if (isa<ConditionalOperator>(E)) {
6173 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006174 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006175 return;
6176 }
6177
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006178 // Check implicit argument conversions for function calls.
6179 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6180 CheckImplicitArgumentConversions(S, Call, CC);
6181
John McCallcc7e5bf2010-05-06 08:58:33 +00006182 // Go ahead and check any implicit conversions we might have skipped.
6183 // The non-canonical typecheck is just an optimization;
6184 // CheckImplicitConversion will filter out dead implicit conversions.
6185 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006186 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006187
6188 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006189
6190 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006191 if (POE->getResultExpr())
6192 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006193 }
6194
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006195 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6196 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6197
John McCallcc7e5bf2010-05-06 08:58:33 +00006198 // Skip past explicit casts.
6199 if (isa<ExplicitCastExpr>(E)) {
6200 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006201 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006202 }
6203
John McCalld2a53122010-11-09 23:24:47 +00006204 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6205 // Do a somewhat different check with comparison operators.
6206 if (BO->isComparisonOp())
6207 return AnalyzeComparison(S, BO);
6208
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006209 // And with simple assignments.
6210 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006211 return AnalyzeAssignment(S, BO);
6212 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006213
6214 // These break the otherwise-useful invariant below. Fortunately,
6215 // we don't really need to recurse into them, because any internal
6216 // expressions should have been analyzed already when they were
6217 // built into statements.
6218 if (isa<StmtExpr>(E)) return;
6219
6220 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006221 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006222
6223 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006224 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006225 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006226 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006227 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006228 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006229 if (!ChildExpr)
6230 continue;
6231
Richard Trieu955231d2014-01-25 01:10:35 +00006232 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006233 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006234 // Ignore checking string literals that are in logical and operators.
6235 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006236 continue;
6237 AnalyzeImplicitConversions(S, ChildExpr, CC);
6238 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006239}
6240
6241} // end anonymous namespace
6242
Richard Trieu3bb8b562014-02-26 02:36:06 +00006243enum {
6244 AddressOf,
6245 FunctionPointer,
6246 ArrayPointer
6247};
6248
Richard Trieuc1888e02014-06-28 23:25:37 +00006249// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6250// Returns true when emitting a warning about taking the address of a reference.
6251static bool CheckForReference(Sema &SemaRef, const Expr *E,
6252 PartialDiagnostic PD) {
6253 E = E->IgnoreParenImpCasts();
6254
6255 const FunctionDecl *FD = nullptr;
6256
6257 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6258 if (!DRE->getDecl()->getType()->isReferenceType())
6259 return false;
6260 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6261 if (!M->getMemberDecl()->getType()->isReferenceType())
6262 return false;
6263 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6264 if (!Call->getCallReturnType()->isReferenceType())
6265 return false;
6266 FD = Call->getDirectCallee();
6267 } else {
6268 return false;
6269 }
6270
6271 SemaRef.Diag(E->getExprLoc(), PD);
6272
6273 // If possible, point to location of function.
6274 if (FD) {
6275 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6276 }
6277
6278 return true;
6279}
6280
Richard Trieu3bb8b562014-02-26 02:36:06 +00006281/// \brief Diagnose pointers that are always non-null.
6282/// \param E the expression containing the pointer
6283/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6284/// compared to a null pointer
6285/// \param IsEqual True when the comparison is equal to a null pointer
6286/// \param Range Extra SourceRange to highlight in the diagnostic
6287void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6288 Expr::NullPointerConstantKind NullKind,
6289 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006290 if (!E)
6291 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006292
6293 // Don't warn inside macros.
6294 if (E->getExprLoc().isMacroID())
6295 return;
6296 E = E->IgnoreImpCasts();
6297
6298 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6299
Richard Trieuf7432752014-06-06 21:39:26 +00006300 if (isa<CXXThisExpr>(E)) {
6301 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6302 : diag::warn_this_bool_conversion;
6303 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6304 return;
6305 }
6306
Richard Trieu3bb8b562014-02-26 02:36:06 +00006307 bool IsAddressOf = false;
6308
6309 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6310 if (UO->getOpcode() != UO_AddrOf)
6311 return;
6312 IsAddressOf = true;
6313 E = UO->getSubExpr();
6314 }
6315
Richard Trieuc1888e02014-06-28 23:25:37 +00006316 if (IsAddressOf) {
6317 unsigned DiagID = IsCompare
6318 ? diag::warn_address_of_reference_null_compare
6319 : diag::warn_address_of_reference_bool_conversion;
6320 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6321 << IsEqual;
6322 if (CheckForReference(*this, E, PD)) {
6323 return;
6324 }
6325 }
6326
Richard Trieu3bb8b562014-02-26 02:36:06 +00006327 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006328 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006329 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6330 D = R->getDecl();
6331 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6332 D = M->getMemberDecl();
6333 }
6334
6335 // Weak Decls can be null.
6336 if (!D || D->isWeak())
6337 return;
6338
6339 QualType T = D->getType();
6340 const bool IsArray = T->isArrayType();
6341 const bool IsFunction = T->isFunctionType();
6342
Richard Trieuc1888e02014-06-28 23:25:37 +00006343 // Address of function is used to silence the function warning.
6344 if (IsAddressOf && IsFunction) {
6345 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006346 }
6347
6348 // Found nothing.
6349 if (!IsAddressOf && !IsFunction && !IsArray)
6350 return;
6351
6352 // Pretty print the expression for the diagnostic.
6353 std::string Str;
6354 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006355 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006356
6357 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6358 : diag::warn_impcast_pointer_to_bool;
6359 unsigned DiagType;
6360 if (IsAddressOf)
6361 DiagType = AddressOf;
6362 else if (IsFunction)
6363 DiagType = FunctionPointer;
6364 else if (IsArray)
6365 DiagType = ArrayPointer;
6366 else
6367 llvm_unreachable("Could not determine diagnostic.");
6368 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6369 << Range << IsEqual;
6370
6371 if (!IsFunction)
6372 return;
6373
6374 // Suggest '&' to silence the function warning.
6375 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6376 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6377
6378 // Check to see if '()' fixit should be emitted.
6379 QualType ReturnType;
6380 UnresolvedSet<4> NonTemplateOverloads;
6381 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6382 if (ReturnType.isNull())
6383 return;
6384
6385 if (IsCompare) {
6386 // There are two cases here. If there is null constant, the only suggest
6387 // for a pointer return type. If the null is 0, then suggest if the return
6388 // type is a pointer or an integer type.
6389 if (!ReturnType->isPointerType()) {
6390 if (NullKind == Expr::NPCK_ZeroExpression ||
6391 NullKind == Expr::NPCK_ZeroLiteral) {
6392 if (!ReturnType->isIntegerType())
6393 return;
6394 } else {
6395 return;
6396 }
6397 }
6398 } else { // !IsCompare
6399 // For function to bool, only suggest if the function pointer has bool
6400 // return type.
6401 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6402 return;
6403 }
6404 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006405 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006406}
6407
6408
John McCallcc7e5bf2010-05-06 08:58:33 +00006409/// Diagnoses "dangerous" implicit conversions within the given
6410/// expression (which is a full expression). Implements -Wconversion
6411/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006412///
6413/// \param CC the "context" location of the implicit conversion, i.e.
6414/// the most location of the syntactic entity requiring the implicit
6415/// conversion
6416void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006417 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006418 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006419 return;
6420
6421 // Don't diagnose for value- or type-dependent expressions.
6422 if (E->isTypeDependent() || E->isValueDependent())
6423 return;
6424
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006425 // Check for array bounds violations in cases where the check isn't triggered
6426 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6427 // ArraySubscriptExpr is on the RHS of a variable initialization.
6428 CheckArrayAccess(E);
6429
John McCallacf0ee52010-10-08 02:01:28 +00006430 // This is not the right CC for (e.g.) a variable initialization.
6431 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006432}
6433
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006434/// Diagnose when expression is an integer constant expression and its evaluation
6435/// results in integer overflow
6436void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006437 if (isa<BinaryOperator>(E->IgnoreParens()))
6438 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006439}
6440
Richard Smithc406cb72013-01-17 01:17:56 +00006441namespace {
6442/// \brief Visitor for expressions which looks for unsequenced operations on the
6443/// same object.
6444class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006445 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6446
Richard Smithc406cb72013-01-17 01:17:56 +00006447 /// \brief A tree of sequenced regions within an expression. Two regions are
6448 /// unsequenced if one is an ancestor or a descendent of the other. When we
6449 /// finish processing an expression with sequencing, such as a comma
6450 /// expression, we fold its tree nodes into its parent, since they are
6451 /// unsequenced with respect to nodes we will visit later.
6452 class SequenceTree {
6453 struct Value {
6454 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6455 unsigned Parent : 31;
6456 bool Merged : 1;
6457 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006458 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006459
6460 public:
6461 /// \brief A region within an expression which may be sequenced with respect
6462 /// to some other region.
6463 class Seq {
6464 explicit Seq(unsigned N) : Index(N) {}
6465 unsigned Index;
6466 friend class SequenceTree;
6467 public:
6468 Seq() : Index(0) {}
6469 };
6470
6471 SequenceTree() { Values.push_back(Value(0)); }
6472 Seq root() const { return Seq(0); }
6473
6474 /// \brief Create a new sequence of operations, which is an unsequenced
6475 /// subset of \p Parent. This sequence of operations is sequenced with
6476 /// respect to other children of \p Parent.
6477 Seq allocate(Seq Parent) {
6478 Values.push_back(Value(Parent.Index));
6479 return Seq(Values.size() - 1);
6480 }
6481
6482 /// \brief Merge a sequence of operations into its parent.
6483 void merge(Seq S) {
6484 Values[S.Index].Merged = true;
6485 }
6486
6487 /// \brief Determine whether two operations are unsequenced. This operation
6488 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6489 /// should have been merged into its parent as appropriate.
6490 bool isUnsequenced(Seq Cur, Seq Old) {
6491 unsigned C = representative(Cur.Index);
6492 unsigned Target = representative(Old.Index);
6493 while (C >= Target) {
6494 if (C == Target)
6495 return true;
6496 C = Values[C].Parent;
6497 }
6498 return false;
6499 }
6500
6501 private:
6502 /// \brief Pick a representative for a sequence.
6503 unsigned representative(unsigned K) {
6504 if (Values[K].Merged)
6505 // Perform path compression as we go.
6506 return Values[K].Parent = representative(Values[K].Parent);
6507 return K;
6508 }
6509 };
6510
6511 /// An object for which we can track unsequenced uses.
6512 typedef NamedDecl *Object;
6513
6514 /// Different flavors of object usage which we track. We only track the
6515 /// least-sequenced usage of each kind.
6516 enum UsageKind {
6517 /// A read of an object. Multiple unsequenced reads are OK.
6518 UK_Use,
6519 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006520 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006521 UK_ModAsValue,
6522 /// A modification of an object which is not sequenced before the value
6523 /// computation of the expression, such as n++.
6524 UK_ModAsSideEffect,
6525
6526 UK_Count = UK_ModAsSideEffect + 1
6527 };
6528
6529 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006530 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006531 Expr *Use;
6532 SequenceTree::Seq Seq;
6533 };
6534
6535 struct UsageInfo {
6536 UsageInfo() : Diagnosed(false) {}
6537 Usage Uses[UK_Count];
6538 /// Have we issued a diagnostic for this variable already?
6539 bool Diagnosed;
6540 };
6541 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6542
6543 Sema &SemaRef;
6544 /// Sequenced regions within the expression.
6545 SequenceTree Tree;
6546 /// Declaration modifications and references which we have seen.
6547 UsageInfoMap UsageMap;
6548 /// The region we are currently within.
6549 SequenceTree::Seq Region;
6550 /// Filled in with declarations which were modified as a side-effect
6551 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006552 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006553 /// Expressions to check later. We defer checking these to reduce
6554 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006555 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006556
6557 /// RAII object wrapping the visitation of a sequenced subexpression of an
6558 /// expression. At the end of this process, the side-effects of the evaluation
6559 /// become sequenced with respect to the value computation of the result, so
6560 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6561 /// UK_ModAsValue.
6562 struct SequencedSubexpression {
6563 SequencedSubexpression(SequenceChecker &Self)
6564 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6565 Self.ModAsSideEffect = &ModAsSideEffect;
6566 }
6567 ~SequencedSubexpression() {
6568 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6569 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6570 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6571 Self.addUsage(U, ModAsSideEffect[I].first,
6572 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6573 }
6574 Self.ModAsSideEffect = OldModAsSideEffect;
6575 }
6576
6577 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006578 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6579 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006580 };
6581
Richard Smith40238f02013-06-20 22:21:56 +00006582 /// RAII object wrapping the visitation of a subexpression which we might
6583 /// choose to evaluate as a constant. If any subexpression is evaluated and
6584 /// found to be non-constant, this allows us to suppress the evaluation of
6585 /// the outer expression.
6586 class EvaluationTracker {
6587 public:
6588 EvaluationTracker(SequenceChecker &Self)
6589 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6590 Self.EvalTracker = this;
6591 }
6592 ~EvaluationTracker() {
6593 Self.EvalTracker = Prev;
6594 if (Prev)
6595 Prev->EvalOK &= EvalOK;
6596 }
6597
6598 bool evaluate(const Expr *E, bool &Result) {
6599 if (!EvalOK || E->isValueDependent())
6600 return false;
6601 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6602 return EvalOK;
6603 }
6604
6605 private:
6606 SequenceChecker &Self;
6607 EvaluationTracker *Prev;
6608 bool EvalOK;
6609 } *EvalTracker;
6610
Richard Smithc406cb72013-01-17 01:17:56 +00006611 /// \brief Find the object which is produced by the specified expression,
6612 /// if any.
6613 Object getObject(Expr *E, bool Mod) const {
6614 E = E->IgnoreParenCasts();
6615 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6616 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6617 return getObject(UO->getSubExpr(), Mod);
6618 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6619 if (BO->getOpcode() == BO_Comma)
6620 return getObject(BO->getRHS(), Mod);
6621 if (Mod && BO->isAssignmentOp())
6622 return getObject(BO->getLHS(), Mod);
6623 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6624 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6625 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6626 return ME->getMemberDecl();
6627 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6628 // FIXME: If this is a reference, map through to its value.
6629 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006630 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006631 }
6632
6633 /// \brief Note that an object was modified or used by an expression.
6634 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6635 Usage &U = UI.Uses[UK];
6636 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6637 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6638 ModAsSideEffect->push_back(std::make_pair(O, U));
6639 U.Use = Ref;
6640 U.Seq = Region;
6641 }
6642 }
6643 /// \brief Check whether a modification or use conflicts with a prior usage.
6644 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6645 bool IsModMod) {
6646 if (UI.Diagnosed)
6647 return;
6648
6649 const Usage &U = UI.Uses[OtherKind];
6650 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6651 return;
6652
6653 Expr *Mod = U.Use;
6654 Expr *ModOrUse = Ref;
6655 if (OtherKind == UK_Use)
6656 std::swap(Mod, ModOrUse);
6657
6658 SemaRef.Diag(Mod->getExprLoc(),
6659 IsModMod ? diag::warn_unsequenced_mod_mod
6660 : diag::warn_unsequenced_mod_use)
6661 << O << SourceRange(ModOrUse->getExprLoc());
6662 UI.Diagnosed = true;
6663 }
6664
6665 void notePreUse(Object O, Expr *Use) {
6666 UsageInfo &U = UsageMap[O];
6667 // Uses conflict with other modifications.
6668 checkUsage(O, U, Use, UK_ModAsValue, false);
6669 }
6670 void notePostUse(Object O, Expr *Use) {
6671 UsageInfo &U = UsageMap[O];
6672 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6673 addUsage(U, O, Use, UK_Use);
6674 }
6675
6676 void notePreMod(Object O, Expr *Mod) {
6677 UsageInfo &U = UsageMap[O];
6678 // Modifications conflict with other modifications and with uses.
6679 checkUsage(O, U, Mod, UK_ModAsValue, true);
6680 checkUsage(O, U, Mod, UK_Use, false);
6681 }
6682 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6683 UsageInfo &U = UsageMap[O];
6684 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6685 addUsage(U, O, Use, UK);
6686 }
6687
6688public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006689 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006690 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6691 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006692 Visit(E);
6693 }
6694
6695 void VisitStmt(Stmt *S) {
6696 // Skip all statements which aren't expressions for now.
6697 }
6698
6699 void VisitExpr(Expr *E) {
6700 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006701 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006702 }
6703
6704 void VisitCastExpr(CastExpr *E) {
6705 Object O = Object();
6706 if (E->getCastKind() == CK_LValueToRValue)
6707 O = getObject(E->getSubExpr(), false);
6708
6709 if (O)
6710 notePreUse(O, E);
6711 VisitExpr(E);
6712 if (O)
6713 notePostUse(O, E);
6714 }
6715
6716 void VisitBinComma(BinaryOperator *BO) {
6717 // C++11 [expr.comma]p1:
6718 // Every value computation and side effect associated with the left
6719 // expression is sequenced before every value computation and side
6720 // effect associated with the right expression.
6721 SequenceTree::Seq LHS = Tree.allocate(Region);
6722 SequenceTree::Seq RHS = Tree.allocate(Region);
6723 SequenceTree::Seq OldRegion = Region;
6724
6725 {
6726 SequencedSubexpression SeqLHS(*this);
6727 Region = LHS;
6728 Visit(BO->getLHS());
6729 }
6730
6731 Region = RHS;
6732 Visit(BO->getRHS());
6733
6734 Region = OldRegion;
6735
6736 // Forget that LHS and RHS are sequenced. They are both unsequenced
6737 // with respect to other stuff.
6738 Tree.merge(LHS);
6739 Tree.merge(RHS);
6740 }
6741
6742 void VisitBinAssign(BinaryOperator *BO) {
6743 // The modification is sequenced after the value computation of the LHS
6744 // and RHS, so check it before inspecting the operands and update the
6745 // map afterwards.
6746 Object O = getObject(BO->getLHS(), true);
6747 if (!O)
6748 return VisitExpr(BO);
6749
6750 notePreMod(O, BO);
6751
6752 // C++11 [expr.ass]p7:
6753 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6754 // only once.
6755 //
6756 // Therefore, for a compound assignment operator, O is considered used
6757 // everywhere except within the evaluation of E1 itself.
6758 if (isa<CompoundAssignOperator>(BO))
6759 notePreUse(O, BO);
6760
6761 Visit(BO->getLHS());
6762
6763 if (isa<CompoundAssignOperator>(BO))
6764 notePostUse(O, BO);
6765
6766 Visit(BO->getRHS());
6767
Richard Smith83e37bee2013-06-26 23:16:51 +00006768 // C++11 [expr.ass]p1:
6769 // the assignment is sequenced [...] before the value computation of the
6770 // assignment expression.
6771 // C11 6.5.16/3 has no such rule.
6772 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6773 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006774 }
6775 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6776 VisitBinAssign(CAO);
6777 }
6778
6779 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6780 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6781 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6782 Object O = getObject(UO->getSubExpr(), true);
6783 if (!O)
6784 return VisitExpr(UO);
6785
6786 notePreMod(O, UO);
6787 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006788 // C++11 [expr.pre.incr]p1:
6789 // the expression ++x is equivalent to x+=1
6790 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6791 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006792 }
6793
6794 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6795 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6796 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6797 Object O = getObject(UO->getSubExpr(), true);
6798 if (!O)
6799 return VisitExpr(UO);
6800
6801 notePreMod(O, UO);
6802 Visit(UO->getSubExpr());
6803 notePostMod(O, UO, UK_ModAsSideEffect);
6804 }
6805
6806 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6807 void VisitBinLOr(BinaryOperator *BO) {
6808 // The side-effects of the LHS of an '&&' are sequenced before the
6809 // value computation of the RHS, and hence before the value computation
6810 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6811 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006812 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006813 {
6814 SequencedSubexpression Sequenced(*this);
6815 Visit(BO->getLHS());
6816 }
6817
6818 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006819 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006820 if (!Result)
6821 Visit(BO->getRHS());
6822 } else {
6823 // Check for unsequenced operations in the RHS, treating it as an
6824 // entirely separate evaluation.
6825 //
6826 // FIXME: If there are operations in the RHS which are unsequenced
6827 // with respect to operations outside the RHS, and those operations
6828 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006829 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006830 }
Richard Smithc406cb72013-01-17 01:17:56 +00006831 }
6832 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006833 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006834 {
6835 SequencedSubexpression Sequenced(*this);
6836 Visit(BO->getLHS());
6837 }
6838
6839 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006840 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006841 if (Result)
6842 Visit(BO->getRHS());
6843 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006844 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006845 }
Richard Smithc406cb72013-01-17 01:17:56 +00006846 }
6847
6848 // Only visit the condition, unless we can be sure which subexpression will
6849 // be chosen.
6850 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006851 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006852 {
6853 SequencedSubexpression Sequenced(*this);
6854 Visit(CO->getCond());
6855 }
Richard Smithc406cb72013-01-17 01:17:56 +00006856
6857 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006858 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006859 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006860 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006861 WorkList.push_back(CO->getTrueExpr());
6862 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006863 }
Richard Smithc406cb72013-01-17 01:17:56 +00006864 }
6865
Richard Smithe3dbfe02013-06-30 10:40:20 +00006866 void VisitCallExpr(CallExpr *CE) {
6867 // C++11 [intro.execution]p15:
6868 // When calling a function [...], every value computation and side effect
6869 // associated with any argument expression, or with the postfix expression
6870 // designating the called function, is sequenced before execution of every
6871 // expression or statement in the body of the function [and thus before
6872 // the value computation of its result].
6873 SequencedSubexpression Sequenced(*this);
6874 Base::VisitCallExpr(CE);
6875
6876 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6877 }
6878
Richard Smithc406cb72013-01-17 01:17:56 +00006879 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006880 // This is a call, so all subexpressions are sequenced before the result.
6881 SequencedSubexpression Sequenced(*this);
6882
Richard Smithc406cb72013-01-17 01:17:56 +00006883 if (!CCE->isListInitialization())
6884 return VisitExpr(CCE);
6885
6886 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006887 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006888 SequenceTree::Seq Parent = Region;
6889 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6890 E = CCE->arg_end();
6891 I != E; ++I) {
6892 Region = Tree.allocate(Parent);
6893 Elts.push_back(Region);
6894 Visit(*I);
6895 }
6896
6897 // Forget that the initializers are sequenced.
6898 Region = Parent;
6899 for (unsigned I = 0; I < Elts.size(); ++I)
6900 Tree.merge(Elts[I]);
6901 }
6902
6903 void VisitInitListExpr(InitListExpr *ILE) {
6904 if (!SemaRef.getLangOpts().CPlusPlus11)
6905 return VisitExpr(ILE);
6906
6907 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006908 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006909 SequenceTree::Seq Parent = Region;
6910 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6911 Expr *E = ILE->getInit(I);
6912 if (!E) continue;
6913 Region = Tree.allocate(Parent);
6914 Elts.push_back(Region);
6915 Visit(E);
6916 }
6917
6918 // Forget that the initializers are sequenced.
6919 Region = Parent;
6920 for (unsigned I = 0; I < Elts.size(); ++I)
6921 Tree.merge(Elts[I]);
6922 }
6923};
6924}
6925
6926void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006927 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006928 WorkList.push_back(E);
6929 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006930 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006931 SequenceChecker(*this, Item, WorkList);
6932 }
Richard Smithc406cb72013-01-17 01:17:56 +00006933}
6934
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006935void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6936 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006937 CheckImplicitConversions(E, CheckLoc);
6938 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006939 if (!IsConstexpr && !E->isValueDependent())
6940 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006941}
6942
John McCall1f425642010-11-11 03:21:53 +00006943void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6944 FieldDecl *BitField,
6945 Expr *Init) {
6946 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6947}
6948
Mike Stump0c2ec772010-01-21 03:59:47 +00006949/// CheckParmsForFunctionDef - Check that the parameters of the given
6950/// function are appropriate for the definition of a function. This
6951/// takes care of any checks that cannot be performed on the
6952/// declaration itself, e.g., that the types of each of the function
6953/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006954bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6955 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006956 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006957 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006958 for (; P != PEnd; ++P) {
6959 ParmVarDecl *Param = *P;
6960
Mike Stump0c2ec772010-01-21 03:59:47 +00006961 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6962 // function declarator that is part of a function definition of
6963 // that function shall not have incomplete type.
6964 //
6965 // This is also C++ [dcl.fct]p6.
6966 if (!Param->isInvalidDecl() &&
6967 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006968 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006969 Param->setInvalidDecl();
6970 HasInvalidParm = true;
6971 }
6972
6973 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6974 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006975 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00006976 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006977 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006978 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006979 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006980
6981 // C99 6.7.5.3p12:
6982 // If the function declarator is not part of a definition of that
6983 // function, parameters may have incomplete type and may use the [*]
6984 // notation in their sequences of declarator specifiers to specify
6985 // variable length array types.
6986 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006987 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006988 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006989 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006990 // information is added for it.
6991 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006992 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006993 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006994 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006995 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006996
6997 // MSVC destroys objects passed by value in the callee. Therefore a
6998 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006999 // object's destructor. However, we don't perform any direct access check
7000 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007001 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7002 .getCXXABI()
7003 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007004 if (!Param->isInvalidDecl()) {
7005 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7006 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7007 if (!ClassDecl->isInvalidDecl() &&
7008 !ClassDecl->hasIrrelevantDestructor() &&
7009 !ClassDecl->isDependentContext()) {
7010 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7011 MarkFunctionReferenced(Param->getLocation(), Destructor);
7012 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7013 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007014 }
7015 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007016 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007017 }
7018
7019 return HasInvalidParm;
7020}
John McCall2b5c1b22010-08-12 21:44:57 +00007021
7022/// CheckCastAlign - Implements -Wcast-align, which warns when a
7023/// pointer cast increases the alignment requirements.
7024void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7025 // This is actually a lot of work to potentially be doing on every
7026 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007027 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007028 return;
7029
7030 // Ignore dependent types.
7031 if (T->isDependentType() || Op->getType()->isDependentType())
7032 return;
7033
7034 // Require that the destination be a pointer type.
7035 const PointerType *DestPtr = T->getAs<PointerType>();
7036 if (!DestPtr) return;
7037
7038 // If the destination has alignment 1, we're done.
7039 QualType DestPointee = DestPtr->getPointeeType();
7040 if (DestPointee->isIncompleteType()) return;
7041 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7042 if (DestAlign.isOne()) return;
7043
7044 // Require that the source be a pointer type.
7045 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7046 if (!SrcPtr) return;
7047 QualType SrcPointee = SrcPtr->getPointeeType();
7048
7049 // Whitelist casts from cv void*. We already implicitly
7050 // whitelisted casts to cv void*, since they have alignment 1.
7051 // Also whitelist casts involving incomplete types, which implicitly
7052 // includes 'void'.
7053 if (SrcPointee->isIncompleteType()) return;
7054
7055 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7056 if (SrcAlign >= DestAlign) return;
7057
7058 Diag(TRange.getBegin(), diag::warn_cast_align)
7059 << Op->getType() << T
7060 << static_cast<unsigned>(SrcAlign.getQuantity())
7061 << static_cast<unsigned>(DestAlign.getQuantity())
7062 << TRange << Op->getSourceRange();
7063}
7064
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007065static const Type* getElementType(const Expr *BaseExpr) {
7066 const Type* EltType = BaseExpr->getType().getTypePtr();
7067 if (EltType->isAnyPointerType())
7068 return EltType->getPointeeType().getTypePtr();
7069 else if (EltType->isArrayType())
7070 return EltType->getBaseElementTypeUnsafe();
7071 return EltType;
7072}
7073
Chandler Carruth28389f02011-08-05 09:10:50 +00007074/// \brief Check whether this array fits the idiom of a size-one tail padded
7075/// array member of a struct.
7076///
7077/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7078/// commonly used to emulate flexible arrays in C89 code.
7079static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7080 const NamedDecl *ND) {
7081 if (Size != 1 || !ND) return false;
7082
7083 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7084 if (!FD) return false;
7085
7086 // Don't consider sizes resulting from macro expansions or template argument
7087 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007088
7089 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007090 while (TInfo) {
7091 TypeLoc TL = TInfo->getTypeLoc();
7092 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007093 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7094 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007095 TInfo = TDL->getTypeSourceInfo();
7096 continue;
7097 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007098 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7099 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007100 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7101 return false;
7102 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007103 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007104 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007105
7106 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007107 if (!RD) return false;
7108 if (RD->isUnion()) return false;
7109 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7110 if (!CRD->isStandardLayout()) return false;
7111 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007112
Benjamin Kramer8c543672011-08-06 03:04:42 +00007113 // See if this is the last field decl in the record.
7114 const Decl *D = FD;
7115 while ((D = D->getNextDeclInContext()))
7116 if (isa<FieldDecl>(D))
7117 return false;
7118 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007119}
7120
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007121void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007122 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007123 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007124 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007125 if (IndexExpr->isValueDependent())
7126 return;
7127
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007128 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007129 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007130 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007131 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007132 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007133 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007134
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007135 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007136 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007137 return;
Richard Smith13f67182011-12-16 19:31:14 +00007138 if (IndexNegated)
7139 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007140
Craig Topperc3ec1492014-05-26 06:22:03 +00007141 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007142 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7143 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007144 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007145 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007146
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007147 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007148 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007149 if (!size.isStrictlyPositive())
7150 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007151
7152 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007153 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007154 // Make sure we're comparing apples to apples when comparing index to size
7155 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7156 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007157 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007158 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007159 if (ptrarith_typesize != array_typesize) {
7160 // There's a cast to a different size type involved
7161 uint64_t ratio = array_typesize / ptrarith_typesize;
7162 // TODO: Be smarter about handling cases where array_typesize is not a
7163 // multiple of ptrarith_typesize
7164 if (ptrarith_typesize * ratio == array_typesize)
7165 size *= llvm::APInt(size.getBitWidth(), ratio);
7166 }
7167 }
7168
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007169 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007170 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007171 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007172 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007173
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007174 // For array subscripting the index must be less than size, but for pointer
7175 // arithmetic also allow the index (offset) to be equal to size since
7176 // computing the next address after the end of the array is legal and
7177 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007178 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007179 return;
7180
7181 // Also don't warn for arrays of size 1 which are members of some
7182 // structure. These are often used to approximate flexible arrays in C89
7183 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007184 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007185 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007186
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007187 // Suppress the warning if the subscript expression (as identified by the
7188 // ']' location) and the index expression are both from macro expansions
7189 // within a system header.
7190 if (ASE) {
7191 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7192 ASE->getRBracketLoc());
7193 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7194 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7195 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007196 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007197 return;
7198 }
7199 }
7200
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007201 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007202 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007203 DiagID = diag::warn_array_index_exceeds_bounds;
7204
7205 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7206 PDiag(DiagID) << index.toString(10, true)
7207 << size.toString(10, true)
7208 << (unsigned)size.getLimitedValue(~0U)
7209 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007210 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007211 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007212 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007213 DiagID = diag::warn_ptr_arith_precedes_bounds;
7214 if (index.isNegative()) index = -index;
7215 }
7216
7217 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7218 PDiag(DiagID) << index.toString(10, true)
7219 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007220 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007221
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007222 if (!ND) {
7223 // Try harder to find a NamedDecl to point at in the note.
7224 while (const ArraySubscriptExpr *ASE =
7225 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7226 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7227 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7228 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7229 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7230 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7231 }
7232
Chandler Carruth1af88f12011-02-17 21:10:52 +00007233 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007234 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7235 PDiag(diag::note_array_index_out_of_bounds)
7236 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007237}
7238
Ted Kremenekdf26df72011-03-01 18:41:00 +00007239void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007240 int AllowOnePastEnd = 0;
7241 while (expr) {
7242 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007243 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007244 case Stmt::ArraySubscriptExprClass: {
7245 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007246 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007247 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007248 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007249 }
7250 case Stmt::UnaryOperatorClass: {
7251 // Only unwrap the * and & unary operators
7252 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7253 expr = UO->getSubExpr();
7254 switch (UO->getOpcode()) {
7255 case UO_AddrOf:
7256 AllowOnePastEnd++;
7257 break;
7258 case UO_Deref:
7259 AllowOnePastEnd--;
7260 break;
7261 default:
7262 return;
7263 }
7264 break;
7265 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007266 case Stmt::ConditionalOperatorClass: {
7267 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7268 if (const Expr *lhs = cond->getLHS())
7269 CheckArrayAccess(lhs);
7270 if (const Expr *rhs = cond->getRHS())
7271 CheckArrayAccess(rhs);
7272 return;
7273 }
7274 default:
7275 return;
7276 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007277 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007278}
John McCall31168b02011-06-15 23:02:42 +00007279
7280//===--- CHECK: Objective-C retain cycles ----------------------------------//
7281
7282namespace {
7283 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007284 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007285 VarDecl *Variable;
7286 SourceRange Range;
7287 SourceLocation Loc;
7288 bool Indirect;
7289
7290 void setLocsFrom(Expr *e) {
7291 Loc = e->getExprLoc();
7292 Range = e->getSourceRange();
7293 }
7294 };
7295}
7296
7297/// Consider whether capturing the given variable can possibly lead to
7298/// a retain cycle.
7299static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007300 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007301 // lifetime. In MRR, it's captured strongly if the variable is
7302 // __block and has an appropriate type.
7303 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7304 return false;
7305
7306 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007307 if (ref)
7308 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007309 return true;
7310}
7311
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007312static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007313 while (true) {
7314 e = e->IgnoreParens();
7315 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7316 switch (cast->getCastKind()) {
7317 case CK_BitCast:
7318 case CK_LValueBitCast:
7319 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007320 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007321 e = cast->getSubExpr();
7322 continue;
7323
John McCall31168b02011-06-15 23:02:42 +00007324 default:
7325 return false;
7326 }
7327 }
7328
7329 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7330 ObjCIvarDecl *ivar = ref->getDecl();
7331 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7332 return false;
7333
7334 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007335 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007336 return false;
7337
7338 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7339 owner.Indirect = true;
7340 return true;
7341 }
7342
7343 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7344 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7345 if (!var) return false;
7346 return considerVariable(var, ref, owner);
7347 }
7348
John McCall31168b02011-06-15 23:02:42 +00007349 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7350 if (member->isArrow()) return false;
7351
7352 // Don't count this as an indirect ownership.
7353 e = member->getBase();
7354 continue;
7355 }
7356
John McCallfe96e0b2011-11-06 09:01:30 +00007357 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7358 // Only pay attention to pseudo-objects on property references.
7359 ObjCPropertyRefExpr *pre
7360 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7361 ->IgnoreParens());
7362 if (!pre) return false;
7363 if (pre->isImplicitProperty()) return false;
7364 ObjCPropertyDecl *property = pre->getExplicitProperty();
7365 if (!property->isRetaining() &&
7366 !(property->getPropertyIvarDecl() &&
7367 property->getPropertyIvarDecl()->getType()
7368 .getObjCLifetime() == Qualifiers::OCL_Strong))
7369 return false;
7370
7371 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007372 if (pre->isSuperReceiver()) {
7373 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7374 if (!owner.Variable)
7375 return false;
7376 owner.Loc = pre->getLocation();
7377 owner.Range = pre->getSourceRange();
7378 return true;
7379 }
John McCallfe96e0b2011-11-06 09:01:30 +00007380 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7381 ->getSourceExpr());
7382 continue;
7383 }
7384
John McCall31168b02011-06-15 23:02:42 +00007385 // Array ivars?
7386
7387 return false;
7388 }
7389}
7390
7391namespace {
7392 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7393 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7394 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007395 Context(Context), Variable(variable), Capturer(nullptr),
7396 VarWillBeReased(false) {}
7397 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007398 VarDecl *Variable;
7399 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007400 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007401
7402 void VisitDeclRefExpr(DeclRefExpr *ref) {
7403 if (ref->getDecl() == Variable && !Capturer)
7404 Capturer = ref;
7405 }
7406
John McCall31168b02011-06-15 23:02:42 +00007407 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7408 if (Capturer) return;
7409 Visit(ref->getBase());
7410 if (Capturer && ref->isFreeIvar())
7411 Capturer = ref;
7412 }
7413
7414 void VisitBlockExpr(BlockExpr *block) {
7415 // Look inside nested blocks
7416 if (block->getBlockDecl()->capturesVariable(Variable))
7417 Visit(block->getBlockDecl()->getBody());
7418 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007419
7420 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7421 if (Capturer) return;
7422 if (OVE->getSourceExpr())
7423 Visit(OVE->getSourceExpr());
7424 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007425 void VisitBinaryOperator(BinaryOperator *BinOp) {
7426 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7427 return;
7428 Expr *LHS = BinOp->getLHS();
7429 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7430 if (DRE->getDecl() != Variable)
7431 return;
7432 if (Expr *RHS = BinOp->getRHS()) {
7433 RHS = RHS->IgnoreParenCasts();
7434 llvm::APSInt Value;
7435 VarWillBeReased =
7436 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7437 }
7438 }
7439 }
John McCall31168b02011-06-15 23:02:42 +00007440 };
7441}
7442
7443/// Check whether the given argument is a block which captures a
7444/// variable.
7445static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7446 assert(owner.Variable && owner.Loc.isValid());
7447
7448 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007449
7450 // Look through [^{...} copy] and Block_copy(^{...}).
7451 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7452 Selector Cmd = ME->getSelector();
7453 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7454 e = ME->getInstanceReceiver();
7455 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007456 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007457 e = e->IgnoreParenCasts();
7458 }
7459 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7460 if (CE->getNumArgs() == 1) {
7461 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007462 if (Fn) {
7463 const IdentifierInfo *FnI = Fn->getIdentifier();
7464 if (FnI && FnI->isStr("_Block_copy")) {
7465 e = CE->getArg(0)->IgnoreParenCasts();
7466 }
7467 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007468 }
7469 }
7470
John McCall31168b02011-06-15 23:02:42 +00007471 BlockExpr *block = dyn_cast<BlockExpr>(e);
7472 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007473 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007474
7475 FindCaptureVisitor visitor(S.Context, owner.Variable);
7476 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007477 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007478}
7479
7480static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7481 RetainCycleOwner &owner) {
7482 assert(capturer);
7483 assert(owner.Variable && owner.Loc.isValid());
7484
7485 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7486 << owner.Variable << capturer->getSourceRange();
7487 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7488 << owner.Indirect << owner.Range;
7489}
7490
7491/// Check for a keyword selector that starts with the word 'add' or
7492/// 'set'.
7493static bool isSetterLikeSelector(Selector sel) {
7494 if (sel.isUnarySelector()) return false;
7495
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007496 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007497 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007498 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007499 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007500 else if (str.startswith("add")) {
7501 // Specially whitelist 'addOperationWithBlock:'.
7502 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7503 return false;
7504 str = str.substr(3);
7505 }
John McCall31168b02011-06-15 23:02:42 +00007506 else
7507 return false;
7508
7509 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007510 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007511}
7512
7513/// Check a message send to see if it's likely to cause a retain cycle.
7514void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7515 // Only check instance methods whose selector looks like a setter.
7516 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7517 return;
7518
7519 // Try to find a variable that the receiver is strongly owned by.
7520 RetainCycleOwner owner;
7521 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007522 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007523 return;
7524 } else {
7525 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7526 owner.Variable = getCurMethodDecl()->getSelfDecl();
7527 owner.Loc = msg->getSuperLoc();
7528 owner.Range = msg->getSuperLoc();
7529 }
7530
7531 // Check whether the receiver is captured by any of the arguments.
7532 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7533 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7534 return diagnoseRetainCycle(*this, capturer, owner);
7535}
7536
7537/// Check a property assign to see if it's likely to cause a retain cycle.
7538void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7539 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007540 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007541 return;
7542
7543 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7544 diagnoseRetainCycle(*this, capturer, owner);
7545}
7546
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007547void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7548 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007549 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007550 return;
7551
7552 // Because we don't have an expression for the variable, we have to set the
7553 // location explicitly here.
7554 Owner.Loc = Var->getLocation();
7555 Owner.Range = Var->getSourceRange();
7556
7557 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7558 diagnoseRetainCycle(*this, Capturer, Owner);
7559}
7560
Ted Kremenek9304da92012-12-21 08:04:28 +00007561static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7562 Expr *RHS, bool isProperty) {
7563 // Check if RHS is an Objective-C object literal, which also can get
7564 // immediately zapped in a weak reference. Note that we explicitly
7565 // allow ObjCStringLiterals, since those are designed to never really die.
7566 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007567
Ted Kremenek64873352012-12-21 22:46:35 +00007568 // This enum needs to match with the 'select' in
7569 // warn_objc_arc_literal_assign (off-by-1).
7570 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7571 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7572 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007573
7574 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007575 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007576 << (isProperty ? 0 : 1)
7577 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007578
7579 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007580}
7581
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007582static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7583 Qualifiers::ObjCLifetime LT,
7584 Expr *RHS, bool isProperty) {
7585 // Strip off any implicit cast added to get to the one ARC-specific.
7586 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7587 if (cast->getCastKind() == CK_ARCConsumeObject) {
7588 S.Diag(Loc, diag::warn_arc_retained_assign)
7589 << (LT == Qualifiers::OCL_ExplicitNone)
7590 << (isProperty ? 0 : 1)
7591 << RHS->getSourceRange();
7592 return true;
7593 }
7594 RHS = cast->getSubExpr();
7595 }
7596
7597 if (LT == Qualifiers::OCL_Weak &&
7598 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7599 return true;
7600
7601 return false;
7602}
7603
Ted Kremenekb36234d2012-12-21 08:04:20 +00007604bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7605 QualType LHS, Expr *RHS) {
7606 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7607
7608 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7609 return false;
7610
7611 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7612 return true;
7613
7614 return false;
7615}
7616
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007617void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7618 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007619 QualType LHSType;
7620 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007621 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007622 ObjCPropertyRefExpr *PRE
7623 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7624 if (PRE && !PRE->isImplicitProperty()) {
7625 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7626 if (PD)
7627 LHSType = PD->getType();
7628 }
7629
7630 if (LHSType.isNull())
7631 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007632
7633 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7634
7635 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007636 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007637 getCurFunction()->markSafeWeakUse(LHS);
7638 }
7639
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007640 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7641 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007642
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007643 // FIXME. Check for other life times.
7644 if (LT != Qualifiers::OCL_None)
7645 return;
7646
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007647 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007648 if (PRE->isImplicitProperty())
7649 return;
7650 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7651 if (!PD)
7652 return;
7653
Bill Wendling44426052012-12-20 19:22:21 +00007654 unsigned Attributes = PD->getPropertyAttributes();
7655 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007656 // when 'assign' attribute was not explicitly specified
7657 // by user, ignore it and rely on property type itself
7658 // for lifetime info.
7659 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7660 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7661 LHSType->isObjCRetainableType())
7662 return;
7663
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007664 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007665 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007666 Diag(Loc, diag::warn_arc_retained_property_assign)
7667 << RHS->getSourceRange();
7668 return;
7669 }
7670 RHS = cast->getSubExpr();
7671 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007672 }
Bill Wendling44426052012-12-20 19:22:21 +00007673 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007674 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7675 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007676 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007677 }
7678}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007679
7680//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7681
7682namespace {
7683bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7684 SourceLocation StmtLoc,
7685 const NullStmt *Body) {
7686 // Do not warn if the body is a macro that expands to nothing, e.g:
7687 //
7688 // #define CALL(x)
7689 // if (condition)
7690 // CALL(0);
7691 //
7692 if (Body->hasLeadingEmptyMacro())
7693 return false;
7694
7695 // Get line numbers of statement and body.
7696 bool StmtLineInvalid;
7697 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7698 &StmtLineInvalid);
7699 if (StmtLineInvalid)
7700 return false;
7701
7702 bool BodyLineInvalid;
7703 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7704 &BodyLineInvalid);
7705 if (BodyLineInvalid)
7706 return false;
7707
7708 // Warn if null statement and body are on the same line.
7709 if (StmtLine != BodyLine)
7710 return false;
7711
7712 return true;
7713}
7714} // Unnamed namespace
7715
7716void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7717 const Stmt *Body,
7718 unsigned DiagID) {
7719 // Since this is a syntactic check, don't emit diagnostic for template
7720 // instantiations, this just adds noise.
7721 if (CurrentInstantiationScope)
7722 return;
7723
7724 // The body should be a null statement.
7725 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7726 if (!NBody)
7727 return;
7728
7729 // Do the usual checks.
7730 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7731 return;
7732
7733 Diag(NBody->getSemiLoc(), DiagID);
7734 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7735}
7736
7737void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7738 const Stmt *PossibleBody) {
7739 assert(!CurrentInstantiationScope); // Ensured by caller
7740
7741 SourceLocation StmtLoc;
7742 const Stmt *Body;
7743 unsigned DiagID;
7744 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7745 StmtLoc = FS->getRParenLoc();
7746 Body = FS->getBody();
7747 DiagID = diag::warn_empty_for_body;
7748 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7749 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7750 Body = WS->getBody();
7751 DiagID = diag::warn_empty_while_body;
7752 } else
7753 return; // Neither `for' nor `while'.
7754
7755 // The body should be a null statement.
7756 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7757 if (!NBody)
7758 return;
7759
7760 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007761 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007762 return;
7763
7764 // Do the usual checks.
7765 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7766 return;
7767
7768 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7769 // noise level low, emit diagnostics only if for/while is followed by a
7770 // CompoundStmt, e.g.:
7771 // for (int i = 0; i < n; i++);
7772 // {
7773 // a(i);
7774 // }
7775 // or if for/while is followed by a statement with more indentation
7776 // than for/while itself:
7777 // for (int i = 0; i < n; i++);
7778 // a(i);
7779 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7780 if (!ProbableTypo) {
7781 bool BodyColInvalid;
7782 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7783 PossibleBody->getLocStart(),
7784 &BodyColInvalid);
7785 if (BodyColInvalid)
7786 return;
7787
7788 bool StmtColInvalid;
7789 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7790 S->getLocStart(),
7791 &StmtColInvalid);
7792 if (StmtColInvalid)
7793 return;
7794
7795 if (BodyCol > StmtCol)
7796 ProbableTypo = true;
7797 }
7798
7799 if (ProbableTypo) {
7800 Diag(NBody->getSemiLoc(), DiagID);
7801 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7802 }
7803}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007804
7805//===--- Layout compatibility ----------------------------------------------//
7806
7807namespace {
7808
7809bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7810
7811/// \brief Check if two enumeration types are layout-compatible.
7812bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7813 // C++11 [dcl.enum] p8:
7814 // Two enumeration types are layout-compatible if they have the same
7815 // underlying type.
7816 return ED1->isComplete() && ED2->isComplete() &&
7817 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7818}
7819
7820/// \brief Check if two fields are layout-compatible.
7821bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7822 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7823 return false;
7824
7825 if (Field1->isBitField() != Field2->isBitField())
7826 return false;
7827
7828 if (Field1->isBitField()) {
7829 // Make sure that the bit-fields are the same length.
7830 unsigned Bits1 = Field1->getBitWidthValue(C);
7831 unsigned Bits2 = Field2->getBitWidthValue(C);
7832
7833 if (Bits1 != Bits2)
7834 return false;
7835 }
7836
7837 return true;
7838}
7839
7840/// \brief Check if two standard-layout structs are layout-compatible.
7841/// (C++11 [class.mem] p17)
7842bool isLayoutCompatibleStruct(ASTContext &C,
7843 RecordDecl *RD1,
7844 RecordDecl *RD2) {
7845 // If both records are C++ classes, check that base classes match.
7846 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7847 // If one of records is a CXXRecordDecl we are in C++ mode,
7848 // thus the other one is a CXXRecordDecl, too.
7849 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7850 // Check number of base classes.
7851 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7852 return false;
7853
7854 // Check the base classes.
7855 for (CXXRecordDecl::base_class_const_iterator
7856 Base1 = D1CXX->bases_begin(),
7857 BaseEnd1 = D1CXX->bases_end(),
7858 Base2 = D2CXX->bases_begin();
7859 Base1 != BaseEnd1;
7860 ++Base1, ++Base2) {
7861 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7862 return false;
7863 }
7864 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7865 // If only RD2 is a C++ class, it should have zero base classes.
7866 if (D2CXX->getNumBases() > 0)
7867 return false;
7868 }
7869
7870 // Check the fields.
7871 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7872 Field2End = RD2->field_end(),
7873 Field1 = RD1->field_begin(),
7874 Field1End = RD1->field_end();
7875 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7876 if (!isLayoutCompatible(C, *Field1, *Field2))
7877 return false;
7878 }
7879 if (Field1 != Field1End || Field2 != Field2End)
7880 return false;
7881
7882 return true;
7883}
7884
7885/// \brief Check if two standard-layout unions are layout-compatible.
7886/// (C++11 [class.mem] p18)
7887bool isLayoutCompatibleUnion(ASTContext &C,
7888 RecordDecl *RD1,
7889 RecordDecl *RD2) {
7890 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007891 for (auto *Field2 : RD2->fields())
7892 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007893
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007894 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007895 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7896 I = UnmatchedFields.begin(),
7897 E = UnmatchedFields.end();
7898
7899 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007900 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007901 bool Result = UnmatchedFields.erase(*I);
7902 (void) Result;
7903 assert(Result);
7904 break;
7905 }
7906 }
7907 if (I == E)
7908 return false;
7909 }
7910
7911 return UnmatchedFields.empty();
7912}
7913
7914bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7915 if (RD1->isUnion() != RD2->isUnion())
7916 return false;
7917
7918 if (RD1->isUnion())
7919 return isLayoutCompatibleUnion(C, RD1, RD2);
7920 else
7921 return isLayoutCompatibleStruct(C, RD1, RD2);
7922}
7923
7924/// \brief Check if two types are layout-compatible in C++11 sense.
7925bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7926 if (T1.isNull() || T2.isNull())
7927 return false;
7928
7929 // C++11 [basic.types] p11:
7930 // If two types T1 and T2 are the same type, then T1 and T2 are
7931 // layout-compatible types.
7932 if (C.hasSameType(T1, T2))
7933 return true;
7934
7935 T1 = T1.getCanonicalType().getUnqualifiedType();
7936 T2 = T2.getCanonicalType().getUnqualifiedType();
7937
7938 const Type::TypeClass TC1 = T1->getTypeClass();
7939 const Type::TypeClass TC2 = T2->getTypeClass();
7940
7941 if (TC1 != TC2)
7942 return false;
7943
7944 if (TC1 == Type::Enum) {
7945 return isLayoutCompatible(C,
7946 cast<EnumType>(T1)->getDecl(),
7947 cast<EnumType>(T2)->getDecl());
7948 } else if (TC1 == Type::Record) {
7949 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7950 return false;
7951
7952 return isLayoutCompatible(C,
7953 cast<RecordType>(T1)->getDecl(),
7954 cast<RecordType>(T2)->getDecl());
7955 }
7956
7957 return false;
7958}
7959}
7960
7961//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7962
7963namespace {
7964/// \brief Given a type tag expression find the type tag itself.
7965///
7966/// \param TypeExpr Type tag expression, as it appears in user's code.
7967///
7968/// \param VD Declaration of an identifier that appears in a type tag.
7969///
7970/// \param MagicValue Type tag magic value.
7971bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7972 const ValueDecl **VD, uint64_t *MagicValue) {
7973 while(true) {
7974 if (!TypeExpr)
7975 return false;
7976
7977 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7978
7979 switch (TypeExpr->getStmtClass()) {
7980 case Stmt::UnaryOperatorClass: {
7981 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7982 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7983 TypeExpr = UO->getSubExpr();
7984 continue;
7985 }
7986 return false;
7987 }
7988
7989 case Stmt::DeclRefExprClass: {
7990 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7991 *VD = DRE->getDecl();
7992 return true;
7993 }
7994
7995 case Stmt::IntegerLiteralClass: {
7996 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7997 llvm::APInt MagicValueAPInt = IL->getValue();
7998 if (MagicValueAPInt.getActiveBits() <= 64) {
7999 *MagicValue = MagicValueAPInt.getZExtValue();
8000 return true;
8001 } else
8002 return false;
8003 }
8004
8005 case Stmt::BinaryConditionalOperatorClass:
8006 case Stmt::ConditionalOperatorClass: {
8007 const AbstractConditionalOperator *ACO =
8008 cast<AbstractConditionalOperator>(TypeExpr);
8009 bool Result;
8010 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8011 if (Result)
8012 TypeExpr = ACO->getTrueExpr();
8013 else
8014 TypeExpr = ACO->getFalseExpr();
8015 continue;
8016 }
8017 return false;
8018 }
8019
8020 case Stmt::BinaryOperatorClass: {
8021 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8022 if (BO->getOpcode() == BO_Comma) {
8023 TypeExpr = BO->getRHS();
8024 continue;
8025 }
8026 return false;
8027 }
8028
8029 default:
8030 return false;
8031 }
8032 }
8033}
8034
8035/// \brief Retrieve the C type corresponding to type tag TypeExpr.
8036///
8037/// \param TypeExpr Expression that specifies a type tag.
8038///
8039/// \param MagicValues Registered magic values.
8040///
8041/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8042/// kind.
8043///
8044/// \param TypeInfo Information about the corresponding C type.
8045///
8046/// \returns true if the corresponding C type was found.
8047bool GetMatchingCType(
8048 const IdentifierInfo *ArgumentKind,
8049 const Expr *TypeExpr, const ASTContext &Ctx,
8050 const llvm::DenseMap<Sema::TypeTagMagicValue,
8051 Sema::TypeTagData> *MagicValues,
8052 bool &FoundWrongKind,
8053 Sema::TypeTagData &TypeInfo) {
8054 FoundWrongKind = false;
8055
8056 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00008057 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008058
8059 uint64_t MagicValue;
8060
8061 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8062 return false;
8063
8064 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00008065 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008066 if (I->getArgumentKind() != ArgumentKind) {
8067 FoundWrongKind = true;
8068 return false;
8069 }
8070 TypeInfo.Type = I->getMatchingCType();
8071 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8072 TypeInfo.MustBeNull = I->getMustBeNull();
8073 return true;
8074 }
8075 return false;
8076 }
8077
8078 if (!MagicValues)
8079 return false;
8080
8081 llvm::DenseMap<Sema::TypeTagMagicValue,
8082 Sema::TypeTagData>::const_iterator I =
8083 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8084 if (I == MagicValues->end())
8085 return false;
8086
8087 TypeInfo = I->second;
8088 return true;
8089}
8090} // unnamed namespace
8091
8092void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8093 uint64_t MagicValue, QualType Type,
8094 bool LayoutCompatible,
8095 bool MustBeNull) {
8096 if (!TypeTagForDatatypeMagicValues)
8097 TypeTagForDatatypeMagicValues.reset(
8098 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8099
8100 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8101 (*TypeTagForDatatypeMagicValues)[Magic] =
8102 TypeTagData(Type, LayoutCompatible, MustBeNull);
8103}
8104
8105namespace {
8106bool IsSameCharType(QualType T1, QualType T2) {
8107 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8108 if (!BT1)
8109 return false;
8110
8111 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8112 if (!BT2)
8113 return false;
8114
8115 BuiltinType::Kind T1Kind = BT1->getKind();
8116 BuiltinType::Kind T2Kind = BT2->getKind();
8117
8118 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8119 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8120 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8121 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8122}
8123} // unnamed namespace
8124
8125void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8126 const Expr * const *ExprArgs) {
8127 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8128 bool IsPointerAttr = Attr->getIsPointer();
8129
8130 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8131 bool FoundWrongKind;
8132 TypeTagData TypeInfo;
8133 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8134 TypeTagForDatatypeMagicValues.get(),
8135 FoundWrongKind, TypeInfo)) {
8136 if (FoundWrongKind)
8137 Diag(TypeTagExpr->getExprLoc(),
8138 diag::warn_type_tag_for_datatype_wrong_kind)
8139 << TypeTagExpr->getSourceRange();
8140 return;
8141 }
8142
8143 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8144 if (IsPointerAttr) {
8145 // Skip implicit cast of pointer to `void *' (as a function argument).
8146 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008147 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008148 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008149 ArgumentExpr = ICE->getSubExpr();
8150 }
8151 QualType ArgumentType = ArgumentExpr->getType();
8152
8153 // Passing a `void*' pointer shouldn't trigger a warning.
8154 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8155 return;
8156
8157 if (TypeInfo.MustBeNull) {
8158 // Type tag with matching void type requires a null pointer.
8159 if (!ArgumentExpr->isNullPointerConstant(Context,
8160 Expr::NPC_ValueDependentIsNotNull)) {
8161 Diag(ArgumentExpr->getExprLoc(),
8162 diag::warn_type_safety_null_pointer_required)
8163 << ArgumentKind->getName()
8164 << ArgumentExpr->getSourceRange()
8165 << TypeTagExpr->getSourceRange();
8166 }
8167 return;
8168 }
8169
8170 QualType RequiredType = TypeInfo.Type;
8171 if (IsPointerAttr)
8172 RequiredType = Context.getPointerType(RequiredType);
8173
8174 bool mismatch = false;
8175 if (!TypeInfo.LayoutCompatible) {
8176 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8177
8178 // C++11 [basic.fundamental] p1:
8179 // Plain char, signed char, and unsigned char are three distinct types.
8180 //
8181 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8182 // char' depending on the current char signedness mode.
8183 if (mismatch)
8184 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8185 RequiredType->getPointeeType())) ||
8186 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8187 mismatch = false;
8188 } else
8189 if (IsPointerAttr)
8190 mismatch = !isLayoutCompatible(Context,
8191 ArgumentType->getPointeeType(),
8192 RequiredType->getPointeeType());
8193 else
8194 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8195
8196 if (mismatch)
8197 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008198 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008199 << TypeInfo.LayoutCompatible << RequiredType
8200 << ArgumentExpr->getSourceRange()
8201 << TypeTagExpr->getSourceRange();
8202}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008203