blob: 72d3b2761d817fafb66cab3807e03ff5b33f83d3 [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;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000178 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000179 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000180 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000181 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000182 case Builtin::BI__builtin_longjmp:
183 if (SemaBuiltinLongjmp(TheCall))
184 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000185 break;
John McCallbebede42011-02-26 05:39:39 +0000186
187 case Builtin::BI__builtin_classify_type:
188 if (checkArgCount(*this, TheCall, 1)) return true;
189 TheCall->setType(Context.IntTy);
190 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000191 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000192 if (checkArgCount(*this, TheCall, 1)) return true;
193 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000194 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000195 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000196 case Builtin::BI__sync_fetch_and_add_1:
197 case Builtin::BI__sync_fetch_and_add_2:
198 case Builtin::BI__sync_fetch_and_add_4:
199 case Builtin::BI__sync_fetch_and_add_8:
200 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000201 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000202 case Builtin::BI__sync_fetch_and_sub_1:
203 case Builtin::BI__sync_fetch_and_sub_2:
204 case Builtin::BI__sync_fetch_and_sub_4:
205 case Builtin::BI__sync_fetch_and_sub_8:
206 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000207 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000208 case Builtin::BI__sync_fetch_and_or_1:
209 case Builtin::BI__sync_fetch_and_or_2:
210 case Builtin::BI__sync_fetch_and_or_4:
211 case Builtin::BI__sync_fetch_and_or_8:
212 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000213 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000214 case Builtin::BI__sync_fetch_and_and_1:
215 case Builtin::BI__sync_fetch_and_and_2:
216 case Builtin::BI__sync_fetch_and_and_4:
217 case Builtin::BI__sync_fetch_and_and_8:
218 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000219 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000220 case Builtin::BI__sync_fetch_and_xor_1:
221 case Builtin::BI__sync_fetch_and_xor_2:
222 case Builtin::BI__sync_fetch_and_xor_4:
223 case Builtin::BI__sync_fetch_and_xor_8:
224 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000225 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000226 case Builtin::BI__sync_add_and_fetch_1:
227 case Builtin::BI__sync_add_and_fetch_2:
228 case Builtin::BI__sync_add_and_fetch_4:
229 case Builtin::BI__sync_add_and_fetch_8:
230 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000231 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000232 case Builtin::BI__sync_sub_and_fetch_1:
233 case Builtin::BI__sync_sub_and_fetch_2:
234 case Builtin::BI__sync_sub_and_fetch_4:
235 case Builtin::BI__sync_sub_and_fetch_8:
236 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000237 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000238 case Builtin::BI__sync_and_and_fetch_1:
239 case Builtin::BI__sync_and_and_fetch_2:
240 case Builtin::BI__sync_and_and_fetch_4:
241 case Builtin::BI__sync_and_and_fetch_8:
242 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000243 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000244 case Builtin::BI__sync_or_and_fetch_1:
245 case Builtin::BI__sync_or_and_fetch_2:
246 case Builtin::BI__sync_or_and_fetch_4:
247 case Builtin::BI__sync_or_and_fetch_8:
248 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000249 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000250 case Builtin::BI__sync_xor_and_fetch_1:
251 case Builtin::BI__sync_xor_and_fetch_2:
252 case Builtin::BI__sync_xor_and_fetch_4:
253 case Builtin::BI__sync_xor_and_fetch_8:
254 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000255 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000256 case Builtin::BI__sync_val_compare_and_swap_1:
257 case Builtin::BI__sync_val_compare_and_swap_2:
258 case Builtin::BI__sync_val_compare_and_swap_4:
259 case Builtin::BI__sync_val_compare_and_swap_8:
260 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000261 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000262 case Builtin::BI__sync_bool_compare_and_swap_1:
263 case Builtin::BI__sync_bool_compare_and_swap_2:
264 case Builtin::BI__sync_bool_compare_and_swap_4:
265 case Builtin::BI__sync_bool_compare_and_swap_8:
266 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000267 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000268 case Builtin::BI__sync_lock_test_and_set_1:
269 case Builtin::BI__sync_lock_test_and_set_2:
270 case Builtin::BI__sync_lock_test_and_set_4:
271 case Builtin::BI__sync_lock_test_and_set_8:
272 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000273 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000274 case Builtin::BI__sync_lock_release_1:
275 case Builtin::BI__sync_lock_release_2:
276 case Builtin::BI__sync_lock_release_4:
277 case Builtin::BI__sync_lock_release_8:
278 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000279 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000280 case Builtin::BI__sync_swap_1:
281 case Builtin::BI__sync_swap_2:
282 case Builtin::BI__sync_swap_4:
283 case Builtin::BI__sync_swap_8:
284 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000285 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000286#define BUILTIN(ID, TYPE, ATTRS)
287#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
288 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000289 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000290#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000291 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000292 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000293 return ExprError();
294 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000295 case Builtin::BI__builtin_addressof:
296 if (SemaBuiltinAddressof(*this, TheCall))
297 return ExprError();
298 break;
Richard Smith760520b2014-06-03 23:27:44 +0000299 case Builtin::BI__builtin_operator_new:
300 case Builtin::BI__builtin_operator_delete:
301 if (!getLangOpts().CPlusPlus) {
302 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
303 << (BuiltinID == Builtin::BI__builtin_operator_new
304 ? "__builtin_operator_new"
305 : "__builtin_operator_delete")
306 << "C++";
307 return ExprError();
308 }
309 // CodeGen assumes it can find the global new and delete to call,
310 // so ensure that they are declared.
311 DeclareGlobalNewDelete();
312 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000313 }
Richard Smith760520b2014-06-03 23:27:44 +0000314
Nate Begeman4904e322010-06-08 02:47:44 +0000315 // Since the target specific builtins for each arch overlap, only check those
316 // of the arch we are compiling for.
317 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000318 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000319 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000320 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000321 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000322 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000323 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000326 case llvm::Triple::aarch64:
327 case llvm::Triple::aarch64_be:
Tim Northovera2ee4332014-03-29 15:09:45 +0000328 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000329 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000330 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000331 return ExprError();
332 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000333 case llvm::Triple::mips:
334 case llvm::Triple::mipsel:
335 case llvm::Triple::mips64:
336 case llvm::Triple::mips64el:
337 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
338 return ExprError();
339 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000340 case llvm::Triple::x86:
341 case llvm::Triple::x86_64:
342 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
343 return ExprError();
344 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000345 default:
346 break;
347 }
348 }
349
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000350 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000351}
352
Nate Begeman91e1fea2010-06-14 05:21:25 +0000353// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000354static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000355 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000356 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000357 switch (Type.getEltType()) {
358 case NeonTypeFlags::Int8:
359 case NeonTypeFlags::Poly8:
360 return shift ? 7 : (8 << IsQuad) - 1;
361 case NeonTypeFlags::Int16:
362 case NeonTypeFlags::Poly16:
363 return shift ? 15 : (4 << IsQuad) - 1;
364 case NeonTypeFlags::Int32:
365 return shift ? 31 : (2 << IsQuad) - 1;
366 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000367 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000368 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000369 case NeonTypeFlags::Poly128:
370 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000371 case NeonTypeFlags::Float16:
372 assert(!shift && "cannot shift float types!");
373 return (4 << IsQuad) - 1;
374 case NeonTypeFlags::Float32:
375 assert(!shift && "cannot shift float types!");
376 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000377 case NeonTypeFlags::Float64:
378 assert(!shift && "cannot shift float types!");
379 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000380 }
David Blaikie8a40f702012-01-17 06:56:22 +0000381 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000382}
383
Bob Wilsone4d77232011-11-08 05:04:11 +0000384/// getNeonEltType - Return the QualType corresponding to the elements of
385/// the vector type specified by the NeonTypeFlags. This is used to check
386/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000387static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000388 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000389 switch (Flags.getEltType()) {
390 case NeonTypeFlags::Int8:
391 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
392 case NeonTypeFlags::Int16:
393 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
394 case NeonTypeFlags::Int32:
395 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
396 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000397 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000398 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
399 else
400 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
401 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000402 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000403 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000404 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000405 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000406 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000407 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000408 case NeonTypeFlags::Poly128:
409 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000410 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000411 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000412 case NeonTypeFlags::Float32:
413 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000414 case NeonTypeFlags::Float64:
415 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000416 }
David Blaikie8a40f702012-01-17 06:56:22 +0000417 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000418}
419
Tim Northover12670412014-02-19 10:37:05 +0000420bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000421 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000422 uint64_t mask = 0;
423 unsigned TV = 0;
424 int PtrArgNum = -1;
425 bool HasConstPtr = false;
426 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000427#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000428#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000429#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000430 }
431
432 // For NEON intrinsics which are overloaded on vector element type, validate
433 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000434 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000435 if (mask) {
436 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
437 return true;
438
439 TV = Result.getLimitedValue(64);
440 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
441 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000442 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000443 }
444
445 if (PtrArgNum >= 0) {
446 // Check that pointer arguments have the specified type.
447 Expr *Arg = TheCall->getArg(PtrArgNum);
448 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
449 Arg = ICE->getSubExpr();
450 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
451 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000452
Tim Northovera2ee4332014-03-29 15:09:45 +0000453 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
454 bool IsPolyUnsigned =
455 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
456 bool IsInt64Long =
457 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
458 QualType EltTy =
459 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000460 if (HasConstPtr)
461 EltTy = EltTy.withConst();
462 QualType LHSTy = Context.getPointerType(EltTy);
463 AssignConvertType ConvTy;
464 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
465 if (RHS.isInvalid())
466 return true;
467 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
468 RHS.get(), AA_Assigning))
469 return true;
470 }
471
472 // For NEON intrinsics which take an immediate value as part of the
473 // instruction, range check them here.
474 unsigned i = 0, l = 0, u = 0;
475 switch (BuiltinID) {
476 default:
477 return false;
Tim Northover12670412014-02-19 10:37:05 +0000478#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000479#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000480#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000481 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000482
Richard Sandiford28940af2014-04-16 08:47:51 +0000483 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000484}
485
Tim Northovera2ee4332014-03-29 15:09:45 +0000486bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
487 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000488 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000489 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000490 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
491 BuiltinID == AArch64::BI__builtin_arm_strex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000492 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000493 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000494 BuiltinID == AArch64::BI__builtin_arm_ldrex;
Tim Northover6aacd492013-07-16 09:47:53 +0000495
496 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
497
498 // Ensure that we have the proper number of arguments.
499 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
500 return true;
501
502 // Inspect the pointer argument of the atomic builtin. This should always be
503 // a pointer type, whose element is an integral scalar or pointer type.
504 // Because it is a pointer type, we don't have to worry about any implicit
505 // casts here.
506 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
507 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
508 if (PointerArgRes.isInvalid())
509 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000510 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000511
512 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
513 if (!pointerType) {
514 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
515 << PointerArg->getType() << PointerArg->getSourceRange();
516 return true;
517 }
518
519 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
520 // task is to insert the appropriate casts into the AST. First work out just
521 // what the appropriate type is.
522 QualType ValType = pointerType->getPointeeType();
523 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
524 if (IsLdrex)
525 AddrType.addConst();
526
527 // Issue a warning if the cast is dodgy.
528 CastKind CastNeeded = CK_NoOp;
529 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
530 CastNeeded = CK_BitCast;
531 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
532 << PointerArg->getType()
533 << Context.getPointerType(AddrType)
534 << AA_Passing << PointerArg->getSourceRange();
535 }
536
537 // Finally, do the cast and replace the argument with the corrected version.
538 AddrType = Context.getPointerType(AddrType);
539 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
540 if (PointerArgRes.isInvalid())
541 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000542 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000543
544 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
545
546 // In general, we allow ints, floats and pointers to be loaded and stored.
547 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
548 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
549 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
550 << PointerArg->getType() << PointerArg->getSourceRange();
551 return true;
552 }
553
554 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000555 if (Context.getTypeSize(ValType) > MaxWidth) {
556 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000557 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
558 << PointerArg->getType() << PointerArg->getSourceRange();
559 return true;
560 }
561
562 switch (ValType.getObjCLifetime()) {
563 case Qualifiers::OCL_None:
564 case Qualifiers::OCL_ExplicitNone:
565 // okay
566 break;
567
568 case Qualifiers::OCL_Weak:
569 case Qualifiers::OCL_Strong:
570 case Qualifiers::OCL_Autoreleasing:
571 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
572 << ValType << PointerArg->getSourceRange();
573 return true;
574 }
575
576
577 if (IsLdrex) {
578 TheCall->setType(ValType);
579 return false;
580 }
581
582 // Initialize the argument to be stored.
583 ExprResult ValArg = TheCall->getArg(0);
584 InitializedEntity Entity = InitializedEntity::InitializeParameter(
585 Context, ValType, /*consume*/ false);
586 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
587 if (ValArg.isInvalid())
588 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000589 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000590
591 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
592 // but the custom checker bypasses all default analysis.
593 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000594 return false;
595}
596
Nate Begeman4904e322010-06-08 02:47:44 +0000597bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000598 llvm::APSInt Result;
599
Tim Northover6aacd492013-07-16 09:47:53 +0000600 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
601 BuiltinID == ARM::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000602 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000603 }
604
Tim Northover12670412014-02-19 10:37:05 +0000605 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
606 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000607
Bob Wilsond836d3d2014-03-09 23:02:27 +0000608 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000609 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000610 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000611 switch (BuiltinID) {
612 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000613 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
614 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000615 case ARM::BI__builtin_arm_vcvtr_f:
616 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000617 case ARM::BI__builtin_arm_dmb:
618 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000619 }
Nate Begemand773fe62010-06-13 04:47:52 +0000620
Nate Begemanf568b072010-08-03 21:32:34 +0000621 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000622 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000623}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000624
Tim Northover573cbee2014-05-24 12:52:07 +0000625bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000626 CallExpr *TheCall) {
627 llvm::APSInt Result;
628
Tim Northover573cbee2014-05-24 12:52:07 +0000629 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
630 BuiltinID == AArch64::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000631 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
632 }
633
634 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
635 return true;
636
637 return false;
638}
639
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000640bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
641 unsigned i = 0, l = 0, u = 0;
642 switch (BuiltinID) {
643 default: return false;
644 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
645 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000646 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
647 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
648 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
649 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
650 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000651 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000652
Richard Sandiford28940af2014-04-16 08:47:51 +0000653 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000654}
655
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000656bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
657 switch (BuiltinID) {
658 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000659 // This is declared to take (const char*, int)
660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000661 }
662 return false;
663}
664
Richard Smith55ce3522012-06-25 20:30:08 +0000665/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
666/// parameter with the FormatAttr's correct format_idx and firstDataArg.
667/// Returns true when the format fits the function and the FormatStringInfo has
668/// been populated.
669bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
670 FormatStringInfo *FSI) {
671 FSI->HasVAListArg = Format->getFirstArg() == 0;
672 FSI->FormatIdx = Format->getFormatIdx() - 1;
673 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000674
Richard Smith55ce3522012-06-25 20:30:08 +0000675 // The way the format attribute works in GCC, the implicit this argument
676 // of member functions is counted. However, it doesn't appear in our own
677 // lists, so decrement format_idx in that case.
678 if (IsCXXMember) {
679 if(FSI->FormatIdx == 0)
680 return false;
681 --FSI->FormatIdx;
682 if (FSI->FirstDataArg != 0)
683 --FSI->FirstDataArg;
684 }
685 return true;
686}
Mike Stump11289f42009-09-09 15:08:12 +0000687
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000688/// Checks if a the given expression evaluates to null.
689///
690/// \brief Returns true if the value evaluates to null.
691static bool CheckNonNullExpr(Sema &S,
692 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000693 // As a special case, transparent unions initialized with zero are
694 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000695 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000696 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
697 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000698 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000699 if (const InitListExpr *ILE =
700 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000701 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000702 }
703
704 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000705 return (!Expr->isValueDependent() &&
706 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
707 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000708}
709
710static void CheckNonNullArgument(Sema &S,
711 const Expr *ArgExpr,
712 SourceLocation CallSiteLoc) {
713 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000714 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
715}
716
Ted Kremenek2bc73332014-01-17 06:24:43 +0000717static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000718 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000719 const Expr * const *ExprArgs,
720 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000721 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000722 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000723 for (const auto &Val : NonNull->args())
724 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000725 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000726
727 // Check the attributes on the parameters.
728 ArrayRef<ParmVarDecl*> parms;
729 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
730 parms = FD->parameters();
731 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
732 parms = MD->parameters();
733
734 unsigned argIndex = 0;
735 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
736 I != E; ++I, ++argIndex) {
737 const ParmVarDecl *PVD = *I;
738 if (PVD->hasAttr<NonNullAttr>())
739 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
740 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000741}
742
Richard Smith55ce3522012-06-25 20:30:08 +0000743/// Handles the checks for format strings, non-POD arguments to vararg
744/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000745void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
746 unsigned NumParams, bool IsMemberFunction,
747 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000748 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000749 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000750 if (CurContext->isDependentContext())
751 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000752
Ted Kremenekb8176da2010-09-09 04:33:05 +0000753 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000754 llvm::SmallBitVector CheckedVarArgs;
755 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000756 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000757 // Only create vector if there are format attributes.
758 CheckedVarArgs.resize(Args.size());
759
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000760 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000761 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000762 }
Richard Smithd7293d72013-08-05 18:49:43 +0000763 }
Richard Smith55ce3522012-06-25 20:30:08 +0000764
765 // Refuse POD arguments that weren't caught by the format string
766 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000767 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000768 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000769 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000770 if (const Expr *Arg = Args[ArgIdx]) {
771 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
772 checkVariadicArgument(Arg, CallType);
773 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000774 }
Richard Smithd7293d72013-08-05 18:49:43 +0000775 }
Mike Stump11289f42009-09-09 15:08:12 +0000776
Richard Trieu41bc0992013-06-22 00:20:41 +0000777 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000778 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000779
Richard Trieu41bc0992013-06-22 00:20:41 +0000780 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000781 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
782 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000783 }
Richard Smith55ce3522012-06-25 20:30:08 +0000784}
785
786/// CheckConstructorCall - Check a constructor call for correctness and safety
787/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000788void Sema::CheckConstructorCall(FunctionDecl *FDecl,
789 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000790 const FunctionProtoType *Proto,
791 SourceLocation Loc) {
792 VariadicCallType CallType =
793 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000795 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
796}
797
798/// CheckFunctionCall - Check a direct function call for various correctness
799/// and safety properties not strictly enforced by the C type system.
800bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
801 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000802 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
803 isa<CXXMethodDecl>(FDecl);
804 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
805 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000806 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
807 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000808 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000809 Expr** Args = TheCall->getArgs();
810 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000811 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000812 // If this is a call to a member operator, hide the first argument
813 // from checkCall.
814 // FIXME: Our choice of AST representation here is less than ideal.
815 ++Args;
816 --NumArgs;
817 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000818 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000819 IsMemberFunction, TheCall->getRParenLoc(),
820 TheCall->getCallee()->getSourceRange(), CallType);
821
822 IdentifierInfo *FnInfo = FDecl->getIdentifier();
823 // None of the checks below are needed for functions that don't have
824 // simple names (e.g., C++ conversion functions).
825 if (!FnInfo)
826 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000827
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000828 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
829
Anna Zaks22122702012-01-17 00:37:07 +0000830 unsigned CMId = FDecl->getMemoryFunctionKind();
831 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000832 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000833
Anna Zaks201d4892012-01-13 21:52:01 +0000834 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000835 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000836 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000837 else if (CMId == Builtin::BIstrncat)
838 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000839 else
Anna Zaks22122702012-01-17 00:37:07 +0000840 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000841
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000842 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000843}
844
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000845bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000846 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000847 VariadicCallType CallType =
848 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000849
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000850 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000851 /*IsMemberFunction=*/false,
852 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000853
854 return false;
855}
856
Richard Trieu664c4c62013-06-20 21:03:13 +0000857bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
858 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000859 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
860 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000861 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000862
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000863 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000864 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000865 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000866
Richard Trieu664c4c62013-06-20 21:03:13 +0000867 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000868 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000869 CallType = VariadicDoesNotApply;
870 } else if (Ty->isBlockPointerType()) {
871 CallType = VariadicBlock;
872 } else { // Ty->isFunctionPointerType()
873 CallType = VariadicFunction;
874 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000875 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000876
Alp Toker9cacbab2014-01-20 20:26:09 +0000877 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
878 TheCall->getNumArgs()),
879 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000880 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000881
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000882 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000883}
884
Richard Trieu41bc0992013-06-22 00:20:41 +0000885/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
886/// such as function pointers returned from functions.
887bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000888 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000889 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000890 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000891
Craig Topperc3ec1492014-05-26 06:22:03 +0000892 checkCall(/*FDecl=*/nullptr,
893 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
894 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000895 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000896 TheCall->getCallee()->getSourceRange(), CallType);
897
898 return false;
899}
900
Tim Northovere94a34c2014-03-11 10:49:14 +0000901static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
902 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
903 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
904 return false;
905
906 switch (Op) {
907 case AtomicExpr::AO__c11_atomic_init:
908 llvm_unreachable("There is no ordering argument for an init");
909
910 case AtomicExpr::AO__c11_atomic_load:
911 case AtomicExpr::AO__atomic_load_n:
912 case AtomicExpr::AO__atomic_load:
913 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
914 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
915
916 case AtomicExpr::AO__c11_atomic_store:
917 case AtomicExpr::AO__atomic_store:
918 case AtomicExpr::AO__atomic_store_n:
919 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
920 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
921 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
922
923 default:
924 return true;
925 }
926}
927
Richard Smithfeea8832012-04-12 05:08:17 +0000928ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
929 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000930 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
931 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000932
Richard Smithfeea8832012-04-12 05:08:17 +0000933 // All these operations take one of the following forms:
934 enum {
935 // C __c11_atomic_init(A *, C)
936 Init,
937 // C __c11_atomic_load(A *, int)
938 Load,
939 // void __atomic_load(A *, CP, int)
940 Copy,
941 // C __c11_atomic_add(A *, M, int)
942 Arithmetic,
943 // C __atomic_exchange_n(A *, CP, int)
944 Xchg,
945 // void __atomic_exchange(A *, C *, CP, int)
946 GNUXchg,
947 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
948 C11CmpXchg,
949 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
950 GNUCmpXchg
951 } Form = Init;
952 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
953 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
954 // where:
955 // C is an appropriate type,
956 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
957 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
958 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
959 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000960
Richard Smithfeea8832012-04-12 05:08:17 +0000961 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
962 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
963 && "need to update code for modified C11 atomics");
964 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
965 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
966 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
967 Op == AtomicExpr::AO__atomic_store_n ||
968 Op == AtomicExpr::AO__atomic_exchange_n ||
969 Op == AtomicExpr::AO__atomic_compare_exchange_n;
970 bool IsAddSub = false;
971
972 switch (Op) {
973 case AtomicExpr::AO__c11_atomic_init:
974 Form = Init;
975 break;
976
977 case AtomicExpr::AO__c11_atomic_load:
978 case AtomicExpr::AO__atomic_load_n:
979 Form = Load;
980 break;
981
982 case AtomicExpr::AO__c11_atomic_store:
983 case AtomicExpr::AO__atomic_load:
984 case AtomicExpr::AO__atomic_store:
985 case AtomicExpr::AO__atomic_store_n:
986 Form = Copy;
987 break;
988
989 case AtomicExpr::AO__c11_atomic_fetch_add:
990 case AtomicExpr::AO__c11_atomic_fetch_sub:
991 case AtomicExpr::AO__atomic_fetch_add:
992 case AtomicExpr::AO__atomic_fetch_sub:
993 case AtomicExpr::AO__atomic_add_fetch:
994 case AtomicExpr::AO__atomic_sub_fetch:
995 IsAddSub = true;
996 // Fall through.
997 case AtomicExpr::AO__c11_atomic_fetch_and:
998 case AtomicExpr::AO__c11_atomic_fetch_or:
999 case AtomicExpr::AO__c11_atomic_fetch_xor:
1000 case AtomicExpr::AO__atomic_fetch_and:
1001 case AtomicExpr::AO__atomic_fetch_or:
1002 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001003 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001004 case AtomicExpr::AO__atomic_and_fetch:
1005 case AtomicExpr::AO__atomic_or_fetch:
1006 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001007 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001008 Form = Arithmetic;
1009 break;
1010
1011 case AtomicExpr::AO__c11_atomic_exchange:
1012 case AtomicExpr::AO__atomic_exchange_n:
1013 Form = Xchg;
1014 break;
1015
1016 case AtomicExpr::AO__atomic_exchange:
1017 Form = GNUXchg;
1018 break;
1019
1020 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1021 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1022 Form = C11CmpXchg;
1023 break;
1024
1025 case AtomicExpr::AO__atomic_compare_exchange:
1026 case AtomicExpr::AO__atomic_compare_exchange_n:
1027 Form = GNUCmpXchg;
1028 break;
1029 }
1030
1031 // Check we have the right number of arguments.
1032 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001033 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001034 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001035 << TheCall->getCallee()->getSourceRange();
1036 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001037 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1038 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001039 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001040 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001041 << TheCall->getCallee()->getSourceRange();
1042 return ExprError();
1043 }
1044
Richard Smithfeea8832012-04-12 05:08:17 +00001045 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001046 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001047 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1048 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1049 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001050 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001051 << Ptr->getType() << Ptr->getSourceRange();
1052 return ExprError();
1053 }
1054
Richard Smithfeea8832012-04-12 05:08:17 +00001055 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1056 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1057 QualType ValType = AtomTy; // 'C'
1058 if (IsC11) {
1059 if (!AtomTy->isAtomicType()) {
1060 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1061 << Ptr->getType() << Ptr->getSourceRange();
1062 return ExprError();
1063 }
Richard Smithe00921a2012-09-15 06:09:58 +00001064 if (AtomTy.isConstQualified()) {
1065 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1066 << Ptr->getType() << Ptr->getSourceRange();
1067 return ExprError();
1068 }
Richard Smithfeea8832012-04-12 05:08:17 +00001069 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001070 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001071
Richard Smithfeea8832012-04-12 05:08:17 +00001072 // For an arithmetic operation, the implied arithmetic must be well-formed.
1073 if (Form == Arithmetic) {
1074 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1075 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1076 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1077 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1078 return ExprError();
1079 }
1080 if (!IsAddSub && !ValType->isIntegerType()) {
1081 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1082 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1083 return ExprError();
1084 }
1085 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1086 // For __atomic_*_n operations, the value type must be a scalar integral or
1087 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001088 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001089 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1090 return ExprError();
1091 }
1092
Eli Friedmanaa769812013-09-11 03:49:34 +00001093 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1094 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001095 // For GNU atomics, require a trivially-copyable type. This is not part of
1096 // the GNU atomics specification, but we enforce it for sanity.
1097 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001098 << Ptr->getType() << Ptr->getSourceRange();
1099 return ExprError();
1100 }
1101
Richard Smithfeea8832012-04-12 05:08:17 +00001102 // FIXME: For any builtin other than a load, the ValType must not be
1103 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001104
1105 switch (ValType.getObjCLifetime()) {
1106 case Qualifiers::OCL_None:
1107 case Qualifiers::OCL_ExplicitNone:
1108 // okay
1109 break;
1110
1111 case Qualifiers::OCL_Weak:
1112 case Qualifiers::OCL_Strong:
1113 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001114 // FIXME: Can this happen? By this point, ValType should be known
1115 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001116 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1117 << ValType << Ptr->getSourceRange();
1118 return ExprError();
1119 }
1120
1121 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001122 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001123 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001124 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001125 ResultType = Context.BoolTy;
1126
Richard Smithfeea8832012-04-12 05:08:17 +00001127 // The type of a parameter passed 'by value'. In the GNU atomics, such
1128 // arguments are actually passed as pointers.
1129 QualType ByValType = ValType; // 'CP'
1130 if (!IsC11 && !IsN)
1131 ByValType = Ptr->getType();
1132
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001133 // The first argument --- the pointer --- has a fixed type; we
1134 // deduce the types of the rest of the arguments accordingly. Walk
1135 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001136 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001137 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001138 if (i < NumVals[Form] + 1) {
1139 switch (i) {
1140 case 1:
1141 // The second argument is the non-atomic operand. For arithmetic, this
1142 // is always passed by value, and for a compare_exchange it is always
1143 // passed by address. For the rest, GNU uses by-address and C11 uses
1144 // by-value.
1145 assert(Form != Load);
1146 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1147 Ty = ValType;
1148 else if (Form == Copy || Form == Xchg)
1149 Ty = ByValType;
1150 else if (Form == Arithmetic)
1151 Ty = Context.getPointerDiffType();
1152 else
1153 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1154 break;
1155 case 2:
1156 // The third argument to compare_exchange / GNU exchange is a
1157 // (pointer to a) desired value.
1158 Ty = ByValType;
1159 break;
1160 case 3:
1161 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1162 Ty = Context.BoolTy;
1163 break;
1164 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001165 } else {
1166 // The order(s) are always converted to int.
1167 Ty = Context.IntTy;
1168 }
Richard Smithfeea8832012-04-12 05:08:17 +00001169
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001170 InitializedEntity Entity =
1171 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001172 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001173 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1174 if (Arg.isInvalid())
1175 return true;
1176 TheCall->setArg(i, Arg.get());
1177 }
1178
Richard Smithfeea8832012-04-12 05:08:17 +00001179 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001180 SmallVector<Expr*, 5> SubExprs;
1181 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001182 switch (Form) {
1183 case Init:
1184 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001185 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001186 break;
1187 case Load:
1188 SubExprs.push_back(TheCall->getArg(1)); // Order
1189 break;
1190 case Copy:
1191 case Arithmetic:
1192 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001193 SubExprs.push_back(TheCall->getArg(2)); // Order
1194 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001195 break;
1196 case GNUXchg:
1197 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1198 SubExprs.push_back(TheCall->getArg(3)); // Order
1199 SubExprs.push_back(TheCall->getArg(1)); // Val1
1200 SubExprs.push_back(TheCall->getArg(2)); // Val2
1201 break;
1202 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001203 SubExprs.push_back(TheCall->getArg(3)); // Order
1204 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001205 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001206 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001207 break;
1208 case GNUCmpXchg:
1209 SubExprs.push_back(TheCall->getArg(4)); // Order
1210 SubExprs.push_back(TheCall->getArg(1)); // Val1
1211 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1212 SubExprs.push_back(TheCall->getArg(2)); // Val2
1213 SubExprs.push_back(TheCall->getArg(3)); // Weak
1214 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001215 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001216
1217 if (SubExprs.size() >= 2 && Form != Init) {
1218 llvm::APSInt Result(32);
1219 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1220 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001221 Diag(SubExprs[1]->getLocStart(),
1222 diag::warn_atomic_op_has_invalid_memory_order)
1223 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001224 }
1225
Fariborz Jahanian615de762013-05-28 17:37:39 +00001226 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1227 SubExprs, ResultType, Op,
1228 TheCall->getRParenLoc());
1229
1230 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1231 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1232 Context.AtomicUsesUnsupportedLibcall(AE))
1233 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1234 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001235
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001236 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001237}
1238
1239
John McCall29ad95b2011-08-27 01:09:30 +00001240/// checkBuiltinArgument - Given a call to a builtin function, perform
1241/// normal type-checking on the given argument, updating the call in
1242/// place. This is useful when a builtin function requires custom
1243/// type-checking for some of its arguments but not necessarily all of
1244/// them.
1245///
1246/// Returns true on error.
1247static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1248 FunctionDecl *Fn = E->getDirectCallee();
1249 assert(Fn && "builtin call without direct callee!");
1250
1251 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1252 InitializedEntity Entity =
1253 InitializedEntity::InitializeParameter(S.Context, Param);
1254
1255 ExprResult Arg = E->getArg(0);
1256 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1257 if (Arg.isInvalid())
1258 return true;
1259
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001260 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001261 return false;
1262}
1263
Chris Lattnerdc046542009-05-08 06:58:22 +00001264/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1265/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1266/// type of its first argument. The main ActOnCallExpr routines have already
1267/// promoted the types of arguments because all of these calls are prototyped as
1268/// void(...).
1269///
1270/// This function goes through and does final semantic checking for these
1271/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001272ExprResult
1273Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001274 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001275 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1276 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1277
1278 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001279 if (TheCall->getNumArgs() < 1) {
1280 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1281 << 0 << 1 << TheCall->getNumArgs()
1282 << TheCall->getCallee()->getSourceRange();
1283 return ExprError();
1284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Chris Lattnerdc046542009-05-08 06:58:22 +00001286 // Inspect the first argument of the atomic builtin. This should always be
1287 // a pointer type, whose element is an integral scalar or pointer type.
1288 // Because it is a pointer type, we don't have to worry about any implicit
1289 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001290 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001291 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001292 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1293 if (FirstArgResult.isInvalid())
1294 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001295 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001296 TheCall->setArg(0, FirstArg);
1297
John McCall31168b02011-06-15 23:02:42 +00001298 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1299 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001300 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1301 << FirstArg->getType() << FirstArg->getSourceRange();
1302 return ExprError();
1303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall31168b02011-06-15 23:02:42 +00001305 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001306 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001307 !ValType->isBlockPointerType()) {
1308 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1309 << FirstArg->getType() << FirstArg->getSourceRange();
1310 return ExprError();
1311 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001312
John McCall31168b02011-06-15 23:02:42 +00001313 switch (ValType.getObjCLifetime()) {
1314 case Qualifiers::OCL_None:
1315 case Qualifiers::OCL_ExplicitNone:
1316 // okay
1317 break;
1318
1319 case Qualifiers::OCL_Weak:
1320 case Qualifiers::OCL_Strong:
1321 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001322 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001323 << ValType << FirstArg->getSourceRange();
1324 return ExprError();
1325 }
1326
John McCallb50451a2011-10-05 07:41:44 +00001327 // Strip any qualifiers off ValType.
1328 ValType = ValType.getUnqualifiedType();
1329
Chandler Carruth3973af72010-07-18 20:54:12 +00001330 // The majority of builtins return a value, but a few have special return
1331 // types, so allow them to override appropriately below.
1332 QualType ResultType = ValType;
1333
Chris Lattnerdc046542009-05-08 06:58:22 +00001334 // We need to figure out which concrete builtin this maps onto. For example,
1335 // __sync_fetch_and_add with a 2 byte object turns into
1336 // __sync_fetch_and_add_2.
1337#define BUILTIN_ROW(x) \
1338 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1339 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerdc046542009-05-08 06:58:22 +00001341 static const unsigned BuiltinIndices[][5] = {
1342 BUILTIN_ROW(__sync_fetch_and_add),
1343 BUILTIN_ROW(__sync_fetch_and_sub),
1344 BUILTIN_ROW(__sync_fetch_and_or),
1345 BUILTIN_ROW(__sync_fetch_and_and),
1346 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001347
Chris Lattnerdc046542009-05-08 06:58:22 +00001348 BUILTIN_ROW(__sync_add_and_fetch),
1349 BUILTIN_ROW(__sync_sub_and_fetch),
1350 BUILTIN_ROW(__sync_and_and_fetch),
1351 BUILTIN_ROW(__sync_or_and_fetch),
1352 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerdc046542009-05-08 06:58:22 +00001354 BUILTIN_ROW(__sync_val_compare_and_swap),
1355 BUILTIN_ROW(__sync_bool_compare_and_swap),
1356 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001357 BUILTIN_ROW(__sync_lock_release),
1358 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001359 };
Mike Stump11289f42009-09-09 15:08:12 +00001360#undef BUILTIN_ROW
1361
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 // Determine the index of the size.
1363 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001364 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001365 case 1: SizeIndex = 0; break;
1366 case 2: SizeIndex = 1; break;
1367 case 4: SizeIndex = 2; break;
1368 case 8: SizeIndex = 3; break;
1369 case 16: SizeIndex = 4; break;
1370 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001371 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1372 << FirstArg->getType() << FirstArg->getSourceRange();
1373 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Chris Lattnerdc046542009-05-08 06:58:22 +00001376 // Each of these builtins has one pointer argument, followed by some number of
1377 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1378 // that we ignore. Find out which row of BuiltinIndices to read from as well
1379 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001380 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001381 unsigned BuiltinIndex, NumFixed = 1;
1382 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001383 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001384 case Builtin::BI__sync_fetch_and_add:
1385 case Builtin::BI__sync_fetch_and_add_1:
1386 case Builtin::BI__sync_fetch_and_add_2:
1387 case Builtin::BI__sync_fetch_and_add_4:
1388 case Builtin::BI__sync_fetch_and_add_8:
1389 case Builtin::BI__sync_fetch_and_add_16:
1390 BuiltinIndex = 0;
1391 break;
1392
1393 case Builtin::BI__sync_fetch_and_sub:
1394 case Builtin::BI__sync_fetch_and_sub_1:
1395 case Builtin::BI__sync_fetch_and_sub_2:
1396 case Builtin::BI__sync_fetch_and_sub_4:
1397 case Builtin::BI__sync_fetch_and_sub_8:
1398 case Builtin::BI__sync_fetch_and_sub_16:
1399 BuiltinIndex = 1;
1400 break;
1401
1402 case Builtin::BI__sync_fetch_and_or:
1403 case Builtin::BI__sync_fetch_and_or_1:
1404 case Builtin::BI__sync_fetch_and_or_2:
1405 case Builtin::BI__sync_fetch_and_or_4:
1406 case Builtin::BI__sync_fetch_and_or_8:
1407 case Builtin::BI__sync_fetch_and_or_16:
1408 BuiltinIndex = 2;
1409 break;
1410
1411 case Builtin::BI__sync_fetch_and_and:
1412 case Builtin::BI__sync_fetch_and_and_1:
1413 case Builtin::BI__sync_fetch_and_and_2:
1414 case Builtin::BI__sync_fetch_and_and_4:
1415 case Builtin::BI__sync_fetch_and_and_8:
1416 case Builtin::BI__sync_fetch_and_and_16:
1417 BuiltinIndex = 3;
1418 break;
Mike Stump11289f42009-09-09 15:08:12 +00001419
Douglas Gregor73722482011-11-28 16:30:08 +00001420 case Builtin::BI__sync_fetch_and_xor:
1421 case Builtin::BI__sync_fetch_and_xor_1:
1422 case Builtin::BI__sync_fetch_and_xor_2:
1423 case Builtin::BI__sync_fetch_and_xor_4:
1424 case Builtin::BI__sync_fetch_and_xor_8:
1425 case Builtin::BI__sync_fetch_and_xor_16:
1426 BuiltinIndex = 4;
1427 break;
1428
1429 case Builtin::BI__sync_add_and_fetch:
1430 case Builtin::BI__sync_add_and_fetch_1:
1431 case Builtin::BI__sync_add_and_fetch_2:
1432 case Builtin::BI__sync_add_and_fetch_4:
1433 case Builtin::BI__sync_add_and_fetch_8:
1434 case Builtin::BI__sync_add_and_fetch_16:
1435 BuiltinIndex = 5;
1436 break;
1437
1438 case Builtin::BI__sync_sub_and_fetch:
1439 case Builtin::BI__sync_sub_and_fetch_1:
1440 case Builtin::BI__sync_sub_and_fetch_2:
1441 case Builtin::BI__sync_sub_and_fetch_4:
1442 case Builtin::BI__sync_sub_and_fetch_8:
1443 case Builtin::BI__sync_sub_and_fetch_16:
1444 BuiltinIndex = 6;
1445 break;
1446
1447 case Builtin::BI__sync_and_and_fetch:
1448 case Builtin::BI__sync_and_and_fetch_1:
1449 case Builtin::BI__sync_and_and_fetch_2:
1450 case Builtin::BI__sync_and_and_fetch_4:
1451 case Builtin::BI__sync_and_and_fetch_8:
1452 case Builtin::BI__sync_and_and_fetch_16:
1453 BuiltinIndex = 7;
1454 break;
1455
1456 case Builtin::BI__sync_or_and_fetch:
1457 case Builtin::BI__sync_or_and_fetch_1:
1458 case Builtin::BI__sync_or_and_fetch_2:
1459 case Builtin::BI__sync_or_and_fetch_4:
1460 case Builtin::BI__sync_or_and_fetch_8:
1461 case Builtin::BI__sync_or_and_fetch_16:
1462 BuiltinIndex = 8;
1463 break;
1464
1465 case Builtin::BI__sync_xor_and_fetch:
1466 case Builtin::BI__sync_xor_and_fetch_1:
1467 case Builtin::BI__sync_xor_and_fetch_2:
1468 case Builtin::BI__sync_xor_and_fetch_4:
1469 case Builtin::BI__sync_xor_and_fetch_8:
1470 case Builtin::BI__sync_xor_and_fetch_16:
1471 BuiltinIndex = 9;
1472 break;
Mike Stump11289f42009-09-09 15:08:12 +00001473
Chris Lattnerdc046542009-05-08 06:58:22 +00001474 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001475 case Builtin::BI__sync_val_compare_and_swap_1:
1476 case Builtin::BI__sync_val_compare_and_swap_2:
1477 case Builtin::BI__sync_val_compare_and_swap_4:
1478 case Builtin::BI__sync_val_compare_and_swap_8:
1479 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001480 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001481 NumFixed = 2;
1482 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001483
Chris Lattnerdc046542009-05-08 06:58:22 +00001484 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001485 case Builtin::BI__sync_bool_compare_and_swap_1:
1486 case Builtin::BI__sync_bool_compare_and_swap_2:
1487 case Builtin::BI__sync_bool_compare_and_swap_4:
1488 case Builtin::BI__sync_bool_compare_and_swap_8:
1489 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001490 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001491 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001492 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001493 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001494
1495 case Builtin::BI__sync_lock_test_and_set:
1496 case Builtin::BI__sync_lock_test_and_set_1:
1497 case Builtin::BI__sync_lock_test_and_set_2:
1498 case Builtin::BI__sync_lock_test_and_set_4:
1499 case Builtin::BI__sync_lock_test_and_set_8:
1500 case Builtin::BI__sync_lock_test_and_set_16:
1501 BuiltinIndex = 12;
1502 break;
1503
Chris Lattnerdc046542009-05-08 06:58:22 +00001504 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001505 case Builtin::BI__sync_lock_release_1:
1506 case Builtin::BI__sync_lock_release_2:
1507 case Builtin::BI__sync_lock_release_4:
1508 case Builtin::BI__sync_lock_release_8:
1509 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001510 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001511 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001512 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001513 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001514
1515 case Builtin::BI__sync_swap:
1516 case Builtin::BI__sync_swap_1:
1517 case Builtin::BI__sync_swap_2:
1518 case Builtin::BI__sync_swap_4:
1519 case Builtin::BI__sync_swap_8:
1520 case Builtin::BI__sync_swap_16:
1521 BuiltinIndex = 14;
1522 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001523 }
Mike Stump11289f42009-09-09 15:08:12 +00001524
Chris Lattnerdc046542009-05-08 06:58:22 +00001525 // Now that we know how many fixed arguments we expect, first check that we
1526 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001527 if (TheCall->getNumArgs() < 1+NumFixed) {
1528 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1529 << 0 << 1+NumFixed << TheCall->getNumArgs()
1530 << TheCall->getCallee()->getSourceRange();
1531 return ExprError();
1532 }
Mike Stump11289f42009-09-09 15:08:12 +00001533
Chris Lattner5b9241b2009-05-08 15:36:58 +00001534 // Get the decl for the concrete builtin from this, we can tell what the
1535 // concrete integer type we should convert to is.
1536 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1537 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001538 FunctionDecl *NewBuiltinDecl;
1539 if (NewBuiltinID == BuiltinID)
1540 NewBuiltinDecl = FDecl;
1541 else {
1542 // Perform builtin lookup to avoid redeclaring it.
1543 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1544 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1545 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1546 assert(Res.getFoundDecl());
1547 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001548 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001549 return ExprError();
1550 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001551
John McCallcf142162010-08-07 06:22:56 +00001552 // The first argument --- the pointer --- has a fixed type; we
1553 // deduce the types of the rest of the arguments accordingly. Walk
1554 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001555 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001556 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001557
Chris Lattnerdc046542009-05-08 06:58:22 +00001558 // GCC does an implicit conversion to the pointer or integer ValType. This
1559 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001560 // Initialize the argument.
1561 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1562 ValType, /*consume*/ false);
1563 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001564 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001565 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001566
Chris Lattnerdc046542009-05-08 06:58:22 +00001567 // Okay, we have something that *can* be converted to the right type. Check
1568 // to see if there is a potentially weird extension going on here. This can
1569 // happen when you do an atomic operation on something like an char* and
1570 // pass in 42. The 42 gets converted to char. This is even more strange
1571 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001572 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001573 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001574 }
Mike Stump11289f42009-09-09 15:08:12 +00001575
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001576 ASTContext& Context = this->getASTContext();
1577
1578 // Create a new DeclRefExpr to refer to the new decl.
1579 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1580 Context,
1581 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001582 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001583 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001584 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001585 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001586 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001587 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001588
Chris Lattnerdc046542009-05-08 06:58:22 +00001589 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001590 // FIXME: This loses syntactic information.
1591 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1592 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1593 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001594 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001595
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001596 // Change the result type of the call to match the original value type. This
1597 // is arbitrary, but the codegen for these builtins ins design to handle it
1598 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001599 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001600
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001601 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001602}
1603
Chris Lattner6436fb62009-02-18 06:01:06 +00001604/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001605/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001606/// Note: It might also make sense to do the UTF-16 conversion here (would
1607/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001608bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001609 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001610 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1611
Douglas Gregorfb65e592011-07-27 05:40:30 +00001612 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001613 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1614 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001615 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001616 }
Mike Stump11289f42009-09-09 15:08:12 +00001617
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001618 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001619 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001620 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001621 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001622 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001623 UTF16 *ToPtr = &ToBuf[0];
1624
1625 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1626 &ToPtr, ToPtr + NumBytes,
1627 strictConversion);
1628 // Check for conversion failure.
1629 if (Result != conversionOK)
1630 Diag(Arg->getLocStart(),
1631 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1632 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001633 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001634}
1635
Chris Lattnere202e6a2007-12-20 00:05:45 +00001636/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1637/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001638bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1639 Expr *Fn = TheCall->getCallee();
1640 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001641 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001642 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001643 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1644 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001645 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001646 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001647 return true;
1648 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001649
1650 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001651 return Diag(TheCall->getLocEnd(),
1652 diag::err_typecheck_call_too_few_args_at_least)
1653 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001654 }
1655
John McCall29ad95b2011-08-27 01:09:30 +00001656 // Type-check the first argument normally.
1657 if (checkBuiltinArgument(*this, TheCall, 0))
1658 return true;
1659
Chris Lattnere202e6a2007-12-20 00:05:45 +00001660 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001661 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001662 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001663 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001664 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001665 else if (FunctionDecl *FD = getCurFunctionDecl())
1666 isVariadic = FD->isVariadic();
1667 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001668 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001669
Chris Lattnere202e6a2007-12-20 00:05:45 +00001670 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001671 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1672 return true;
1673 }
Mike Stump11289f42009-09-09 15:08:12 +00001674
Chris Lattner43be2e62007-12-19 23:59:04 +00001675 // Verify that the second argument to the builtin is the last argument of the
1676 // current function or method.
1677 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001678 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001679
Nico Weber9eea7642013-05-24 23:31:57 +00001680 // These are valid if SecondArgIsLastNamedArgument is false after the next
1681 // block.
1682 QualType Type;
1683 SourceLocation ParamLoc;
1684
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001685 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1686 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 // FIXME: This isn't correct for methods (results in bogus warning).
1688 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001689 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001690 if (CurBlock)
1691 LastArg = *(CurBlock->TheDecl->param_end()-1);
1692 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001693 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001694 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001695 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001696 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001697
1698 Type = PV->getType();
1699 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001700 }
1701 }
Mike Stump11289f42009-09-09 15:08:12 +00001702
Chris Lattner43be2e62007-12-19 23:59:04 +00001703 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001704 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001705 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001706 else if (Type->isReferenceType()) {
1707 Diag(Arg->getLocStart(),
1708 diag::warn_va_start_of_reference_type_is_undefined);
1709 Diag(ParamLoc, diag::note_parameter_type) << Type;
1710 }
1711
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001712 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001713 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001714}
Chris Lattner43be2e62007-12-19 23:59:04 +00001715
Chris Lattner2da14fb2007-12-20 00:26:33 +00001716/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1717/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001718bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1719 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001720 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001721 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001722 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001723 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001724 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001725 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001726 << SourceRange(TheCall->getArg(2)->getLocStart(),
1727 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001728
John Wiegley01296292011-04-08 18:41:53 +00001729 ExprResult OrigArg0 = TheCall->getArg(0);
1730 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001731
Chris Lattner2da14fb2007-12-20 00:26:33 +00001732 // Do standard promotions between the two arguments, returning their common
1733 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001734 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001735 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1736 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001737
1738 // Make sure any conversions are pushed back into the call; this is
1739 // type safe since unordered compare builtins are declared as "_Bool
1740 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001741 TheCall->setArg(0, OrigArg0.get());
1742 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001743
John Wiegley01296292011-04-08 18:41:53 +00001744 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001745 return false;
1746
Chris Lattner2da14fb2007-12-20 00:26:33 +00001747 // If the common type isn't a real floating type, then the arguments were
1748 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001749 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001750 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001751 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001752 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1753 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001754
Chris Lattner2da14fb2007-12-20 00:26:33 +00001755 return false;
1756}
1757
Benjamin Kramer634fc102010-02-15 22:42:31 +00001758/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1759/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001760/// to check everything. We expect the last argument to be a floating point
1761/// value.
1762bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1763 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001764 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001765 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001766 if (TheCall->getNumArgs() > NumArgs)
1767 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001768 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001769 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001770 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001771 (*(TheCall->arg_end()-1))->getLocEnd());
1772
Benjamin Kramer64aae502010-02-16 10:07:31 +00001773 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001774
Eli Friedman7e4faac2009-08-31 20:06:00 +00001775 if (OrigArg->isTypeDependent())
1776 return false;
1777
Chris Lattner68784ef2010-05-06 05:50:07 +00001778 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001779 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001780 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001781 diag::err_typecheck_call_invalid_unary_fp)
1782 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001783
Chris Lattner68784ef2010-05-06 05:50:07 +00001784 // If this is an implicit conversion from float -> double, remove it.
1785 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1786 Expr *CastArg = Cast->getSubExpr();
1787 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1788 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1789 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001790 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001791 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001792 }
1793 }
1794
Eli Friedman7e4faac2009-08-31 20:06:00 +00001795 return false;
1796}
1797
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001798/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1799// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001800ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001801 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001802 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001803 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001804 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1805 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001806
Nate Begemana0110022010-06-08 00:16:34 +00001807 // Determine which of the following types of shufflevector we're checking:
1808 // 1) unary, vector mask: (lhs, mask)
1809 // 2) binary, vector mask: (lhs, rhs, mask)
1810 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1811 QualType resType = TheCall->getArg(0)->getType();
1812 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001813
Douglas Gregorc25f7662009-05-19 22:10:17 +00001814 if (!TheCall->getArg(0)->isTypeDependent() &&
1815 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001816 QualType LHSType = TheCall->getArg(0)->getType();
1817 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001818
Craig Topperbaca3892013-07-29 06:47:04 +00001819 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1820 return ExprError(Diag(TheCall->getLocStart(),
1821 diag::err_shufflevector_non_vector)
1822 << SourceRange(TheCall->getArg(0)->getLocStart(),
1823 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001824
Nate Begemana0110022010-06-08 00:16:34 +00001825 numElements = LHSType->getAs<VectorType>()->getNumElements();
1826 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001827
Nate Begemana0110022010-06-08 00:16:34 +00001828 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1829 // with mask. If so, verify that RHS is an integer vector type with the
1830 // same number of elts as lhs.
1831 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001832 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001833 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001834 return ExprError(Diag(TheCall->getLocStart(),
1835 diag::err_shufflevector_incompatible_vector)
1836 << SourceRange(TheCall->getArg(1)->getLocStart(),
1837 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001838 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001839 return ExprError(Diag(TheCall->getLocStart(),
1840 diag::err_shufflevector_incompatible_vector)
1841 << SourceRange(TheCall->getArg(0)->getLocStart(),
1842 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001843 } else if (numElements != numResElements) {
1844 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001845 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001846 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001847 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001848 }
1849
1850 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001851 if (TheCall->getArg(i)->isTypeDependent() ||
1852 TheCall->getArg(i)->isValueDependent())
1853 continue;
1854
Nate Begemana0110022010-06-08 00:16:34 +00001855 llvm::APSInt Result(32);
1856 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1857 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001858 diag::err_shufflevector_nonconstant_argument)
1859 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001860
Craig Topper50ad5b72013-08-03 17:40:38 +00001861 // Allow -1 which will be translated to undef in the IR.
1862 if (Result.isSigned() && Result.isAllOnesValue())
1863 continue;
1864
Chris Lattner7ab824e2008-08-10 02:05:13 +00001865 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001866 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001867 diag::err_shufflevector_argument_too_large)
1868 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001869 }
1870
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001871 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001872
Chris Lattner7ab824e2008-08-10 02:05:13 +00001873 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001874 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001875 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001876 }
1877
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001878 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1879 TheCall->getCallee()->getLocStart(),
1880 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001881}
Chris Lattner43be2e62007-12-19 23:59:04 +00001882
Hal Finkelc4d7c822013-09-18 03:29:45 +00001883/// SemaConvertVectorExpr - Handle __builtin_convertvector
1884ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1885 SourceLocation BuiltinLoc,
1886 SourceLocation RParenLoc) {
1887 ExprValueKind VK = VK_RValue;
1888 ExprObjectKind OK = OK_Ordinary;
1889 QualType DstTy = TInfo->getType();
1890 QualType SrcTy = E->getType();
1891
1892 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1893 return ExprError(Diag(BuiltinLoc,
1894 diag::err_convertvector_non_vector)
1895 << E->getSourceRange());
1896 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1897 return ExprError(Diag(BuiltinLoc,
1898 diag::err_convertvector_non_vector_type));
1899
1900 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1901 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1902 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1903 if (SrcElts != DstElts)
1904 return ExprError(Diag(BuiltinLoc,
1905 diag::err_convertvector_incompatible_vector)
1906 << E->getSourceRange());
1907 }
1908
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001909 return new (Context)
1910 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001911}
1912
Daniel Dunbarb7257262008-07-21 22:59:13 +00001913/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1914// This is declared to take (const void*, ...) and can take two
1915// optional constant int args.
1916bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001917 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001918
Chris Lattner3b054132008-11-19 05:08:23 +00001919 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001920 return Diag(TheCall->getLocEnd(),
1921 diag::err_typecheck_call_too_many_args_at_most)
1922 << 0 /*function call*/ << 3 << NumArgs
1923 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001924
1925 // Argument 0 is checked for us and the remaining arguments must be
1926 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001927 for (unsigned i = 1; i != NumArgs; ++i)
1928 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001929 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001930
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001931 return false;
1932}
1933
Eric Christopher8d0c6212010-04-17 02:26:23 +00001934/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1935/// TheCall is a constant expression.
1936bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1937 llvm::APSInt &Result) {
1938 Expr *Arg = TheCall->getArg(ArgNum);
1939 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1940 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1941
1942 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1943
1944 if (!Arg->isIntegerConstantExpr(Result, Context))
1945 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001946 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001947
Chris Lattnerd545ad12009-09-23 06:06:36 +00001948 return false;
1949}
1950
Richard Sandiford28940af2014-04-16 08:47:51 +00001951/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1952/// TheCall is a constant expression in the range [Low, High].
1953bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1954 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001955 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001956
1957 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001958 Expr *Arg = TheCall->getArg(ArgNum);
1959 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001960 return false;
1961
Eric Christopher8d0c6212010-04-17 02:26:23 +00001962 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00001963 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001964 return true;
1965
Richard Sandiford28940af2014-04-16 08:47:51 +00001966 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00001967 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00001968 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001969
1970 return false;
1971}
1972
Eli Friedmanc97d0142009-05-03 06:04:26 +00001973/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001974/// This checks that val is a constant 1.
1975bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1976 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001977 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001978
Eric Christopher8d0c6212010-04-17 02:26:23 +00001979 // TODO: This is less than ideal. Overload this to take a value.
1980 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1981 return true;
1982
1983 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001984 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1985 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1986
1987 return false;
1988}
1989
Richard Smithd7293d72013-08-05 18:49:43 +00001990namespace {
1991enum StringLiteralCheckType {
1992 SLCT_NotALiteral,
1993 SLCT_UncheckedLiteral,
1994 SLCT_CheckedLiteral
1995};
1996}
1997
Richard Smith55ce3522012-06-25 20:30:08 +00001998// Determine if an expression is a string literal or constant string.
1999// If this function returns false on the arguments to a function expecting a
2000// format string, we will usually need to emit a warning.
2001// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002002static StringLiteralCheckType
2003checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2004 bool HasVAListArg, unsigned format_idx,
2005 unsigned firstDataArg, Sema::FormatStringType Type,
2006 Sema::VariadicCallType CallType, bool InFunctionCall,
2007 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002008 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002009 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002010 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002011
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002012 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002013
Richard Smithd7293d72013-08-05 18:49:43 +00002014 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002015 // Technically -Wformat-nonliteral does not warn about this case.
2016 // The behavior of printf and friends in this case is implementation
2017 // dependent. Ideally if the format string cannot be null then
2018 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002019 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002020
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002021 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002022 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002023 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002024 // The expression is a literal if both sub-expressions were, and it was
2025 // completely checked only if both sub-expressions were checked.
2026 const AbstractConditionalOperator *C =
2027 cast<AbstractConditionalOperator>(E);
2028 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002029 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002030 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002031 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002032 if (Left == SLCT_NotALiteral)
2033 return SLCT_NotALiteral;
2034 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002035 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002036 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002037 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002038 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002039 }
2040
2041 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002042 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2043 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002044 }
2045
John McCallc07a0c72011-02-17 10:25:35 +00002046 case Stmt::OpaqueValueExprClass:
2047 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2048 E = src;
2049 goto tryAgain;
2050 }
Richard Smith55ce3522012-06-25 20:30:08 +00002051 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002052
Ted Kremeneka8890832011-02-24 23:03:04 +00002053 case Stmt::PredefinedExprClass:
2054 // While __func__, etc., are technically not string literals, they
2055 // cannot contain format specifiers and thus are not a security
2056 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002057 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002058
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002059 case Stmt::DeclRefExprClass: {
2060 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002062 // As an exception, do not flag errors for variables binding to
2063 // const string literals.
2064 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2065 bool isConstant = false;
2066 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002067
Richard Smithd7293d72013-08-05 18:49:43 +00002068 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2069 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002070 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002071 isConstant = T.isConstant(S.Context) &&
2072 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002073 } else if (T->isObjCObjectPointerType()) {
2074 // In ObjC, there is usually no "const ObjectPointer" type,
2075 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002076 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002079 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002080 if (const Expr *Init = VD->getAnyInitializer()) {
2081 // Look through initializers like const char c[] = { "foo" }
2082 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2083 if (InitList->isStringLiteralInit())
2084 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2085 }
Richard Smithd7293d72013-08-05 18:49:43 +00002086 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002087 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002088 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002089 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002090 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002091 }
Mike Stump11289f42009-09-09 15:08:12 +00002092
Anders Carlssonb012ca92009-06-28 19:55:58 +00002093 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2094 // special check to see if the format string is a function parameter
2095 // of the function calling the printf function. If the function
2096 // has an attribute indicating it is a printf-like function, then we
2097 // should suppress warnings concerning non-literals being used in a call
2098 // to a vprintf function. For example:
2099 //
2100 // void
2101 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2102 // va_list ap;
2103 // va_start(ap, fmt);
2104 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2105 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002106 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002107 if (HasVAListArg) {
2108 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2109 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2110 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002111 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002112 // adjust for implicit parameter
2113 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2114 if (MD->isInstance())
2115 ++PVIndex;
2116 // We also check if the formats are compatible.
2117 // We can't pass a 'scanf' string to a 'printf' function.
2118 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002119 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002120 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002121 }
2122 }
2123 }
2124 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Richard Smith55ce3522012-06-25 20:30:08 +00002127 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002128 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002129
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002130 case Stmt::CallExprClass:
2131 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002132 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002133 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2134 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2135 unsigned ArgIndex = FA->getFormatIdx();
2136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2137 if (MD->isInstance())
2138 --ArgIndex;
2139 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002140
Richard Smithd7293d72013-08-05 18:49:43 +00002141 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002142 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002143 Type, CallType, InFunctionCall,
2144 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002145 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2146 unsigned BuiltinID = FD->getBuiltinID();
2147 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2148 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2149 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002150 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002151 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002152 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002153 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002154 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002155 }
2156 }
Mike Stump11289f42009-09-09 15:08:12 +00002157
Richard Smith55ce3522012-06-25 20:30:08 +00002158 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002159 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002160 case Stmt::ObjCStringLiteralClass:
2161 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002162 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002165 StrE = ObjCFExpr->getString();
2166 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002167 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002168
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002169 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002170 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2171 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002172 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002173 }
Mike Stump11289f42009-09-09 15:08:12 +00002174
Richard Smith55ce3522012-06-25 20:30:08 +00002175 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002176 }
Mike Stump11289f42009-09-09 15:08:12 +00002177
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002178 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002179 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002180 }
2181}
2182
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002183Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002184 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002185 .Case("scanf", FST_Scanf)
2186 .Cases("printf", "printf0", FST_Printf)
2187 .Cases("NSString", "CFString", FST_NSString)
2188 .Case("strftime", FST_Strftime)
2189 .Case("strfmon", FST_Strfmon)
2190 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2191 .Default(FST_Unknown);
2192}
2193
Jordan Rose3e0ec582012-07-19 18:10:23 +00002194/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002195/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002196/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002197bool Sema::CheckFormatArguments(const FormatAttr *Format,
2198 ArrayRef<const Expr *> Args,
2199 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002200 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002201 SourceLocation Loc, SourceRange Range,
2202 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002203 FormatStringInfo FSI;
2204 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002205 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002206 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002207 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002208 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002209}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002210
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002211bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002212 bool HasVAListArg, unsigned format_idx,
2213 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002214 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002215 SourceLocation Loc, SourceRange Range,
2216 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002217 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002218 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002219 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002220 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002221 }
Mike Stump11289f42009-09-09 15:08:12 +00002222
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002223 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002224
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002225 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002226 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002227 // Dynamically generated format strings are difficult to
2228 // automatically vet at compile time. Requiring that format strings
2229 // are string literals: (1) permits the checking of format strings by
2230 // the compiler and thereby (2) can practically remove the source of
2231 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002232
Mike Stump11289f42009-09-09 15:08:12 +00002233 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002234 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002235 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002236 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002237 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002238 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2239 format_idx, firstDataArg, Type, CallType,
2240 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002241 if (CT != SLCT_NotALiteral)
2242 // Literal format string found, check done!
2243 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002244
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002245 // Strftime is particular as it always uses a single 'time' argument,
2246 // so it is safe to pass a non-literal string.
2247 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002248 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002249
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002250 // Do not emit diag when the string param is a macro expansion and the
2251 // format is either NSString or CFString. This is a hack to prevent
2252 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2253 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002254 if (Type == FST_NSString &&
2255 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002256 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002257
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002258 // If there are no arguments specified, warn with -Wformat-security, otherwise
2259 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002260 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002261 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002262 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002263 << OrigFormatExpr->getSourceRange();
2264 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002265 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002266 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002267 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002268 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002269}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002270
Ted Kremenekab278de2010-01-28 23:39:18 +00002271namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002272class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2273protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002274 Sema &S;
2275 const StringLiteral *FExpr;
2276 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002277 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002278 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002279 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002280 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002281 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002282 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002283 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002284 bool usesPositionalArgs;
2285 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002286 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002287 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002288 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002289public:
Ted Kremenek02087932010-07-16 02:11:22 +00002290 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002291 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002292 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002293 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002294 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002295 Sema::VariadicCallType callType,
2296 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002297 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002298 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2299 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002300 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002301 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002302 inFunctionCall(inFunctionCall), CallType(callType),
2303 CheckedVarArgs(CheckedVarArgs) {
2304 CoveredArgs.resize(numDataArgs);
2305 CoveredArgs.reset();
2306 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002307
Ted Kremenek019d2242010-01-29 01:50:07 +00002308 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002309
Ted Kremenek02087932010-07-16 02:11:22 +00002310 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002311 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002312
Jordan Rose92303592012-09-08 04:00:03 +00002313 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002314 const analyze_format_string::FormatSpecifier &FS,
2315 const analyze_format_string::ConversionSpecifier &CS,
2316 const char *startSpecifier, unsigned specifierLen,
2317 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002318
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002319 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002320 const analyze_format_string::FormatSpecifier &FS,
2321 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002322
2323 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002324 const analyze_format_string::ConversionSpecifier &CS,
2325 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002326
Craig Toppere14c0f82014-03-12 04:55:44 +00002327 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002328
Craig Toppere14c0f82014-03-12 04:55:44 +00002329 void HandleInvalidPosition(const char *startSpecifier,
2330 unsigned specifierLen,
2331 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002332
Craig Toppere14c0f82014-03-12 04:55:44 +00002333 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002334
Craig Toppere14c0f82014-03-12 04:55:44 +00002335 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002336
Richard Trieu03cf7b72011-10-28 00:41:25 +00002337 template <typename Range>
2338 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2339 const Expr *ArgumentExpr,
2340 PartialDiagnostic PDiag,
2341 SourceLocation StringLoc,
2342 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002343 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002344
Ted Kremenek02087932010-07-16 02:11:22 +00002345protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002346 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2347 const char *startSpec,
2348 unsigned specifierLen,
2349 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002350
2351 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2352 const char *startSpec,
2353 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002354
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002355 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002356 CharSourceRange getSpecifierRange(const char *startSpecifier,
2357 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002358 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002359
Ted Kremenek5739de72010-01-29 01:06:55 +00002360 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002361
2362 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2363 const analyze_format_string::ConversionSpecifier &CS,
2364 const char *startSpecifier, unsigned specifierLen,
2365 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002366
2367 template <typename Range>
2368 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2369 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002370 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002371};
2372}
2373
Ted Kremenek02087932010-07-16 02:11:22 +00002374SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002375 return OrigFormatExpr->getSourceRange();
2376}
2377
Ted Kremenek02087932010-07-16 02:11:22 +00002378CharSourceRange CheckFormatHandler::
2379getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002380 SourceLocation Start = getLocationOfByte(startSpecifier);
2381 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2382
2383 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002384 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002385
2386 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002387}
2388
Ted Kremenek02087932010-07-16 02:11:22 +00002389SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002390 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002391}
2392
Ted Kremenek02087932010-07-16 02:11:22 +00002393void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2394 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002395 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2396 getLocationOfByte(startSpecifier),
2397 /*IsStringLocation*/true,
2398 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002399}
2400
Jordan Rose92303592012-09-08 04:00:03 +00002401void CheckFormatHandler::HandleInvalidLengthModifier(
2402 const analyze_format_string::FormatSpecifier &FS,
2403 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002404 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002405 using namespace analyze_format_string;
2406
2407 const LengthModifier &LM = FS.getLengthModifier();
2408 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2409
2410 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002411 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002412 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002413 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002414 getLocationOfByte(LM.getStart()),
2415 /*IsStringLocation*/true,
2416 getSpecifierRange(startSpecifier, specifierLen));
2417
2418 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2419 << FixedLM->toString()
2420 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2421
2422 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002423 FixItHint Hint;
2424 if (DiagID == diag::warn_format_nonsensical_length)
2425 Hint = FixItHint::CreateRemoval(LMRange);
2426
2427 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002428 getLocationOfByte(LM.getStart()),
2429 /*IsStringLocation*/true,
2430 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002431 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002432 }
2433}
2434
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002435void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002436 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002437 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002438 using namespace analyze_format_string;
2439
2440 const LengthModifier &LM = FS.getLengthModifier();
2441 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2442
2443 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002444 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002445 if (FixedLM) {
2446 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2447 << LM.toString() << 0,
2448 getLocationOfByte(LM.getStart()),
2449 /*IsStringLocation*/true,
2450 getSpecifierRange(startSpecifier, specifierLen));
2451
2452 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2453 << FixedLM->toString()
2454 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2455
2456 } else {
2457 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2458 << LM.toString() << 0,
2459 getLocationOfByte(LM.getStart()),
2460 /*IsStringLocation*/true,
2461 getSpecifierRange(startSpecifier, specifierLen));
2462 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002463}
2464
2465void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2466 const analyze_format_string::ConversionSpecifier &CS,
2467 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002468 using namespace analyze_format_string;
2469
2470 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002471 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002472 if (FixedCS) {
2473 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2474 << CS.toString() << /*conversion specifier*/1,
2475 getLocationOfByte(CS.getStart()),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startSpecifier, specifierLen));
2478
2479 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2480 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2481 << FixedCS->toString()
2482 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2483 } else {
2484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2485 << CS.toString() << /*conversion specifier*/1,
2486 getLocationOfByte(CS.getStart()),
2487 /*IsStringLocation*/true,
2488 getSpecifierRange(startSpecifier, specifierLen));
2489 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002490}
2491
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002492void CheckFormatHandler::HandlePosition(const char *startPos,
2493 unsigned posLen) {
2494 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2495 getLocationOfByte(startPos),
2496 /*IsStringLocation*/true,
2497 getSpecifierRange(startPos, posLen));
2498}
2499
Ted Kremenekd1668192010-02-27 01:41:03 +00002500void
Ted Kremenek02087932010-07-16 02:11:22 +00002501CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2502 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2504 << (unsigned) p,
2505 getLocationOfByte(startPos), /*IsStringLocation*/true,
2506 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002507}
2508
Ted Kremenek02087932010-07-16 02:11:22 +00002509void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002510 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2512 getLocationOfByte(startPos),
2513 /*IsStringLocation*/true,
2514 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002515}
2516
Ted Kremenek02087932010-07-16 02:11:22 +00002517void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002518 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002519 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002520 EmitFormatDiagnostic(
2521 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2522 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2523 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002524 }
Ted Kremenek02087932010-07-16 02:11:22 +00002525}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002526
Jordan Rose58bbe422012-07-19 18:10:08 +00002527// Note that this may return NULL if there was an error parsing or building
2528// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002529const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002530 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002531}
2532
2533void CheckFormatHandler::DoneProcessing() {
2534 // Does the number of data arguments exceed the number of
2535 // format conversions in the format string?
2536 if (!HasVAListArg) {
2537 // Find any arguments that weren't covered.
2538 CoveredArgs.flip();
2539 signed notCoveredArg = CoveredArgs.find_first();
2540 if (notCoveredArg >= 0) {
2541 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002542 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2543 SourceLocation Loc = E->getLocStart();
2544 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2545 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2546 Loc, /*IsStringLocation*/false,
2547 getFormatStringRange());
2548 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002549 }
Ted Kremenek02087932010-07-16 02:11:22 +00002550 }
2551 }
2552}
2553
Ted Kremenekce815422010-07-19 21:25:57 +00002554bool
2555CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2556 SourceLocation Loc,
2557 const char *startSpec,
2558 unsigned specifierLen,
2559 const char *csStart,
2560 unsigned csLen) {
2561
2562 bool keepGoing = true;
2563 if (argIndex < NumDataArgs) {
2564 // Consider the argument coverered, even though the specifier doesn't
2565 // make sense.
2566 CoveredArgs.set(argIndex);
2567 }
2568 else {
2569 // If argIndex exceeds the number of data arguments we
2570 // don't issue a warning because that is just a cascade of warnings (and
2571 // they may have intended '%%' anyway). We don't want to continue processing
2572 // the format string after this point, however, as we will like just get
2573 // gibberish when trying to match arguments.
2574 keepGoing = false;
2575 }
2576
Richard Trieu03cf7b72011-10-28 00:41:25 +00002577 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2578 << StringRef(csStart, csLen),
2579 Loc, /*IsStringLocation*/true,
2580 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002581
2582 return keepGoing;
2583}
2584
Richard Trieu03cf7b72011-10-28 00:41:25 +00002585void
2586CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2587 const char *startSpec,
2588 unsigned specifierLen) {
2589 EmitFormatDiagnostic(
2590 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2591 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2592}
2593
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002594bool
2595CheckFormatHandler::CheckNumArgs(
2596 const analyze_format_string::FormatSpecifier &FS,
2597 const analyze_format_string::ConversionSpecifier &CS,
2598 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2599
2600 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002601 PartialDiagnostic PDiag = FS.usesPositionalArg()
2602 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2603 << (argIndex+1) << NumDataArgs)
2604 : S.PDiag(diag::warn_printf_insufficient_data_args);
2605 EmitFormatDiagnostic(
2606 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2607 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002608 return false;
2609 }
2610 return true;
2611}
2612
Richard Trieu03cf7b72011-10-28 00:41:25 +00002613template<typename Range>
2614void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2615 SourceLocation Loc,
2616 bool IsStringLocation,
2617 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002618 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002619 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002620 Loc, IsStringLocation, StringRange, FixIt);
2621}
2622
2623/// \brief If the format string is not within the funcion call, emit a note
2624/// so that the function call and string are in diagnostic messages.
2625///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002626/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002627/// call and only one diagnostic message will be produced. Otherwise, an
2628/// extra note will be emitted pointing to location of the format string.
2629///
2630/// \param ArgumentExpr the expression that is passed as the format string
2631/// argument in the function call. Used for getting locations when two
2632/// diagnostics are emitted.
2633///
2634/// \param PDiag the callee should already have provided any strings for the
2635/// diagnostic message. This function only adds locations and fixits
2636/// to diagnostics.
2637///
2638/// \param Loc primary location for diagnostic. If two diagnostics are
2639/// required, one will be at Loc and a new SourceLocation will be created for
2640/// the other one.
2641///
2642/// \param IsStringLocation if true, Loc points to the format string should be
2643/// used for the note. Otherwise, Loc points to the argument list and will
2644/// be used with PDiag.
2645///
2646/// \param StringRange some or all of the string to highlight. This is
2647/// templated so it can accept either a CharSourceRange or a SourceRange.
2648///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002649/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002650template<typename Range>
2651void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2652 const Expr *ArgumentExpr,
2653 PartialDiagnostic PDiag,
2654 SourceLocation Loc,
2655 bool IsStringLocation,
2656 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002657 ArrayRef<FixItHint> FixIt) {
2658 if (InFunctionCall) {
2659 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2660 D << StringRange;
2661 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2662 I != E; ++I) {
2663 D << *I;
2664 }
2665 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002666 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2667 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002668
2669 const Sema::SemaDiagnosticBuilder &Note =
2670 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2671 diag::note_format_string_defined);
2672
2673 Note << StringRange;
2674 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2675 I != E; ++I) {
2676 Note << *I;
2677 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002678 }
2679}
2680
Ted Kremenek02087932010-07-16 02:11:22 +00002681//===--- CHECK: Printf format string checking ------------------------------===//
2682
2683namespace {
2684class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002685 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002686public:
2687 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2688 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002689 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002690 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002691 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002692 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002693 Sema::VariadicCallType CallType,
2694 llvm::SmallBitVector &CheckedVarArgs)
2695 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2696 numDataArgs, beg, hasVAListArg, Args,
2697 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2698 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002699 {}
2700
Craig Toppere14c0f82014-03-12 04:55:44 +00002701
Ted Kremenek02087932010-07-16 02:11:22 +00002702 bool HandleInvalidPrintfConversionSpecifier(
2703 const analyze_printf::PrintfSpecifier &FS,
2704 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002705 unsigned specifierLen) override;
2706
Ted Kremenek02087932010-07-16 02:11:22 +00002707 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2708 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002709 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002710 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2711 const char *StartSpecifier,
2712 unsigned SpecifierLen,
2713 const Expr *E);
2714
Ted Kremenek02087932010-07-16 02:11:22 +00002715 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2716 const char *startSpecifier, unsigned specifierLen);
2717 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2718 const analyze_printf::OptionalAmount &Amt,
2719 unsigned type,
2720 const char *startSpecifier, unsigned specifierLen);
2721 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2722 const analyze_printf::OptionalFlag &flag,
2723 const char *startSpecifier, unsigned specifierLen);
2724 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2725 const analyze_printf::OptionalFlag &ignoredFlag,
2726 const analyze_printf::OptionalFlag &flag,
2727 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002728 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002729 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002730
Ted Kremenek02087932010-07-16 02:11:22 +00002731};
2732}
2733
2734bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2735 const analyze_printf::PrintfSpecifier &FS,
2736 const char *startSpecifier,
2737 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002738 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002739 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002740
Ted Kremenekce815422010-07-19 21:25:57 +00002741 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2742 getLocationOfByte(CS.getStart()),
2743 startSpecifier, specifierLen,
2744 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002745}
2746
Ted Kremenek02087932010-07-16 02:11:22 +00002747bool CheckPrintfHandler::HandleAmount(
2748 const analyze_format_string::OptionalAmount &Amt,
2749 unsigned k, const char *startSpecifier,
2750 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002751
2752 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002753 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002754 unsigned argIndex = Amt.getArgIndex();
2755 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002756 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2757 << k,
2758 getLocationOfByte(Amt.getStart()),
2759 /*IsStringLocation*/true,
2760 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002761 // Don't do any more checking. We will just emit
2762 // spurious errors.
2763 return false;
2764 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002765
Ted Kremenek5739de72010-01-29 01:06:55 +00002766 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002767 // Although not in conformance with C99, we also allow the argument to be
2768 // an 'unsigned int' as that is a reasonably safe case. GCC also
2769 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002770 CoveredArgs.set(argIndex);
2771 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002772 if (!Arg)
2773 return false;
2774
Ted Kremenek5739de72010-01-29 01:06:55 +00002775 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002776
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002777 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2778 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002779
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002780 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002781 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002782 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002783 << T << Arg->getSourceRange(),
2784 getLocationOfByte(Amt.getStart()),
2785 /*IsStringLocation*/true,
2786 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002787 // Don't do any more checking. We will just emit
2788 // spurious errors.
2789 return false;
2790 }
2791 }
2792 }
2793 return true;
2794}
Ted Kremenek5739de72010-01-29 01:06:55 +00002795
Tom Careb49ec692010-06-17 19:00:27 +00002796void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002797 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002798 const analyze_printf::OptionalAmount &Amt,
2799 unsigned type,
2800 const char *startSpecifier,
2801 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002802 const analyze_printf::PrintfConversionSpecifier &CS =
2803 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002804
Richard Trieu03cf7b72011-10-28 00:41:25 +00002805 FixItHint fixit =
2806 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2807 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2808 Amt.getConstantLength()))
2809 : FixItHint();
2810
2811 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2812 << type << CS.toString(),
2813 getLocationOfByte(Amt.getStart()),
2814 /*IsStringLocation*/true,
2815 getSpecifierRange(startSpecifier, specifierLen),
2816 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002817}
2818
Ted Kremenek02087932010-07-16 02:11:22 +00002819void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002820 const analyze_printf::OptionalFlag &flag,
2821 const char *startSpecifier,
2822 unsigned specifierLen) {
2823 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002824 const analyze_printf::PrintfConversionSpecifier &CS =
2825 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002826 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2827 << flag.toString() << CS.toString(),
2828 getLocationOfByte(flag.getPosition()),
2829 /*IsStringLocation*/true,
2830 getSpecifierRange(startSpecifier, specifierLen),
2831 FixItHint::CreateRemoval(
2832 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002833}
2834
2835void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002836 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002837 const analyze_printf::OptionalFlag &ignoredFlag,
2838 const analyze_printf::OptionalFlag &flag,
2839 const char *startSpecifier,
2840 unsigned specifierLen) {
2841 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2843 << ignoredFlag.toString() << flag.toString(),
2844 getLocationOfByte(ignoredFlag.getPosition()),
2845 /*IsStringLocation*/true,
2846 getSpecifierRange(startSpecifier, specifierLen),
2847 FixItHint::CreateRemoval(
2848 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002849}
2850
Richard Smith55ce3522012-06-25 20:30:08 +00002851// Determines if the specified is a C++ class or struct containing
2852// a member with the specified name and kind (e.g. a CXXMethodDecl named
2853// "c_str()").
2854template<typename MemberKind>
2855static llvm::SmallPtrSet<MemberKind*, 1>
2856CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2857 const RecordType *RT = Ty->getAs<RecordType>();
2858 llvm::SmallPtrSet<MemberKind*, 1> Results;
2859
2860 if (!RT)
2861 return Results;
2862 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002863 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002864 return Results;
2865
Alp Tokerb6cc5922014-05-03 03:45:55 +00002866 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002867 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002868 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002869
2870 // We just need to include all members of the right kind turned up by the
2871 // filter, at this point.
2872 if (S.LookupQualifiedName(R, RT->getDecl()))
2873 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2874 NamedDecl *decl = (*I)->getUnderlyingDecl();
2875 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2876 Results.insert(FK);
2877 }
2878 return Results;
2879}
2880
Richard Smith2868a732014-02-28 01:36:39 +00002881/// Check if we could call '.c_str()' on an object.
2882///
2883/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2884/// allow the call, or if it would be ambiguous).
2885bool Sema::hasCStrMethod(const Expr *E) {
2886 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2887 MethodSet Results =
2888 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2889 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2890 MI != ME; ++MI)
2891 if ((*MI)->getMinRequiredArguments() == 0)
2892 return true;
2893 return false;
2894}
2895
Richard Smith55ce3522012-06-25 20:30:08 +00002896// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002897// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002898// Returns true when a c_str() conversion method is found.
2899bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002900 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002901 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2902
2903 MethodSet Results =
2904 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2905
2906 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2907 MI != ME; ++MI) {
2908 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002909 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002910 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002911 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002912 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002913 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2914 << "c_str()"
2915 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2916 return true;
2917 }
2918 }
2919
2920 return false;
2921}
2922
Ted Kremenekab278de2010-01-28 23:39:18 +00002923bool
Ted Kremenek02087932010-07-16 02:11:22 +00002924CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002925 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002926 const char *startSpecifier,
2927 unsigned specifierLen) {
2928
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002929 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002930 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002931 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002932
Ted Kremenek6cd69422010-07-19 22:01:06 +00002933 if (FS.consumesDataArgument()) {
2934 if (atFirstArg) {
2935 atFirstArg = false;
2936 usesPositionalArgs = FS.usesPositionalArg();
2937 }
2938 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002939 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2940 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002941 return false;
2942 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002943 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002944
Ted Kremenekd1668192010-02-27 01:41:03 +00002945 // First check if the field width, precision, and conversion specifier
2946 // have matching data arguments.
2947 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2948 startSpecifier, specifierLen)) {
2949 return false;
2950 }
2951
2952 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2953 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002954 return false;
2955 }
2956
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002957 if (!CS.consumesDataArgument()) {
2958 // FIXME: Technically specifying a precision or field width here
2959 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002960 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002961 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002962
Ted Kremenek4a49d982010-02-26 19:18:41 +00002963 // Consume the argument.
2964 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002965 if (argIndex < NumDataArgs) {
2966 // The check to see if the argIndex is valid will come later.
2967 // We set the bit here because we may exit early from this
2968 // function if we encounter some other error.
2969 CoveredArgs.set(argIndex);
2970 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002971
2972 // Check for using an Objective-C specific conversion specifier
2973 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002974 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002975 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2976 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002977 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002978
Tom Careb49ec692010-06-17 19:00:27 +00002979 // Check for invalid use of field width
2980 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002981 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002982 startSpecifier, specifierLen);
2983 }
2984
2985 // Check for invalid use of precision
2986 if (!FS.hasValidPrecision()) {
2987 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2988 startSpecifier, specifierLen);
2989 }
2990
2991 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002992 if (!FS.hasValidThousandsGroupingPrefix())
2993 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002994 if (!FS.hasValidLeadingZeros())
2995 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2996 if (!FS.hasValidPlusPrefix())
2997 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002998 if (!FS.hasValidSpacePrefix())
2999 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003000 if (!FS.hasValidAlternativeForm())
3001 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3002 if (!FS.hasValidLeftJustified())
3003 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3004
3005 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003006 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3007 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3008 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003009 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3010 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3011 startSpecifier, specifierLen);
3012
3013 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003014 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003015 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3016 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003017 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003018 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003019 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003020 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3021 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003022
Jordan Rose92303592012-09-08 04:00:03 +00003023 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3024 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3025
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003026 // The remaining checks depend on the data arguments.
3027 if (HasVAListArg)
3028 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003029
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003030 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003031 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003032
Jordan Rose58bbe422012-07-19 18:10:08 +00003033 const Expr *Arg = getDataArg(argIndex);
3034 if (!Arg)
3035 return true;
3036
3037 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003038}
3039
Jordan Roseaee34382012-09-05 22:56:26 +00003040static bool requiresParensToAddCast(const Expr *E) {
3041 // FIXME: We should have a general way to reason about operator
3042 // precedence and whether parens are actually needed here.
3043 // Take care of a few common cases where they aren't.
3044 const Expr *Inside = E->IgnoreImpCasts();
3045 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3046 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3047
3048 switch (Inside->getStmtClass()) {
3049 case Stmt::ArraySubscriptExprClass:
3050 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003051 case Stmt::CharacterLiteralClass:
3052 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003053 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003054 case Stmt::FloatingLiteralClass:
3055 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003056 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003057 case Stmt::ObjCArrayLiteralClass:
3058 case Stmt::ObjCBoolLiteralExprClass:
3059 case Stmt::ObjCBoxedExprClass:
3060 case Stmt::ObjCDictionaryLiteralClass:
3061 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003062 case Stmt::ObjCIvarRefExprClass:
3063 case Stmt::ObjCMessageExprClass:
3064 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003065 case Stmt::ObjCStringLiteralClass:
3066 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003067 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003068 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003069 case Stmt::UnaryOperatorClass:
3070 return false;
3071 default:
3072 return true;
3073 }
3074}
3075
Richard Smith55ce3522012-06-25 20:30:08 +00003076bool
3077CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3078 const char *StartSpecifier,
3079 unsigned SpecifierLen,
3080 const Expr *E) {
3081 using namespace analyze_format_string;
3082 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003083 // Now type check the data expression that matches the
3084 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003085 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3086 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003087 if (!AT.isValid())
3088 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003089
Jordan Rose598ec092012-12-05 18:44:40 +00003090 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003091 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3092 ExprTy = TET->getUnderlyingExpr()->getType();
3093 }
3094
Jordan Rose598ec092012-12-05 18:44:40 +00003095 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003096 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003097
Jordan Rose22b74712012-09-05 22:56:19 +00003098 // Look through argument promotions for our error message's reported type.
3099 // This includes the integral and floating promotions, but excludes array
3100 // and function pointer decay; seeing that an argument intended to be a
3101 // string has type 'char [6]' is probably more confusing than 'char *'.
3102 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3103 if (ICE->getCastKind() == CK_IntegralCast ||
3104 ICE->getCastKind() == CK_FloatingCast) {
3105 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003106 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003107
3108 // Check if we didn't match because of an implicit cast from a 'char'
3109 // or 'short' to an 'int'. This is done because printf is a varargs
3110 // function.
3111 if (ICE->getType() == S.Context.IntTy ||
3112 ICE->getType() == S.Context.UnsignedIntTy) {
3113 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003114 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003115 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003116 }
Jordan Rose98709982012-06-04 22:48:57 +00003117 }
Jordan Rose598ec092012-12-05 18:44:40 +00003118 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3119 // Special case for 'a', which has type 'int' in C.
3120 // Note, however, that we do /not/ want to treat multibyte constants like
3121 // 'MooV' as characters! This form is deprecated but still exists.
3122 if (ExprTy == S.Context.IntTy)
3123 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3124 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003125 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003126
Jordan Rosebc53ed12014-05-31 04:12:14 +00003127 // Look through enums to their underlying type.
3128 bool IsEnum = false;
3129 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3130 ExprTy = EnumTy->getDecl()->getIntegerType();
3131 IsEnum = true;
3132 }
3133
Jordan Rose0e5badd2012-12-05 18:44:49 +00003134 // %C in an Objective-C context prints a unichar, not a wchar_t.
3135 // If the argument is an integer of some kind, believe the %C and suggest
3136 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003137 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003138 if (ObjCContext &&
3139 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3140 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3141 !ExprTy->isCharType()) {
3142 // 'unichar' is defined as a typedef of unsigned short, but we should
3143 // prefer using the typedef if it is visible.
3144 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003145
3146 // While we are here, check if the value is an IntegerLiteral that happens
3147 // to be within the valid range.
3148 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3149 const llvm::APInt &V = IL->getValue();
3150 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3151 return true;
3152 }
3153
Jordan Rose0e5badd2012-12-05 18:44:49 +00003154 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3155 Sema::LookupOrdinaryName);
3156 if (S.LookupName(Result, S.getCurScope())) {
3157 NamedDecl *ND = Result.getFoundDecl();
3158 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3159 if (TD->getUnderlyingType() == IntendedTy)
3160 IntendedTy = S.Context.getTypedefType(TD);
3161 }
3162 }
3163 }
3164
3165 // Special-case some of Darwin's platform-independence types by suggesting
3166 // casts to primitive types that are known to be large enough.
3167 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003168 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003169 // Use a 'while' to peel off layers of typedefs.
3170 QualType TyTy = IntendedTy;
3171 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003172 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003173 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003174 .Case("NSInteger", S.Context.LongTy)
3175 .Case("NSUInteger", S.Context.UnsignedLongTy)
3176 .Case("SInt32", S.Context.IntTy)
3177 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003178 .Default(QualType());
3179
3180 if (!CastTy.isNull()) {
3181 ShouldNotPrintDirectly = true;
3182 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003183 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003184 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003185 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003186 }
3187 }
3188
Jordan Rose22b74712012-09-05 22:56:19 +00003189 // We may be able to offer a FixItHint if it is a supported type.
3190 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003191 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003192 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003193
Jordan Rose22b74712012-09-05 22:56:19 +00003194 if (success) {
3195 // Get the fix string from the fixed format specifier
3196 SmallString<16> buf;
3197 llvm::raw_svector_ostream os(buf);
3198 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003199
Jordan Roseaee34382012-09-05 22:56:26 +00003200 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3201
Jordan Rose0e5badd2012-12-05 18:44:49 +00003202 if (IntendedTy == ExprTy) {
3203 // In this case, the specifier is wrong and should be changed to match
3204 // the argument.
3205 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003206 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3207 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003208 << E->getSourceRange(),
3209 E->getLocStart(),
3210 /*IsStringLocation*/false,
3211 SpecRange,
3212 FixItHint::CreateReplacement(SpecRange, os.str()));
3213
3214 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003215 // The canonical type for formatting this value is different from the
3216 // actual type of the expression. (This occurs, for example, with Darwin's
3217 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3218 // should be printed as 'long' for 64-bit compatibility.)
3219 // Rather than emitting a normal format/argument mismatch, we want to
3220 // add a cast to the recommended type (and correct the format string
3221 // if necessary).
3222 SmallString<16> CastBuf;
3223 llvm::raw_svector_ostream CastFix(CastBuf);
3224 CastFix << "(";
3225 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3226 CastFix << ")";
3227
3228 SmallVector<FixItHint,4> Hints;
3229 if (!AT.matchesType(S.Context, IntendedTy))
3230 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3231
3232 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3233 // If there's already a cast present, just replace it.
3234 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3235 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3236
3237 } else if (!requiresParensToAddCast(E)) {
3238 // If the expression has high enough precedence,
3239 // just write the C-style cast.
3240 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3241 CastFix.str()));
3242 } else {
3243 // Otherwise, add parens around the expression as well as the cast.
3244 CastFix << "(";
3245 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3246 CastFix.str()));
3247
Alp Tokerb6cc5922014-05-03 03:45:55 +00003248 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003249 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3250 }
3251
Jordan Rose0e5badd2012-12-05 18:44:49 +00003252 if (ShouldNotPrintDirectly) {
3253 // The expression has a type that should not be printed directly.
3254 // We extract the name from the typedef because we don't want to show
3255 // the underlying type in the diagnostic.
3256 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003257
Jordan Rose0e5badd2012-12-05 18:44:49 +00003258 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003259 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003260 << E->getSourceRange(),
3261 E->getLocStart(), /*IsStringLocation=*/false,
3262 SpecRange, Hints);
3263 } else {
3264 // In this case, the expression could be printed using a different
3265 // specifier, but we've decided that the specifier is probably correct
3266 // and we should cast instead. Just use the normal warning message.
3267 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003268 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3269 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003270 << E->getSourceRange(),
3271 E->getLocStart(), /*IsStringLocation*/false,
3272 SpecRange, Hints);
3273 }
Jordan Roseaee34382012-09-05 22:56:26 +00003274 }
Jordan Rose22b74712012-09-05 22:56:19 +00003275 } else {
3276 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3277 SpecifierLen);
3278 // Since the warning for passing non-POD types to variadic functions
3279 // was deferred until now, we emit a warning for non-POD
3280 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003281 switch (S.isValidVarArgType(ExprTy)) {
3282 case Sema::VAK_Valid:
3283 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003284 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003285 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3286 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003287 << CSR
3288 << E->getSourceRange(),
3289 E->getLocStart(), /*IsStringLocation*/false, CSR);
3290 break;
3291
3292 case Sema::VAK_Undefined:
3293 EmitFormatDiagnostic(
3294 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003295 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003296 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003297 << CallType
3298 << AT.getRepresentativeTypeName(S.Context)
3299 << CSR
3300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003302 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003303 break;
3304
3305 case Sema::VAK_Invalid:
3306 if (ExprTy->isObjCObjectType())
3307 EmitFormatDiagnostic(
3308 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3309 << S.getLangOpts().CPlusPlus11
3310 << ExprTy
3311 << CallType
3312 << AT.getRepresentativeTypeName(S.Context)
3313 << CSR
3314 << E->getSourceRange(),
3315 E->getLocStart(), /*IsStringLocation*/false, CSR);
3316 else
3317 // FIXME: If this is an initializer list, suggest removing the braces
3318 // or inserting a cast to the target type.
3319 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3320 << isa<InitListExpr>(E) << ExprTy << CallType
3321 << AT.getRepresentativeTypeName(S.Context)
3322 << E->getSourceRange();
3323 break;
3324 }
3325
3326 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3327 "format string specifier index out of range");
3328 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003329 }
3330
Ted Kremenekab278de2010-01-28 23:39:18 +00003331 return true;
3332}
3333
Ted Kremenek02087932010-07-16 02:11:22 +00003334//===--- CHECK: Scanf format string checking ------------------------------===//
3335
3336namespace {
3337class CheckScanfHandler : public CheckFormatHandler {
3338public:
3339 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3340 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003341 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003342 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003343 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003344 Sema::VariadicCallType CallType,
3345 llvm::SmallBitVector &CheckedVarArgs)
3346 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3347 numDataArgs, beg, hasVAListArg,
3348 Args, formatIdx, inFunctionCall, CallType,
3349 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003350 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003351
3352 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3353 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003354 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003355
3356 bool HandleInvalidScanfConversionSpecifier(
3357 const analyze_scanf::ScanfSpecifier &FS,
3358 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003359 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003360
Craig Toppere14c0f82014-03-12 04:55:44 +00003361 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003362};
Ted Kremenek019d2242010-01-29 01:50:07 +00003363}
Ted Kremenekab278de2010-01-28 23:39:18 +00003364
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003365void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3366 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003367 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3368 getLocationOfByte(end), /*IsStringLocation*/true,
3369 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003370}
3371
Ted Kremenekce815422010-07-19 21:25:57 +00003372bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3373 const analyze_scanf::ScanfSpecifier &FS,
3374 const char *startSpecifier,
3375 unsigned specifierLen) {
3376
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003377 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003378 FS.getConversionSpecifier();
3379
3380 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3381 getLocationOfByte(CS.getStart()),
3382 startSpecifier, specifierLen,
3383 CS.getStart(), CS.getLength());
3384}
3385
Ted Kremenek02087932010-07-16 02:11:22 +00003386bool CheckScanfHandler::HandleScanfSpecifier(
3387 const analyze_scanf::ScanfSpecifier &FS,
3388 const char *startSpecifier,
3389 unsigned specifierLen) {
3390
3391 using namespace analyze_scanf;
3392 using namespace analyze_format_string;
3393
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003394 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003395
Ted Kremenek6cd69422010-07-19 22:01:06 +00003396 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3397 // be used to decide if we are using positional arguments consistently.
3398 if (FS.consumesDataArgument()) {
3399 if (atFirstArg) {
3400 atFirstArg = false;
3401 usesPositionalArgs = FS.usesPositionalArg();
3402 }
3403 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003404 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3405 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003406 return false;
3407 }
Ted Kremenek02087932010-07-16 02:11:22 +00003408 }
3409
3410 // Check if the field with is non-zero.
3411 const OptionalAmount &Amt = FS.getFieldWidth();
3412 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3413 if (Amt.getConstantAmount() == 0) {
3414 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3415 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003416 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3417 getLocationOfByte(Amt.getStart()),
3418 /*IsStringLocation*/true, R,
3419 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003420 }
3421 }
3422
3423 if (!FS.consumesDataArgument()) {
3424 // FIXME: Technically specifying a precision or field width here
3425 // makes no sense. Worth issuing a warning at some point.
3426 return true;
3427 }
3428
3429 // Consume the argument.
3430 unsigned argIndex = FS.getArgIndex();
3431 if (argIndex < NumDataArgs) {
3432 // The check to see if the argIndex is valid will come later.
3433 // We set the bit here because we may exit early from this
3434 // function if we encounter some other error.
3435 CoveredArgs.set(argIndex);
3436 }
3437
Ted Kremenek4407ea42010-07-20 20:04:47 +00003438 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003439 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003440 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3441 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003442 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003443 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003444 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003445 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3446 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003447
Jordan Rose92303592012-09-08 04:00:03 +00003448 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3449 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3450
Ted Kremenek02087932010-07-16 02:11:22 +00003451 // The remaining checks depend on the data arguments.
3452 if (HasVAListArg)
3453 return true;
3454
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003455 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003456 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003457
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003458 // Check that the argument type matches the format specifier.
3459 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003460 if (!Ex)
3461 return true;
3462
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003463 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3464 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003465 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003466 bool success = fixedFS.fixType(Ex->getType(),
3467 Ex->IgnoreImpCasts()->getType(),
3468 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003469
3470 if (success) {
3471 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003472 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003473 llvm::raw_svector_ostream os(buf);
3474 fixedFS.toString(os);
3475
3476 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003477 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3478 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003479 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003480 Ex->getLocStart(),
3481 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003482 getSpecifierRange(startSpecifier, specifierLen),
3483 FixItHint::CreateReplacement(
3484 getSpecifierRange(startSpecifier, specifierLen),
3485 os.str()));
3486 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003487 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003488 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3489 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003490 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003491 Ex->getLocStart(),
3492 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003493 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003494 }
3495 }
3496
Ted Kremenek02087932010-07-16 02:11:22 +00003497 return true;
3498}
3499
3500void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003501 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003502 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003503 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003504 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003505 bool inFunctionCall, VariadicCallType CallType,
3506 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003507
Ted Kremenekab278de2010-01-28 23:39:18 +00003508 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003509 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003510 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003511 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003512 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3513 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003514 return;
3515 }
Ted Kremenek02087932010-07-16 02:11:22 +00003516
Ted Kremenekab278de2010-01-28 23:39:18 +00003517 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003518 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003519 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003520 // Account for cases where the string literal is truncated in a declaration.
3521 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3522 assert(T && "String literal not of constant array type!");
3523 size_t TypeSize = T->getSize().getZExtValue();
3524 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003525 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003526
3527 // Emit a warning if the string literal is truncated and does not contain an
3528 // embedded null character.
3529 if (TypeSize <= StrRef.size() &&
3530 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3531 CheckFormatHandler::EmitFormatDiagnostic(
3532 *this, inFunctionCall, Args[format_idx],
3533 PDiag(diag::warn_printf_format_string_not_null_terminated),
3534 FExpr->getLocStart(),
3535 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3536 return;
3537 }
3538
Ted Kremenekab278de2010-01-28 23:39:18 +00003539 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003540 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003541 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003542 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003543 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3544 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003545 return;
3546 }
Ted Kremenek02087932010-07-16 02:11:22 +00003547
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003548 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003549 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003550 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003551 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003552 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003553
Hans Wennborg23926bd2011-12-15 10:25:47 +00003554 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003555 getLangOpts(),
3556 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003557 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003558 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003559 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003560 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003561 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003562
Hans Wennborg23926bd2011-12-15 10:25:47 +00003563 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003564 getLangOpts(),
3565 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003566 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003567 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003568}
3569
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003570//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3571
3572// Returns the related absolute value function that is larger, of 0 if one
3573// does not exist.
3574static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3575 switch (AbsFunction) {
3576 default:
3577 return 0;
3578
3579 case Builtin::BI__builtin_abs:
3580 return Builtin::BI__builtin_labs;
3581 case Builtin::BI__builtin_labs:
3582 return Builtin::BI__builtin_llabs;
3583 case Builtin::BI__builtin_llabs:
3584 return 0;
3585
3586 case Builtin::BI__builtin_fabsf:
3587 return Builtin::BI__builtin_fabs;
3588 case Builtin::BI__builtin_fabs:
3589 return Builtin::BI__builtin_fabsl;
3590 case Builtin::BI__builtin_fabsl:
3591 return 0;
3592
3593 case Builtin::BI__builtin_cabsf:
3594 return Builtin::BI__builtin_cabs;
3595 case Builtin::BI__builtin_cabs:
3596 return Builtin::BI__builtin_cabsl;
3597 case Builtin::BI__builtin_cabsl:
3598 return 0;
3599
3600 case Builtin::BIabs:
3601 return Builtin::BIlabs;
3602 case Builtin::BIlabs:
3603 return Builtin::BIllabs;
3604 case Builtin::BIllabs:
3605 return 0;
3606
3607 case Builtin::BIfabsf:
3608 return Builtin::BIfabs;
3609 case Builtin::BIfabs:
3610 return Builtin::BIfabsl;
3611 case Builtin::BIfabsl:
3612 return 0;
3613
3614 case Builtin::BIcabsf:
3615 return Builtin::BIcabs;
3616 case Builtin::BIcabs:
3617 return Builtin::BIcabsl;
3618 case Builtin::BIcabsl:
3619 return 0;
3620 }
3621}
3622
3623// Returns the argument type of the absolute value function.
3624static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3625 unsigned AbsType) {
3626 if (AbsType == 0)
3627 return QualType();
3628
3629 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3630 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3631 if (Error != ASTContext::GE_None)
3632 return QualType();
3633
3634 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3635 if (!FT)
3636 return QualType();
3637
3638 if (FT->getNumParams() != 1)
3639 return QualType();
3640
3641 return FT->getParamType(0);
3642}
3643
3644// Returns the best absolute value function, or zero, based on type and
3645// current absolute value function.
3646static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3647 unsigned AbsFunctionKind) {
3648 unsigned BestKind = 0;
3649 uint64_t ArgSize = Context.getTypeSize(ArgType);
3650 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3651 Kind = getLargerAbsoluteValueFunction(Kind)) {
3652 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3653 if (Context.getTypeSize(ParamType) >= ArgSize) {
3654 if (BestKind == 0)
3655 BestKind = Kind;
3656 else if (Context.hasSameType(ParamType, ArgType)) {
3657 BestKind = Kind;
3658 break;
3659 }
3660 }
3661 }
3662 return BestKind;
3663}
3664
3665enum AbsoluteValueKind {
3666 AVK_Integer,
3667 AVK_Floating,
3668 AVK_Complex
3669};
3670
3671static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3672 if (T->isIntegralOrEnumerationType())
3673 return AVK_Integer;
3674 if (T->isRealFloatingType())
3675 return AVK_Floating;
3676 if (T->isAnyComplexType())
3677 return AVK_Complex;
3678
3679 llvm_unreachable("Type not integer, floating, or complex");
3680}
3681
3682// Changes the absolute value function to a different type. Preserves whether
3683// the function is a builtin.
3684static unsigned changeAbsFunction(unsigned AbsKind,
3685 AbsoluteValueKind ValueKind) {
3686 switch (ValueKind) {
3687 case AVK_Integer:
3688 switch (AbsKind) {
3689 default:
3690 return 0;
3691 case Builtin::BI__builtin_fabsf:
3692 case Builtin::BI__builtin_fabs:
3693 case Builtin::BI__builtin_fabsl:
3694 case Builtin::BI__builtin_cabsf:
3695 case Builtin::BI__builtin_cabs:
3696 case Builtin::BI__builtin_cabsl:
3697 return Builtin::BI__builtin_abs;
3698 case Builtin::BIfabsf:
3699 case Builtin::BIfabs:
3700 case Builtin::BIfabsl:
3701 case Builtin::BIcabsf:
3702 case Builtin::BIcabs:
3703 case Builtin::BIcabsl:
3704 return Builtin::BIabs;
3705 }
3706 case AVK_Floating:
3707 switch (AbsKind) {
3708 default:
3709 return 0;
3710 case Builtin::BI__builtin_abs:
3711 case Builtin::BI__builtin_labs:
3712 case Builtin::BI__builtin_llabs:
3713 case Builtin::BI__builtin_cabsf:
3714 case Builtin::BI__builtin_cabs:
3715 case Builtin::BI__builtin_cabsl:
3716 return Builtin::BI__builtin_fabsf;
3717 case Builtin::BIabs:
3718 case Builtin::BIlabs:
3719 case Builtin::BIllabs:
3720 case Builtin::BIcabsf:
3721 case Builtin::BIcabs:
3722 case Builtin::BIcabsl:
3723 return Builtin::BIfabsf;
3724 }
3725 case AVK_Complex:
3726 switch (AbsKind) {
3727 default:
3728 return 0;
3729 case Builtin::BI__builtin_abs:
3730 case Builtin::BI__builtin_labs:
3731 case Builtin::BI__builtin_llabs:
3732 case Builtin::BI__builtin_fabsf:
3733 case Builtin::BI__builtin_fabs:
3734 case Builtin::BI__builtin_fabsl:
3735 return Builtin::BI__builtin_cabsf;
3736 case Builtin::BIabs:
3737 case Builtin::BIlabs:
3738 case Builtin::BIllabs:
3739 case Builtin::BIfabsf:
3740 case Builtin::BIfabs:
3741 case Builtin::BIfabsl:
3742 return Builtin::BIcabsf;
3743 }
3744 }
3745 llvm_unreachable("Unable to convert function");
3746}
3747
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003748static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003749 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3750 if (!FnInfo)
3751 return 0;
3752
3753 switch (FDecl->getBuiltinID()) {
3754 default:
3755 return 0;
3756 case Builtin::BI__builtin_abs:
3757 case Builtin::BI__builtin_fabs:
3758 case Builtin::BI__builtin_fabsf:
3759 case Builtin::BI__builtin_fabsl:
3760 case Builtin::BI__builtin_labs:
3761 case Builtin::BI__builtin_llabs:
3762 case Builtin::BI__builtin_cabs:
3763 case Builtin::BI__builtin_cabsf:
3764 case Builtin::BI__builtin_cabsl:
3765 case Builtin::BIabs:
3766 case Builtin::BIlabs:
3767 case Builtin::BIllabs:
3768 case Builtin::BIfabs:
3769 case Builtin::BIfabsf:
3770 case Builtin::BIfabsl:
3771 case Builtin::BIcabs:
3772 case Builtin::BIcabsf:
3773 case Builtin::BIcabsl:
3774 return FDecl->getBuiltinID();
3775 }
3776 llvm_unreachable("Unknown Builtin type");
3777}
3778
3779// If the replacement is valid, emit a note with replacement function.
3780// Additionally, suggest including the proper header if not already included.
3781static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003782 unsigned AbsKind, QualType ArgType) {
3783 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003784 const char *HeaderName = nullptr;
3785 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003786 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3787 FunctionName = "std::abs";
3788 if (ArgType->isIntegralOrEnumerationType()) {
3789 HeaderName = "cstdlib";
3790 } else if (ArgType->isRealFloatingType()) {
3791 HeaderName = "cmath";
3792 } else {
3793 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003794 }
Richard Trieubeffb832014-04-15 23:47:53 +00003795
3796 // Lookup all std::abs
3797 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003798 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003799 R.suppressDiagnostics();
3800 S.LookupQualifiedName(R, Std);
3801
3802 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003803 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003804 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3805 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3806 } else {
3807 FDecl = dyn_cast<FunctionDecl>(I);
3808 }
3809 if (!FDecl)
3810 continue;
3811
3812 // Found std::abs(), check that they are the right ones.
3813 if (FDecl->getNumParams() != 1)
3814 continue;
3815
3816 // Check that the parameter type can handle the argument.
3817 QualType ParamType = FDecl->getParamDecl(0)->getType();
3818 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3819 S.Context.getTypeSize(ArgType) <=
3820 S.Context.getTypeSize(ParamType)) {
3821 // Found a function, don't need the header hint.
3822 EmitHeaderHint = false;
3823 break;
3824 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003825 }
Richard Trieubeffb832014-04-15 23:47:53 +00003826 }
3827 } else {
3828 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3829 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3830
3831 if (HeaderName) {
3832 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3833 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3834 R.suppressDiagnostics();
3835 S.LookupName(R, S.getCurScope());
3836
3837 if (R.isSingleResult()) {
3838 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3839 if (FD && FD->getBuiltinID() == AbsKind) {
3840 EmitHeaderHint = false;
3841 } else {
3842 return;
3843 }
3844 } else if (!R.empty()) {
3845 return;
3846 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003847 }
3848 }
3849
3850 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003851 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003852
Richard Trieubeffb832014-04-15 23:47:53 +00003853 if (!HeaderName)
3854 return;
3855
3856 if (!EmitHeaderHint)
3857 return;
3858
3859 S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3860}
3861
3862static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3863 if (!FDecl)
3864 return false;
3865
3866 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3867 return false;
3868
3869 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3870
3871 while (ND && ND->isInlineNamespace()) {
3872 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003873 }
Richard Trieubeffb832014-04-15 23:47:53 +00003874
3875 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3876 return false;
3877
3878 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3879 return false;
3880
3881 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003882}
3883
3884// Warn when using the wrong abs() function.
3885void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3886 const FunctionDecl *FDecl,
3887 IdentifierInfo *FnInfo) {
3888 if (Call->getNumArgs() != 1)
3889 return;
3890
3891 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003892 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3893 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003894 return;
3895
3896 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3897 QualType ParamType = Call->getArg(0)->getType();
3898
3899 // Unsigned types can not be negative. Suggest to drop the absolute value
3900 // function.
3901 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003902 const char *FunctionName =
3903 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003904 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3905 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003906 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003907 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3908 return;
3909 }
3910
Richard Trieubeffb832014-04-15 23:47:53 +00003911 // std::abs has overloads which prevent most of the absolute value problems
3912 // from occurring.
3913 if (IsStdAbs)
3914 return;
3915
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003916 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3917 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3918
3919 // The argument and parameter are the same kind. Check if they are the right
3920 // size.
3921 if (ArgValueKind == ParamValueKind) {
3922 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3923 return;
3924
3925 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3926 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3927 << FDecl << ArgType << ParamType;
3928
3929 if (NewAbsKind == 0)
3930 return;
3931
3932 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003933 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003934 return;
3935 }
3936
3937 // ArgValueKind != ParamValueKind
3938 // The wrong type of absolute value function was used. Attempt to find the
3939 // proper one.
3940 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3941 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3942 if (NewAbsKind == 0)
3943 return;
3944
3945 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3946 << FDecl << ParamValueKind << ArgValueKind;
3947
3948 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003949 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003950 return;
3951}
3952
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003953//===--- CHECK: Standard memory functions ---------------------------------===//
3954
Nico Weber0e6daef2013-12-26 23:38:39 +00003955/// \brief Takes the expression passed to the size_t parameter of functions
3956/// such as memcmp, strncat, etc and warns if it's a comparison.
3957///
3958/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3959static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3960 IdentifierInfo *FnName,
3961 SourceLocation FnLoc,
3962 SourceLocation RParenLoc) {
3963 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3964 if (!Size)
3965 return false;
3966
3967 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3968 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3969 return false;
3970
Nico Weber0e6daef2013-12-26 23:38:39 +00003971 SourceRange SizeRange = Size->getSourceRange();
3972 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3973 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00003974 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00003975 << FnName << FixItHint::CreateInsertion(
3976 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00003977 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00003978 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00003979 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00003980 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3981 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00003982
3983 return true;
3984}
3985
Reid Kleckner5fb5b122014-06-27 23:58:21 +00003986/// \brief Determine whether the given type is or contains a dynamic class type
3987/// (e.g., whether it has a vtable).
3988static const CXXRecordDecl *getContainedDynamicClass(QualType T,
3989 bool &IsContained) {
3990 // Look through array types while ignoring qualifiers.
3991 const Type *Ty = T->getBaseElementTypeUnsafe();
3992 IsContained = false;
3993
3994 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
3995 RD = RD ? RD->getDefinition() : nullptr;
3996 if (!RD)
3997 return nullptr;
3998
3999 if (RD->isDynamicClass())
4000 return RD;
4001
4002 // Check all the fields. If any bases were dynamic, the class is dynamic.
4003 // It's impossible for a class to transitively contain itself by value, so
4004 // infinite recursion is impossible.
4005 for (auto *FD : RD->fields()) {
4006 bool SubContained;
4007 if (const CXXRecordDecl *ContainedRD =
4008 getContainedDynamicClass(FD->getType(), SubContained)) {
4009 IsContained = true;
4010 return ContainedRD;
4011 }
4012 }
4013
4014 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004015}
4016
Chandler Carruth889ed862011-06-21 23:04:20 +00004017/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004018/// otherwise returns NULL.
4019static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004020 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004021 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4022 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4023 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004024
Craig Topperc3ec1492014-05-26 06:22:03 +00004025 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004026}
4027
Chandler Carruth889ed862011-06-21 23:04:20 +00004028/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004029static QualType getSizeOfArgType(const Expr* E) {
4030 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4031 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4032 if (SizeOf->getKind() == clang::UETT_SizeOf)
4033 return SizeOf->getTypeOfArgument();
4034
4035 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004036}
4037
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004038/// \brief Check for dangerous or invalid arguments to memset().
4039///
Chandler Carruthac687262011-06-03 06:23:57 +00004040/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004041/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4042/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004043///
4044/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004045void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004046 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004047 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004048 assert(BId != 0);
4049
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004050 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004051 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004052 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004053 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004054 return;
4055
Anna Zaks22122702012-01-17 00:37:07 +00004056 unsigned LastArg = (BId == Builtin::BImemset ||
4057 BId == Builtin::BIstrndup ? 1 : 2);
4058 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004059 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004060
Nico Weber0e6daef2013-12-26 23:38:39 +00004061 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4062 Call->getLocStart(), Call->getRParenLoc()))
4063 return;
4064
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004065 // We have special checking when the length is a sizeof expression.
4066 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4067 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4068 llvm::FoldingSetNodeID SizeOfArgID;
4069
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004070 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4071 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004072 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004073
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004074 QualType DestTy = Dest->getType();
4075 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4076 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004077
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004078 // Never warn about void type pointers. This can be used to suppress
4079 // false positives.
4080 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004081 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004082
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004083 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4084 // actually comparing the expressions for equality. Because computing the
4085 // expression IDs can be expensive, we only do this if the diagnostic is
4086 // enabled.
4087 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004088 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4089 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004090 // We only compute IDs for expressions if the warning is enabled, and
4091 // cache the sizeof arg's ID.
4092 if (SizeOfArgID == llvm::FoldingSetNodeID())
4093 SizeOfArg->Profile(SizeOfArgID, Context, true);
4094 llvm::FoldingSetNodeID DestID;
4095 Dest->Profile(DestID, Context, true);
4096 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004097 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4098 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004099 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004100 StringRef ReadableName = FnName->getName();
4101
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004102 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004103 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004104 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004105 if (!PointeeTy->isIncompleteType() &&
4106 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004107 ActionIdx = 2; // If the pointee's size is sizeof(char),
4108 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004109
4110 // If the function is defined as a builtin macro, do not show macro
4111 // expansion.
4112 SourceLocation SL = SizeOfArg->getExprLoc();
4113 SourceRange DSR = Dest->getSourceRange();
4114 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004115 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004116
4117 if (SM.isMacroArgExpansion(SL)) {
4118 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4119 SL = SM.getSpellingLoc(SL);
4120 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4121 SM.getSpellingLoc(DSR.getEnd()));
4122 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4123 SM.getSpellingLoc(SSR.getEnd()));
4124 }
4125
Anna Zaksd08d9152012-05-30 23:14:52 +00004126 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004127 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004128 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004129 << PointeeTy
4130 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004131 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004132 << SSR);
4133 DiagRuntimeBehavior(SL, SizeOfArg,
4134 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4135 << ActionIdx
4136 << SSR);
4137
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004138 break;
4139 }
4140 }
4141
4142 // Also check for cases where the sizeof argument is the exact same
4143 // type as the memory argument, and where it points to a user-defined
4144 // record type.
4145 if (SizeOfArgTy != QualType()) {
4146 if (PointeeTy->isRecordType() &&
4147 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4148 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4149 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4150 << FnName << SizeOfArgTy << ArgIdx
4151 << PointeeTy << Dest->getSourceRange()
4152 << LenExpr->getSourceRange());
4153 break;
4154 }
Nico Weberc5e73862011-06-14 16:14:58 +00004155 }
4156
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004157 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004158 bool IsContained;
4159 if (const CXXRecordDecl *ContainedRD =
4160 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004161
4162 unsigned OperationType = 0;
4163 // "overwritten" if we're warning about the destination for any call
4164 // but memcmp; otherwise a verb appropriate to the call.
4165 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4166 if (BId == Builtin::BImemcpy)
4167 OperationType = 1;
4168 else if(BId == Builtin::BImemmove)
4169 OperationType = 2;
4170 else if (BId == Builtin::BImemcmp)
4171 OperationType = 3;
4172 }
4173
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004174 DiagRuntimeBehavior(
4175 Dest->getExprLoc(), Dest,
4176 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004177 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004178 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004179 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004180 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4181 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004182 DiagRuntimeBehavior(
4183 Dest->getExprLoc(), Dest,
4184 PDiag(diag::warn_arc_object_memaccess)
4185 << ArgIdx << FnName << PointeeTy
4186 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004187 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004188 continue;
John McCall31168b02011-06-15 23:02:42 +00004189
4190 DiagRuntimeBehavior(
4191 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004192 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004193 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4194 break;
4195 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004196 }
4197}
4198
Ted Kremenek6865f772011-08-18 20:55:45 +00004199// A little helper routine: ignore addition and subtraction of integer literals.
4200// This intentionally does not ignore all integer constant expressions because
4201// we don't want to remove sizeof().
4202static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4203 Ex = Ex->IgnoreParenCasts();
4204
4205 for (;;) {
4206 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4207 if (!BO || !BO->isAdditiveOp())
4208 break;
4209
4210 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4211 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4212
4213 if (isa<IntegerLiteral>(RHS))
4214 Ex = LHS;
4215 else if (isa<IntegerLiteral>(LHS))
4216 Ex = RHS;
4217 else
4218 break;
4219 }
4220
4221 return Ex;
4222}
4223
Anna Zaks13b08572012-08-08 21:42:23 +00004224static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4225 ASTContext &Context) {
4226 // Only handle constant-sized or VLAs, but not flexible members.
4227 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4228 // Only issue the FIXIT for arrays of size > 1.
4229 if (CAT->getSize().getSExtValue() <= 1)
4230 return false;
4231 } else if (!Ty->isVariableArrayType()) {
4232 return false;
4233 }
4234 return true;
4235}
4236
Ted Kremenek6865f772011-08-18 20:55:45 +00004237// Warn if the user has made the 'size' argument to strlcpy or strlcat
4238// be the size of the source, instead of the destination.
4239void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4240 IdentifierInfo *FnName) {
4241
4242 // Don't crash if the user has the wrong number of arguments
4243 if (Call->getNumArgs() != 3)
4244 return;
4245
4246 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4247 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004248 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004249
4250 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4251 Call->getLocStart(), Call->getRParenLoc()))
4252 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004253
4254 // Look for 'strlcpy(dst, x, sizeof(x))'
4255 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4256 CompareWithSrc = Ex;
4257 else {
4258 // Look for 'strlcpy(dst, x, strlen(x))'
4259 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004260 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4261 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004262 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4263 }
4264 }
4265
4266 if (!CompareWithSrc)
4267 return;
4268
4269 // Determine if the argument to sizeof/strlen is equal to the source
4270 // argument. In principle there's all kinds of things you could do
4271 // here, for instance creating an == expression and evaluating it with
4272 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4273 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4274 if (!SrcArgDRE)
4275 return;
4276
4277 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4278 if (!CompareWithSrcDRE ||
4279 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4280 return;
4281
4282 const Expr *OriginalSizeArg = Call->getArg(2);
4283 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4284 << OriginalSizeArg->getSourceRange() << FnName;
4285
4286 // Output a FIXIT hint if the destination is an array (rather than a
4287 // pointer to an array). This could be enhanced to handle some
4288 // pointers if we know the actual size, like if DstArg is 'array+2'
4289 // we could say 'sizeof(array)-2'.
4290 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004291 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004292 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004293
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004294 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004295 llvm::raw_svector_ostream OS(sizeString);
4296 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004297 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004298 OS << ")";
4299
4300 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4301 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4302 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004303}
4304
Anna Zaks314cd092012-02-01 19:08:57 +00004305/// Check if two expressions refer to the same declaration.
4306static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4307 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4308 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4309 return D1->getDecl() == D2->getDecl();
4310 return false;
4311}
4312
4313static const Expr *getStrlenExprArg(const Expr *E) {
4314 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4315 const FunctionDecl *FD = CE->getDirectCallee();
4316 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004317 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004318 return CE->getArg(0)->IgnoreParenCasts();
4319 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004320 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004321}
4322
4323// Warn on anti-patterns as the 'size' argument to strncat.
4324// The correct size argument should look like following:
4325// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4326void Sema::CheckStrncatArguments(const CallExpr *CE,
4327 IdentifierInfo *FnName) {
4328 // Don't crash if the user has the wrong number of arguments.
4329 if (CE->getNumArgs() < 3)
4330 return;
4331 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4332 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4333 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4334
Nico Weber0e6daef2013-12-26 23:38:39 +00004335 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4336 CE->getRParenLoc()))
4337 return;
4338
Anna Zaks314cd092012-02-01 19:08:57 +00004339 // Identify common expressions, which are wrongly used as the size argument
4340 // to strncat and may lead to buffer overflows.
4341 unsigned PatternType = 0;
4342 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4343 // - sizeof(dst)
4344 if (referToTheSameDecl(SizeOfArg, DstArg))
4345 PatternType = 1;
4346 // - sizeof(src)
4347 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4348 PatternType = 2;
4349 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4350 if (BE->getOpcode() == BO_Sub) {
4351 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4352 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4353 // - sizeof(dst) - strlen(dst)
4354 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4355 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4356 PatternType = 1;
4357 // - sizeof(src) - (anything)
4358 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4359 PatternType = 2;
4360 }
4361 }
4362
4363 if (PatternType == 0)
4364 return;
4365
Anna Zaks5069aa32012-02-03 01:27:37 +00004366 // Generate the diagnostic.
4367 SourceLocation SL = LenArg->getLocStart();
4368 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004369 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004370
4371 // If the function is defined as a builtin macro, do not show macro expansion.
4372 if (SM.isMacroArgExpansion(SL)) {
4373 SL = SM.getSpellingLoc(SL);
4374 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4375 SM.getSpellingLoc(SR.getEnd()));
4376 }
4377
Anna Zaks13b08572012-08-08 21:42:23 +00004378 // Check if the destination is an array (rather than a pointer to an array).
4379 QualType DstTy = DstArg->getType();
4380 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4381 Context);
4382 if (!isKnownSizeArray) {
4383 if (PatternType == 1)
4384 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4385 else
4386 Diag(SL, diag::warn_strncat_src_size) << SR;
4387 return;
4388 }
4389
Anna Zaks314cd092012-02-01 19:08:57 +00004390 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004391 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004392 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004393 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004394
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004395 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004396 llvm::raw_svector_ostream OS(sizeString);
4397 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004398 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004399 OS << ") - ";
4400 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004401 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004402 OS << ") - 1";
4403
Anna Zaks5069aa32012-02-03 01:27:37 +00004404 Diag(SL, diag::note_strncat_wrong_size)
4405 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004406}
4407
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004408//===--- CHECK: Return Address of Stack Variable --------------------------===//
4409
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004410static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4411 Decl *ParentDecl);
4412static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4413 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004414
4415/// CheckReturnStackAddr - Check if a return statement returns the address
4416/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004417static void
4418CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4419 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004420
Craig Topperc3ec1492014-05-26 06:22:03 +00004421 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004422 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004423
4424 // Perform checking for returned stack addresses, local blocks,
4425 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004426 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004427 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004428 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004429 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004430 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004431 }
4432
Craig Topperc3ec1492014-05-26 06:22:03 +00004433 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004434 return; // Nothing suspicious was found.
4435
4436 SourceLocation diagLoc;
4437 SourceRange diagRange;
4438 if (refVars.empty()) {
4439 diagLoc = stackE->getLocStart();
4440 diagRange = stackE->getSourceRange();
4441 } else {
4442 // We followed through a reference variable. 'stackE' contains the
4443 // problematic expression but we will warn at the return statement pointing
4444 // at the reference variable. We will later display the "trail" of
4445 // reference variables using notes.
4446 diagLoc = refVars[0]->getLocStart();
4447 diagRange = refVars[0]->getSourceRange();
4448 }
4449
4450 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004451 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004452 : diag::warn_ret_stack_addr)
4453 << DR->getDecl()->getDeclName() << diagRange;
4454 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004455 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004456 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004457 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004458 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004459 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4460 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004461 << diagRange;
4462 }
4463
4464 // Display the "trail" of reference variables that we followed until we
4465 // found the problematic expression using notes.
4466 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4467 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4468 // If this var binds to another reference var, show the range of the next
4469 // var, otherwise the var binds to the problematic expression, in which case
4470 // show the range of the expression.
4471 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4472 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004473 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4474 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004475 }
4476}
4477
4478/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4479/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004480/// to a location on the stack, a local block, an address of a label, or a
4481/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004482/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004483/// encounter a subexpression that (1) clearly does not lead to one of the
4484/// above problematic expressions (2) is something we cannot determine leads to
4485/// a problematic expression based on such local checking.
4486///
4487/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4488/// the expression that they point to. Such variables are added to the
4489/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004490///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004491/// EvalAddr processes expressions that are pointers that are used as
4492/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004493/// At the base case of the recursion is a check for the above problematic
4494/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004495///
4496/// This implementation handles:
4497///
4498/// * pointer-to-pointer casts
4499/// * implicit conversions from array references to pointers
4500/// * taking the address of fields
4501/// * arbitrary interplay between "&" and "*" operators
4502/// * pointer arithmetic from an address of a stack variable
4503/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004504static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4505 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004506 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004507 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004508
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004509 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004510 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004511 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004512 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004513 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004514
Peter Collingbourne91147592011-04-15 00:35:48 +00004515 E = E->IgnoreParens();
4516
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004517 // Our "symbolic interpreter" is just a dispatch off the currently
4518 // viewed AST node. We then recursively traverse the AST by calling
4519 // EvalAddr and EvalVal appropriately.
4520 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004521 case Stmt::DeclRefExprClass: {
4522 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4523
Richard Smith40f08eb2014-01-30 22:05:38 +00004524 // If we leave the immediate function, the lifetime isn't about to end.
4525 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004526 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004527
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004528 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4529 // If this is a reference variable, follow through to the expression that
4530 // it points to.
4531 if (V->hasLocalStorage() &&
4532 V->getType()->isReferenceType() && V->hasInit()) {
4533 // Add the reference variable to the "trail".
4534 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004535 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004536 }
4537
Craig Topperc3ec1492014-05-26 06:22:03 +00004538 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004539 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004540
Chris Lattner934edb22007-12-28 05:31:15 +00004541 case Stmt::UnaryOperatorClass: {
4542 // The only unary operator that make sense to handle here
4543 // is AddrOf. All others don't make sense as pointers.
4544 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004545
John McCalle3027922010-08-25 11:45:40 +00004546 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004547 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004548 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004549 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004550 }
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattner934edb22007-12-28 05:31:15 +00004552 case Stmt::BinaryOperatorClass: {
4553 // Handle pointer arithmetic. All other binary operators are not valid
4554 // in this context.
4555 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004556 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004557
John McCalle3027922010-08-25 11:45:40 +00004558 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004559 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004560
Chris Lattner934edb22007-12-28 05:31:15 +00004561 Expr *Base = B->getLHS();
4562
4563 // Determine which argument is the real pointer base. It could be
4564 // the RHS argument instead of the LHS.
4565 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004566
Chris Lattner934edb22007-12-28 05:31:15 +00004567 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004568 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004569 }
Steve Naroff2752a172008-09-10 19:17:48 +00004570
Chris Lattner934edb22007-12-28 05:31:15 +00004571 // For conditional operators we need to see if either the LHS or RHS are
4572 // valid DeclRefExpr*s. If one of them is valid, we return it.
4573 case Stmt::ConditionalOperatorClass: {
4574 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004575
Chris Lattner934edb22007-12-28 05:31:15 +00004576 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004577 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4578 if (Expr *LHSExpr = C->getLHS()) {
4579 // In C++, we can have a throw-expression, which has 'void' type.
4580 if (!LHSExpr->getType()->isVoidType())
4581 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004582 return LHS;
4583 }
Chris Lattner934edb22007-12-28 05:31:15 +00004584
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004585 // In C++, we can have a throw-expression, which has 'void' type.
4586 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004587 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004588
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004589 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004590 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004591
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004592 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004593 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004594 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004595 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004596
4597 case Stmt::AddrLabelExprClass:
4598 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004599
John McCall28fc7092011-11-10 05:35:25 +00004600 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004601 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4602 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004603
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004604 // For casts, we need to handle conversions from arrays to
4605 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004606 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004607 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004608 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004609 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004610 case Stmt::CXXStaticCastExprClass:
4611 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004612 case Stmt::CXXConstCastExprClass:
4613 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004614 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4615 switch (cast<CastExpr>(E)->getCastKind()) {
4616 case CK_BitCast:
4617 case CK_LValueToRValue:
4618 case CK_NoOp:
4619 case CK_BaseToDerived:
4620 case CK_DerivedToBase:
4621 case CK_UncheckedDerivedToBase:
4622 case CK_Dynamic:
4623 case CK_CPointerToObjCPointerCast:
4624 case CK_BlockPointerToObjCPointerCast:
4625 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004626 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004627
4628 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004629 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004630
4631 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004632 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004633 }
Chris Lattner934edb22007-12-28 05:31:15 +00004634 }
Mike Stump11289f42009-09-09 15:08:12 +00004635
Douglas Gregorfe314812011-06-21 17:03:29 +00004636 case Stmt::MaterializeTemporaryExprClass:
4637 if (Expr *Result = EvalAddr(
4638 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004639 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004640 return Result;
4641
4642 return E;
4643
Chris Lattner934edb22007-12-28 05:31:15 +00004644 // Everything else: we simply don't reason about them.
4645 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004646 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004647 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004648}
Mike Stump11289f42009-09-09 15:08:12 +00004649
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004650
4651/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4652/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004653static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4654 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004655do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004656 // We should only be called for evaluating non-pointer expressions, or
4657 // expressions with a pointer type that are not used as references but instead
4658 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004659
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004660 // Our "symbolic interpreter" is just a dispatch off the currently
4661 // viewed AST node. We then recursively traverse the AST by calling
4662 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004663
4664 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004665 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004666 case Stmt::ImplicitCastExprClass: {
4667 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004668 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004669 E = IE->getSubExpr();
4670 continue;
4671 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004672 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004673 }
4674
John McCall28fc7092011-11-10 05:35:25 +00004675 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004676 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004677
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004678 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004679 // When we hit a DeclRefExpr we are looking at code that refers to a
4680 // variable's name. If it's not a reference variable we check if it has
4681 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004682 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004683
Richard Smith40f08eb2014-01-30 22:05:38 +00004684 // If we leave the immediate function, the lifetime isn't about to end.
4685 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004686 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004687
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004688 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4689 // Check if it refers to itself, e.g. "int& i = i;".
4690 if (V == ParentDecl)
4691 return DR;
4692
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004693 if (V->hasLocalStorage()) {
4694 if (!V->getType()->isReferenceType())
4695 return DR;
4696
4697 // Reference variable, follow through to the expression that
4698 // it points to.
4699 if (V->hasInit()) {
4700 // Add the reference variable to the "trail".
4701 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004702 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004703 }
4704 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004705 }
Mike Stump11289f42009-09-09 15:08:12 +00004706
Craig Topperc3ec1492014-05-26 06:22:03 +00004707 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004708 }
Mike Stump11289f42009-09-09 15:08:12 +00004709
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004710 case Stmt::UnaryOperatorClass: {
4711 // The only unary operator that make sense to handle here
4712 // is Deref. All others don't resolve to a "name." This includes
4713 // handling all sorts of rvalues passed to a unary operator.
4714 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004715
John McCalle3027922010-08-25 11:45:40 +00004716 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004717 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004718
Craig Topperc3ec1492014-05-26 06:22:03 +00004719 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004722 case Stmt::ArraySubscriptExprClass: {
4723 // Array subscripts are potential references to data on the stack. We
4724 // retrieve the DeclRefExpr* for the array variable if it indeed
4725 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004726 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004727 }
Mike Stump11289f42009-09-09 15:08:12 +00004728
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004729 case Stmt::ConditionalOperatorClass: {
4730 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004731 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004732 ConditionalOperator *C = cast<ConditionalOperator>(E);
4733
Anders Carlsson801c5c72007-11-30 19:04:31 +00004734 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004735 if (Expr *LHSExpr = C->getLHS()) {
4736 // In C++, we can have a throw-expression, which has 'void' type.
4737 if (!LHSExpr->getType()->isVoidType())
4738 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4739 return LHS;
4740 }
4741
4742 // In C++, we can have a throw-expression, which has 'void' type.
4743 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004744 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004745
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004746 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004747 }
Mike Stump11289f42009-09-09 15:08:12 +00004748
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004749 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004750 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004751 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004752
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004753 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004754 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004755 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004756
4757 // Check whether the member type is itself a reference, in which case
4758 // we're not going to refer to the member, but to what the member refers to.
4759 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004760 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004761
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004762 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004763 }
Mike Stump11289f42009-09-09 15:08:12 +00004764
Douglas Gregorfe314812011-06-21 17:03:29 +00004765 case Stmt::MaterializeTemporaryExprClass:
4766 if (Expr *Result = EvalVal(
4767 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004768 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004769 return Result;
4770
4771 return E;
4772
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004773 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004774 // Check that we don't return or take the address of a reference to a
4775 // temporary. This is only useful in C++.
4776 if (!E->isTypeDependent() && E->isRValue())
4777 return E;
4778
4779 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004780 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004781 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004782} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004783}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004784
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004785void
4786Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4787 SourceLocation ReturnLoc,
4788 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004789 const AttrVec *Attrs,
4790 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004791 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4792
4793 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004794 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4795 CheckNonNullExpr(*this, RetValExp))
4796 Diag(ReturnLoc, diag::warn_null_ret)
4797 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004798
4799 // C++11 [basic.stc.dynamic.allocation]p4:
4800 // If an allocation function declared with a non-throwing
4801 // exception-specification fails to allocate storage, it shall return
4802 // a null pointer. Any other allocation function that fails to allocate
4803 // storage shall indicate failure only by throwing an exception [...]
4804 if (FD) {
4805 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4806 if (Op == OO_New || Op == OO_Array_New) {
4807 const FunctionProtoType *Proto
4808 = FD->getType()->castAs<FunctionProtoType>();
4809 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4810 CheckNonNullExpr(*this, RetValExp))
4811 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4812 << FD << getLangOpts().CPlusPlus11;
4813 }
4814 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004815}
4816
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004817//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4818
4819/// Check for comparisons of floating point operands using != and ==.
4820/// Issue a warning if these are no self-comparisons, as they are not likely
4821/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004822void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004823 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4824 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004825
4826 // Special case: check for x == x (which is OK).
4827 // Do not emit warnings for such cases.
4828 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4829 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4830 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004831 return;
Mike Stump11289f42009-09-09 15:08:12 +00004832
4833
Ted Kremenekeda40e22007-11-29 00:59:04 +00004834 // Special case: check for comparisons against literals that can be exactly
4835 // represented by APFloat. In such cases, do not emit a warning. This
4836 // is a heuristic: often comparison against such literals are used to
4837 // detect if a value in a variable has not changed. This clearly can
4838 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004839 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4840 if (FLL->isExact())
4841 return;
4842 } else
4843 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4844 if (FLR->isExact())
4845 return;
Mike Stump11289f42009-09-09 15:08:12 +00004846
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004847 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004848 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004849 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004850 return;
Mike Stump11289f42009-09-09 15:08:12 +00004851
David Blaikie1f4ff152012-07-16 20:47:22 +00004852 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004853 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004854 return;
Mike Stump11289f42009-09-09 15:08:12 +00004855
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004856 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004857 Diag(Loc, diag::warn_floatingpoint_eq)
4858 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004859}
John McCallca01b222010-01-04 23:21:16 +00004860
John McCall70aa5392010-01-06 05:24:50 +00004861//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4862//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004863
John McCall70aa5392010-01-06 05:24:50 +00004864namespace {
John McCallca01b222010-01-04 23:21:16 +00004865
John McCall70aa5392010-01-06 05:24:50 +00004866/// Structure recording the 'active' range of an integer-valued
4867/// expression.
4868struct IntRange {
4869 /// The number of bits active in the int.
4870 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004871
John McCall70aa5392010-01-06 05:24:50 +00004872 /// True if the int is known not to have negative values.
4873 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004874
John McCall70aa5392010-01-06 05:24:50 +00004875 IntRange(unsigned Width, bool NonNegative)
4876 : Width(Width), NonNegative(NonNegative)
4877 {}
John McCallca01b222010-01-04 23:21:16 +00004878
John McCall817d4af2010-11-10 23:38:19 +00004879 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004880 static IntRange forBoolType() {
4881 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004882 }
4883
John McCall817d4af2010-11-10 23:38:19 +00004884 /// Returns the range of an opaque value of the given integral type.
4885 static IntRange forValueOfType(ASTContext &C, QualType T) {
4886 return forValueOfCanonicalType(C,
4887 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004888 }
4889
John McCall817d4af2010-11-10 23:38:19 +00004890 /// Returns the range of an opaque value of a canonical integral type.
4891 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004892 assert(T->isCanonicalUnqualified());
4893
4894 if (const VectorType *VT = dyn_cast<VectorType>(T))
4895 T = VT->getElementType().getTypePtr();
4896 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4897 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004898
David Majnemer6a426652013-06-07 22:07:20 +00004899 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004900 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004901 EnumDecl *Enum = ET->getDecl();
4902 if (!Enum->isCompleteDefinition())
4903 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004904
David Majnemer6a426652013-06-07 22:07:20 +00004905 unsigned NumPositive = Enum->getNumPositiveBits();
4906 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004907
David Majnemer6a426652013-06-07 22:07:20 +00004908 if (NumNegative == 0)
4909 return IntRange(NumPositive, true/*NonNegative*/);
4910 else
4911 return IntRange(std::max(NumPositive + 1, NumNegative),
4912 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004913 }
John McCall70aa5392010-01-06 05:24:50 +00004914
4915 const BuiltinType *BT = cast<BuiltinType>(T);
4916 assert(BT->isInteger());
4917
4918 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4919 }
4920
John McCall817d4af2010-11-10 23:38:19 +00004921 /// Returns the "target" range of a canonical integral type, i.e.
4922 /// the range of values expressible in the type.
4923 ///
4924 /// This matches forValueOfCanonicalType except that enums have the
4925 /// full range of their type, not the range of their enumerators.
4926 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4927 assert(T->isCanonicalUnqualified());
4928
4929 if (const VectorType *VT = dyn_cast<VectorType>(T))
4930 T = VT->getElementType().getTypePtr();
4931 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4932 T = CT->getElementType().getTypePtr();
4933 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004934 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004935
4936 const BuiltinType *BT = cast<BuiltinType>(T);
4937 assert(BT->isInteger());
4938
4939 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4940 }
4941
4942 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004943 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004944 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004945 L.NonNegative && R.NonNegative);
4946 }
4947
John McCall817d4af2010-11-10 23:38:19 +00004948 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004949 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004950 return IntRange(std::min(L.Width, R.Width),
4951 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004952 }
4953};
4954
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004955static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4956 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004957 if (value.isSigned() && value.isNegative())
4958 return IntRange(value.getMinSignedBits(), false);
4959
4960 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004961 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004962
4963 // isNonNegative() just checks the sign bit without considering
4964 // signedness.
4965 return IntRange(value.getActiveBits(), true);
4966}
4967
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004968static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4969 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004970 if (result.isInt())
4971 return GetValueRange(C, result.getInt(), MaxWidth);
4972
4973 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004974 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4975 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4976 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4977 R = IntRange::join(R, El);
4978 }
John McCall70aa5392010-01-06 05:24:50 +00004979 return R;
4980 }
4981
4982 if (result.isComplexInt()) {
4983 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4984 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4985 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004986 }
4987
4988 // This can happen with lossless casts to intptr_t of "based" lvalues.
4989 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004990 // FIXME: The only reason we need to pass the type in here is to get
4991 // the sign right on this one case. It would be nice if APValue
4992 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004993 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004994 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004995}
John McCall70aa5392010-01-06 05:24:50 +00004996
Eli Friedmane6d33952013-07-08 20:20:06 +00004997static QualType GetExprType(Expr *E) {
4998 QualType Ty = E->getType();
4999 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5000 Ty = AtomicRHS->getValueType();
5001 return Ty;
5002}
5003
John McCall70aa5392010-01-06 05:24:50 +00005004/// Pseudo-evaluate the given integer expression, estimating the
5005/// range of values it might take.
5006///
5007/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005008static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005009 E = E->IgnoreParens();
5010
5011 // Try a full evaluation first.
5012 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005013 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005014 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005015
5016 // I think we only want to look through implicit casts here; if the
5017 // user has an explicit widening cast, we should treat the value as
5018 // being of the new, wider type.
5019 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005020 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005021 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5022
Eli Friedmane6d33952013-07-08 20:20:06 +00005023 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005024
John McCalle3027922010-08-25 11:45:40 +00005025 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005026
John McCall70aa5392010-01-06 05:24:50 +00005027 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005028 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005029 return OutputTypeRange;
5030
5031 IntRange SubRange
5032 = GetExprRange(C, CE->getSubExpr(),
5033 std::min(MaxWidth, OutputTypeRange.Width));
5034
5035 // Bail out if the subexpr's range is as wide as the cast type.
5036 if (SubRange.Width >= OutputTypeRange.Width)
5037 return OutputTypeRange;
5038
5039 // Otherwise, we take the smaller width, and we're non-negative if
5040 // either the output type or the subexpr is.
5041 return IntRange(SubRange.Width,
5042 SubRange.NonNegative || OutputTypeRange.NonNegative);
5043 }
5044
5045 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5046 // If we can fold the condition, just take that operand.
5047 bool CondResult;
5048 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5049 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5050 : CO->getFalseExpr(),
5051 MaxWidth);
5052
5053 // Otherwise, conservatively merge.
5054 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5055 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5056 return IntRange::join(L, R);
5057 }
5058
5059 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5060 switch (BO->getOpcode()) {
5061
5062 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005063 case BO_LAnd:
5064 case BO_LOr:
5065 case BO_LT:
5066 case BO_GT:
5067 case BO_LE:
5068 case BO_GE:
5069 case BO_EQ:
5070 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005071 return IntRange::forBoolType();
5072
John McCallc3688382011-07-13 06:35:24 +00005073 // The type of the assignments is the type of the LHS, so the RHS
5074 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005075 case BO_MulAssign:
5076 case BO_DivAssign:
5077 case BO_RemAssign:
5078 case BO_AddAssign:
5079 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005080 case BO_XorAssign:
5081 case BO_OrAssign:
5082 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005083 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005084
John McCallc3688382011-07-13 06:35:24 +00005085 // Simple assignments just pass through the RHS, which will have
5086 // been coerced to the LHS type.
5087 case BO_Assign:
5088 // TODO: bitfields?
5089 return GetExprRange(C, BO->getRHS(), MaxWidth);
5090
John McCall70aa5392010-01-06 05:24:50 +00005091 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005092 case BO_PtrMemD:
5093 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005094 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005095
John McCall2ce81ad2010-01-06 22:07:33 +00005096 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005097 case BO_And:
5098 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005099 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5100 GetExprRange(C, BO->getRHS(), MaxWidth));
5101
John McCall70aa5392010-01-06 05:24:50 +00005102 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005103 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005104 // ...except that we want to treat '1 << (blah)' as logically
5105 // positive. It's an important idiom.
5106 if (IntegerLiteral *I
5107 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5108 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005109 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005110 return IntRange(R.Width, /*NonNegative*/ true);
5111 }
5112 }
5113 // fallthrough
5114
John McCalle3027922010-08-25 11:45:40 +00005115 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005116 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005117
John McCall2ce81ad2010-01-06 22:07:33 +00005118 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005119 case BO_Shr:
5120 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005121 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5122
5123 // If the shift amount is a positive constant, drop the width by
5124 // that much.
5125 llvm::APSInt shift;
5126 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5127 shift.isNonNegative()) {
5128 unsigned zext = shift.getZExtValue();
5129 if (zext >= L.Width)
5130 L.Width = (L.NonNegative ? 0 : 1);
5131 else
5132 L.Width -= zext;
5133 }
5134
5135 return L;
5136 }
5137
5138 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005139 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005140 return GetExprRange(C, BO->getRHS(), MaxWidth);
5141
John McCall2ce81ad2010-01-06 22:07:33 +00005142 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005143 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005144 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005145 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005146 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005147
John McCall51431812011-07-14 22:39:48 +00005148 // The width of a division result is mostly determined by the size
5149 // of the LHS.
5150 case BO_Div: {
5151 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005152 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005153 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5154
5155 // If the divisor is constant, use that.
5156 llvm::APSInt divisor;
5157 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5158 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5159 if (log2 >= L.Width)
5160 L.Width = (L.NonNegative ? 0 : 1);
5161 else
5162 L.Width = std::min(L.Width - log2, MaxWidth);
5163 return L;
5164 }
5165
5166 // Otherwise, just use the LHS's width.
5167 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5168 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5169 }
5170
5171 // The result of a remainder can't be larger than the result of
5172 // either side.
5173 case BO_Rem: {
5174 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005175 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005176 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5177 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5178
5179 IntRange meet = IntRange::meet(L, R);
5180 meet.Width = std::min(meet.Width, MaxWidth);
5181 return meet;
5182 }
5183
5184 // The default behavior is okay for these.
5185 case BO_Mul:
5186 case BO_Add:
5187 case BO_Xor:
5188 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005189 break;
5190 }
5191
John McCall51431812011-07-14 22:39:48 +00005192 // The default case is to treat the operation as if it were closed
5193 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005194 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5195 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5196 return IntRange::join(L, R);
5197 }
5198
5199 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5200 switch (UO->getOpcode()) {
5201 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005202 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005203 return IntRange::forBoolType();
5204
5205 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005206 case UO_Deref:
5207 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005208 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005209
5210 default:
5211 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5212 }
5213 }
5214
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005215 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5216 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5217
John McCalld25db7e2013-05-06 21:39:12 +00005218 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005219 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005220 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005221
Eli Friedmane6d33952013-07-08 20:20:06 +00005222 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005223}
John McCall263a48b2010-01-04 23:31:57 +00005224
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005225static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005226 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005227}
5228
John McCall263a48b2010-01-04 23:31:57 +00005229/// Checks whether the given value, which currently has the given
5230/// source semantics, has the same value when coerced through the
5231/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005232static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5233 const llvm::fltSemantics &Src,
5234 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005235 llvm::APFloat truncated = value;
5236
5237 bool ignored;
5238 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5239 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5240
5241 return truncated.bitwiseIsEqual(value);
5242}
5243
5244/// Checks whether the given value, which currently has the given
5245/// source semantics, has the same value when coerced through the
5246/// target semantics.
5247///
5248/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005249static bool IsSameFloatAfterCast(const APValue &value,
5250 const llvm::fltSemantics &Src,
5251 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005252 if (value.isFloat())
5253 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5254
5255 if (value.isVector()) {
5256 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5257 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5258 return false;
5259 return true;
5260 }
5261
5262 assert(value.isComplexFloat());
5263 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5264 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5265}
5266
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005267static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005268
Ted Kremenek6274be42010-09-23 21:43:44 +00005269static bool IsZero(Sema &S, Expr *E) {
5270 // Suppress cases where we are comparing against an enum constant.
5271 if (const DeclRefExpr *DR =
5272 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5273 if (isa<EnumConstantDecl>(DR->getDecl()))
5274 return false;
5275
5276 // Suppress cases where the '0' value is expanded from a macro.
5277 if (E->getLocStart().isMacroID())
5278 return false;
5279
John McCallcc7e5bf2010-05-06 08:58:33 +00005280 llvm::APSInt Value;
5281 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5282}
5283
John McCall2551c1b2010-10-06 00:25:24 +00005284static bool HasEnumType(Expr *E) {
5285 // Strip off implicit integral promotions.
5286 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005287 if (ICE->getCastKind() != CK_IntegralCast &&
5288 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005289 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005290 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005291 }
5292
5293 return E->getType()->isEnumeralType();
5294}
5295
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005296static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005297 // Disable warning in template instantiations.
5298 if (!S.ActiveTemplateInstantiations.empty())
5299 return;
5300
John McCalle3027922010-08-25 11:45:40 +00005301 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005302 if (E->isValueDependent())
5303 return;
5304
John McCalle3027922010-08-25 11:45:40 +00005305 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005306 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005307 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005308 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005309 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005310 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005311 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005312 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005313 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005314 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005315 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005316 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005317 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005318 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005319 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005320 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5321 }
5322}
5323
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005324static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005325 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005326 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005327 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005328 // Disable warning in template instantiations.
5329 if (!S.ActiveTemplateInstantiations.empty())
5330 return;
5331
Richard Trieu0f097742014-04-04 04:13:47 +00005332 // TODO: Investigate using GetExprRange() to get tighter bounds
5333 // on the bit ranges.
5334 QualType OtherT = Other->getType();
5335 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5336 unsigned OtherWidth = OtherRange.Width;
5337
5338 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5339
Richard Trieu560910c2012-11-14 22:50:24 +00005340 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005341 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005342 return;
5343
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005344 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005345 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005346
Richard Trieu0f097742014-04-04 04:13:47 +00005347 // Used for diagnostic printout.
5348 enum {
5349 LiteralConstant = 0,
5350 CXXBoolLiteralTrue,
5351 CXXBoolLiteralFalse
5352 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005353
Richard Trieu0f097742014-04-04 04:13:47 +00005354 if (!OtherIsBooleanType) {
5355 QualType ConstantT = Constant->getType();
5356 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005357
Richard Trieu0f097742014-04-04 04:13:47 +00005358 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5359 return;
5360 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5361 "comparison with non-integer type");
5362
5363 bool ConstantSigned = ConstantT->isSignedIntegerType();
5364 bool CommonSigned = CommonT->isSignedIntegerType();
5365
5366 bool EqualityOnly = false;
5367
5368 if (CommonSigned) {
5369 // The common type is signed, therefore no signed to unsigned conversion.
5370 if (!OtherRange.NonNegative) {
5371 // Check that the constant is representable in type OtherT.
5372 if (ConstantSigned) {
5373 if (OtherWidth >= Value.getMinSignedBits())
5374 return;
5375 } else { // !ConstantSigned
5376 if (OtherWidth >= Value.getActiveBits() + 1)
5377 return;
5378 }
5379 } else { // !OtherSigned
5380 // Check that the constant is representable in type OtherT.
5381 // Negative values are out of range.
5382 if (ConstantSigned) {
5383 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5384 return;
5385 } else { // !ConstantSigned
5386 if (OtherWidth >= Value.getActiveBits())
5387 return;
5388 }
Richard Trieu560910c2012-11-14 22:50:24 +00005389 }
Richard Trieu0f097742014-04-04 04:13:47 +00005390 } else { // !CommonSigned
5391 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005392 if (OtherWidth >= Value.getActiveBits())
5393 return;
Craig Toppercf360162014-06-18 05:13:11 +00005394 } else { // OtherSigned
5395 assert(!ConstantSigned &&
5396 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00005397 // Check to see if the constant is representable in OtherT.
5398 if (OtherWidth > Value.getActiveBits())
5399 return;
5400 // Check to see if the constant is equivalent to a negative value
5401 // cast to CommonT.
5402 if (S.Context.getIntWidth(ConstantT) ==
5403 S.Context.getIntWidth(CommonT) &&
5404 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5405 return;
5406 // The constant value rests between values that OtherT can represent
5407 // after conversion. Relational comparison still works, but equality
5408 // comparisons will be tautological.
5409 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005410 }
5411 }
Richard Trieu0f097742014-04-04 04:13:47 +00005412
5413 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5414
5415 if (op == BO_EQ || op == BO_NE) {
5416 IsTrue = op == BO_NE;
5417 } else if (EqualityOnly) {
5418 return;
5419 } else if (RhsConstant) {
5420 if (op == BO_GT || op == BO_GE)
5421 IsTrue = !PositiveConstant;
5422 else // op == BO_LT || op == BO_LE
5423 IsTrue = PositiveConstant;
5424 } else {
5425 if (op == BO_LT || op == BO_LE)
5426 IsTrue = !PositiveConstant;
5427 else // op == BO_GT || op == BO_GE
5428 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005429 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005430 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005431 // Other isKnownToHaveBooleanValue
5432 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5433 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5434 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5435
5436 static const struct LinkedConditions {
5437 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5438 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5439 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5440 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5441 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5442 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5443
5444 } TruthTable = {
5445 // Constant on LHS. | Constant on RHS. |
5446 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5447 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5448 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5449 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5450 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5451 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5452 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5453 };
5454
5455 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5456
5457 enum ConstantValue ConstVal = Zero;
5458 if (Value.isUnsigned() || Value.isNonNegative()) {
5459 if (Value == 0) {
5460 LiteralOrBoolConstant =
5461 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5462 ConstVal = Zero;
5463 } else if (Value == 1) {
5464 LiteralOrBoolConstant =
5465 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5466 ConstVal = One;
5467 } else {
5468 LiteralOrBoolConstant = LiteralConstant;
5469 ConstVal = GT_One;
5470 }
5471 } else {
5472 ConstVal = LT_Zero;
5473 }
5474
5475 CompareBoolWithConstantResult CmpRes;
5476
5477 switch (op) {
5478 case BO_LT:
5479 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5480 break;
5481 case BO_GT:
5482 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5483 break;
5484 case BO_LE:
5485 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5486 break;
5487 case BO_GE:
5488 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5489 break;
5490 case BO_EQ:
5491 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5492 break;
5493 case BO_NE:
5494 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5495 break;
5496 default:
5497 CmpRes = Unkwn;
5498 break;
5499 }
5500
5501 if (CmpRes == AFals) {
5502 IsTrue = false;
5503 } else if (CmpRes == ATrue) {
5504 IsTrue = true;
5505 } else {
5506 return;
5507 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005508 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005509
5510 // If this is a comparison to an enum constant, include that
5511 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005512 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005513 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5514 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5515
5516 SmallString<64> PrettySourceValue;
5517 llvm::raw_svector_ostream OS(PrettySourceValue);
5518 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005519 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005520 else
5521 OS << Value;
5522
Richard Trieu0f097742014-04-04 04:13:47 +00005523 S.DiagRuntimeBehavior(
5524 E->getOperatorLoc(), E,
5525 S.PDiag(diag::warn_out_of_range_compare)
5526 << OS.str() << LiteralOrBoolConstant
5527 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5528 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005529}
5530
John McCallcc7e5bf2010-05-06 08:58:33 +00005531/// Analyze the operands of the given comparison. Implements the
5532/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005533static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005534 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5535 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005536}
John McCall263a48b2010-01-04 23:31:57 +00005537
John McCallca01b222010-01-04 23:21:16 +00005538/// \brief Implements -Wsign-compare.
5539///
Richard Trieu82402a02011-09-15 21:56:47 +00005540/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005541static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005542 // The type the comparison is being performed in.
5543 QualType T = E->getLHS()->getType();
5544 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5545 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005546 if (E->isValueDependent())
5547 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005548
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005549 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5550 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005551
5552 bool IsComparisonConstant = false;
5553
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005554 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005555 // of 'true' or 'false'.
5556 if (T->isIntegralType(S.Context)) {
5557 llvm::APSInt RHSValue;
5558 bool IsRHSIntegralLiteral =
5559 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5560 llvm::APSInt LHSValue;
5561 bool IsLHSIntegralLiteral =
5562 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5563 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5564 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5565 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5566 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5567 else
5568 IsComparisonConstant =
5569 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005570 } else if (!T->hasUnsignedIntegerRepresentation())
5571 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005572
John McCallcc7e5bf2010-05-06 08:58:33 +00005573 // We don't do anything special if this isn't an unsigned integral
5574 // comparison: we're only interested in integral comparisons, and
5575 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005576 //
5577 // We also don't care about value-dependent expressions or expressions
5578 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005579 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005580 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005581
John McCallcc7e5bf2010-05-06 08:58:33 +00005582 // Check to see if one of the (unmodified) operands is of different
5583 // signedness.
5584 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005585 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5586 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005587 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005588 signedOperand = LHS;
5589 unsignedOperand = RHS;
5590 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5591 signedOperand = RHS;
5592 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005593 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005594 CheckTrivialUnsignedComparison(S, E);
5595 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005596 }
5597
John McCallcc7e5bf2010-05-06 08:58:33 +00005598 // Otherwise, calculate the effective range of the signed operand.
5599 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005600
John McCallcc7e5bf2010-05-06 08:58:33 +00005601 // Go ahead and analyze implicit conversions in the operands. Note
5602 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005603 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5604 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005605
John McCallcc7e5bf2010-05-06 08:58:33 +00005606 // If the signed range is non-negative, -Wsign-compare won't fire,
5607 // but we should still check for comparisons which are always true
5608 // or false.
5609 if (signedRange.NonNegative)
5610 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005611
5612 // For (in)equality comparisons, if the unsigned operand is a
5613 // constant which cannot collide with a overflowed signed operand,
5614 // then reinterpreting the signed operand as unsigned will not
5615 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005616 if (E->isEqualityOp()) {
5617 unsigned comparisonWidth = S.Context.getIntWidth(T);
5618 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005619
John McCallcc7e5bf2010-05-06 08:58:33 +00005620 // We should never be unable to prove that the unsigned operand is
5621 // non-negative.
5622 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5623
5624 if (unsignedRange.Width < comparisonWidth)
5625 return;
5626 }
5627
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005628 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5629 S.PDiag(diag::warn_mixed_sign_comparison)
5630 << LHS->getType() << RHS->getType()
5631 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005632}
5633
John McCall1f425642010-11-11 03:21:53 +00005634/// Analyzes an attempt to assign the given value to a bitfield.
5635///
5636/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005637static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5638 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005639 assert(Bitfield->isBitField());
5640 if (Bitfield->isInvalidDecl())
5641 return false;
5642
John McCalldeebbcf2010-11-11 05:33:51 +00005643 // White-list bool bitfields.
5644 if (Bitfield->getType()->isBooleanType())
5645 return false;
5646
Douglas Gregor789adec2011-02-04 13:09:01 +00005647 // Ignore value- or type-dependent expressions.
5648 if (Bitfield->getBitWidth()->isValueDependent() ||
5649 Bitfield->getBitWidth()->isTypeDependent() ||
5650 Init->isValueDependent() ||
5651 Init->isTypeDependent())
5652 return false;
5653
John McCall1f425642010-11-11 03:21:53 +00005654 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5655
Richard Smith5fab0c92011-12-28 19:48:30 +00005656 llvm::APSInt Value;
5657 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005658 return false;
5659
John McCall1f425642010-11-11 03:21:53 +00005660 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005661 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005662
5663 if (OriginalWidth <= FieldWidth)
5664 return false;
5665
Eli Friedmanc267a322012-01-26 23:11:39 +00005666 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005667 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005668 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005669
Eli Friedmanc267a322012-01-26 23:11:39 +00005670 // Check whether the stored value is equal to the original value.
5671 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005672 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005673 return false;
5674
Eli Friedmanc267a322012-01-26 23:11:39 +00005675 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005676 // therefore don't strictly fit into a signed bitfield of width 1.
5677 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005678 return false;
5679
John McCall1f425642010-11-11 03:21:53 +00005680 std::string PrettyValue = Value.toString(10);
5681 std::string PrettyTrunc = TruncatedValue.toString(10);
5682
5683 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5684 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5685 << Init->getSourceRange();
5686
5687 return true;
5688}
5689
John McCalld2a53122010-11-09 23:24:47 +00005690/// Analyze the given simple or compound assignment for warning-worthy
5691/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005692static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005693 // Just recurse on the LHS.
5694 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5695
5696 // We want to recurse on the RHS as normal unless we're assigning to
5697 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005698 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005699 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005700 E->getOperatorLoc())) {
5701 // Recurse, ignoring any implicit conversions on the RHS.
5702 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5703 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005704 }
5705 }
5706
5707 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5708}
5709
John McCall263a48b2010-01-04 23:31:57 +00005710/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005711static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005712 SourceLocation CContext, unsigned diag,
5713 bool pruneControlFlow = false) {
5714 if (pruneControlFlow) {
5715 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5716 S.PDiag(diag)
5717 << SourceType << T << E->getSourceRange()
5718 << SourceRange(CContext));
5719 return;
5720 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005721 S.Diag(E->getExprLoc(), diag)
5722 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5723}
5724
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005725/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005726static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005727 SourceLocation CContext, unsigned diag,
5728 bool pruneControlFlow = false) {
5729 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005730}
5731
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005732/// Diagnose an implicit cast from a literal expression. Does not warn when the
5733/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005734void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5735 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005736 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005737 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005738 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005739 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5740 T->hasUnsignedIntegerRepresentation());
5741 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005742 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005743 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005744 return;
5745
Eli Friedman07185912013-08-29 23:44:43 +00005746 // FIXME: Force the precision of the source value down so we don't print
5747 // digits which are usually useless (we don't really care here if we
5748 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5749 // would automatically print the shortest representation, but it's a bit
5750 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005751 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005752 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5753 precision = (precision * 59 + 195) / 196;
5754 Value.toString(PrettySourceValue, precision);
5755
David Blaikie9b88cc02012-05-15 17:18:27 +00005756 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005757 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5758 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5759 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005760 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005761
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005762 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005763 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5764 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005765}
5766
John McCall18a2c2c2010-11-09 22:22:12 +00005767std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5768 if (!Range.Width) return "0";
5769
5770 llvm::APSInt ValueInRange = Value;
5771 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005772 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005773 return ValueInRange.toString(10);
5774}
5775
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005776static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5777 if (!isa<ImplicitCastExpr>(Ex))
5778 return false;
5779
5780 Expr *InnerE = Ex->IgnoreParenImpCasts();
5781 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5782 const Type *Source =
5783 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5784 if (Target->isDependentType())
5785 return false;
5786
5787 const BuiltinType *FloatCandidateBT =
5788 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5789 const Type *BoolCandidateType = ToBool ? Target : Source;
5790
5791 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5792 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5793}
5794
5795void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5796 SourceLocation CC) {
5797 unsigned NumArgs = TheCall->getNumArgs();
5798 for (unsigned i = 0; i < NumArgs; ++i) {
5799 Expr *CurrA = TheCall->getArg(i);
5800 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5801 continue;
5802
5803 bool IsSwapped = ((i > 0) &&
5804 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5805 IsSwapped |= ((i < (NumArgs - 1)) &&
5806 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5807 if (IsSwapped) {
5808 // Warn on this floating-point to bool conversion.
5809 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5810 CurrA->getType(), CC,
5811 diag::warn_impcast_floating_point_to_bool);
5812 }
5813 }
5814}
5815
John McCallcc7e5bf2010-05-06 08:58:33 +00005816void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005817 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005818 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005819
John McCallcc7e5bf2010-05-06 08:58:33 +00005820 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5821 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5822 if (Source == Target) return;
5823 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005824
Chandler Carruthc22845a2011-07-26 05:40:03 +00005825 // If the conversion context location is invalid don't complain. We also
5826 // don't want to emit a warning if the issue occurs from the expansion of
5827 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5828 // delay this check as long as possible. Once we detect we are in that
5829 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005830 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005831 return;
5832
Richard Trieu021baa32011-09-23 20:10:00 +00005833 // Diagnose implicit casts to bool.
5834 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5835 if (isa<StringLiteral>(E))
5836 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005837 // and expressions, for instance, assert(0 && "error here"), are
5838 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005839 return DiagnoseImpCast(S, E, T, CC,
5840 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005841 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5842 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5843 // This covers the literal expressions that evaluate to Objective-C
5844 // objects.
5845 return DiagnoseImpCast(S, E, T, CC,
5846 diag::warn_impcast_objective_c_literal_to_bool);
5847 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005848 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5849 // Warn on pointer to bool conversion that is always true.
5850 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5851 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005852 }
Richard Trieu021baa32011-09-23 20:10:00 +00005853 }
John McCall263a48b2010-01-04 23:31:57 +00005854
5855 // Strip vector types.
5856 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005857 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005858 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005859 return;
John McCallacf0ee52010-10-08 02:01:28 +00005860 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005861 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005862
5863 // If the vector cast is cast between two vectors of the same size, it is
5864 // a bitcast, not a conversion.
5865 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5866 return;
John McCall263a48b2010-01-04 23:31:57 +00005867
5868 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5869 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5870 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005871 if (auto VecTy = dyn_cast<VectorType>(Target))
5872 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005873
5874 // Strip complex types.
5875 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005876 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005877 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005878 return;
5879
John McCallacf0ee52010-10-08 02:01:28 +00005880 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005881 }
John McCall263a48b2010-01-04 23:31:57 +00005882
5883 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5884 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5885 }
5886
5887 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5888 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5889
5890 // If the source is floating point...
5891 if (SourceBT && SourceBT->isFloatingPoint()) {
5892 // ...and the target is floating point...
5893 if (TargetBT && TargetBT->isFloatingPoint()) {
5894 // ...then warn if we're dropping FP rank.
5895
5896 // Builtin FP kinds are ordered by increasing FP rank.
5897 if (SourceBT->getKind() > TargetBT->getKind()) {
5898 // Don't warn about float constants that are precisely
5899 // representable in the target type.
5900 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005901 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005902 // Value might be a float, a float vector, or a float complex.
5903 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005904 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5905 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005906 return;
5907 }
5908
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005909 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005910 return;
5911
John McCallacf0ee52010-10-08 02:01:28 +00005912 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005913 }
5914 return;
5915 }
5916
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005917 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005918 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005919 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005920 return;
5921
Chandler Carruth22c7a792011-02-17 11:05:49 +00005922 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005923 // We also want to warn on, e.g., "int i = -1.234"
5924 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5925 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5926 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5927
Chandler Carruth016ef402011-04-10 08:36:24 +00005928 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5929 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005930 } else {
5931 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5932 }
5933 }
John McCall263a48b2010-01-04 23:31:57 +00005934
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005935 // If the target is bool, warn if expr is a function or method call.
5936 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5937 isa<CallExpr>(E)) {
5938 // Check last argument of function call to see if it is an
5939 // implicit cast from a type matching the type the result
5940 // is being cast to.
5941 CallExpr *CEx = cast<CallExpr>(E);
5942 unsigned NumArgs = CEx->getNumArgs();
5943 if (NumArgs > 0) {
5944 Expr *LastA = CEx->getArg(NumArgs - 1);
5945 Expr *InnerE = LastA->IgnoreParenImpCasts();
5946 const Type *InnerType =
5947 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5948 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5949 // Warn on this floating-point to bool conversion
5950 DiagnoseImpCast(S, E, T, CC,
5951 diag::warn_impcast_floating_point_to_bool);
5952 }
5953 }
5954 }
John McCall263a48b2010-01-04 23:31:57 +00005955 return;
5956 }
5957
Richard Trieubeaf3452011-05-29 19:59:02 +00005958 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005959 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005960 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005961 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005962 SourceLocation Loc = E->getSourceRange().getBegin();
5963 if (Loc.isMacroID())
5964 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005965 if (!Loc.isMacroID() || CC.isMacroID())
5966 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5967 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005968 << FixItHint::CreateReplacement(Loc,
5969 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005970 }
5971
David Blaikie9366d2b2012-06-19 21:19:06 +00005972 if (!Source->isIntegerType() || !Target->isIntegerType())
5973 return;
5974
David Blaikie7555b6a2012-05-15 16:56:36 +00005975 // TODO: remove this early return once the false positives for constant->bool
5976 // in templates, macros, etc, are reduced or removed.
5977 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5978 return;
5979
John McCallcc7e5bf2010-05-06 08:58:33 +00005980 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005981 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005982
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005983 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005984 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005985 // TODO: this should happen for bitfield stores, too.
5986 llvm::APSInt Value(32);
5987 if (E->isIntegerConstantExpr(Value, S.Context)) {
5988 if (S.SourceMgr.isInSystemMacro(CC))
5989 return;
5990
John McCall18a2c2c2010-11-09 22:22:12 +00005991 std::string PrettySourceValue = Value.toString(10);
5992 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005993
Ted Kremenek33ba9952011-10-22 02:37:33 +00005994 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5995 S.PDiag(diag::warn_impcast_integer_precision_constant)
5996 << PrettySourceValue << PrettyTargetValue
5997 << E->getType() << T << E->getSourceRange()
5998 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005999 return;
6000 }
6001
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006002 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6003 if (S.SourceMgr.isInSystemMacro(CC))
6004 return;
6005
David Blaikie9455da02012-04-12 22:40:54 +00006006 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006007 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6008 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006009 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006010 }
6011
6012 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6013 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6014 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006015
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006016 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006017 return;
6018
John McCallcc7e5bf2010-05-06 08:58:33 +00006019 unsigned DiagID = diag::warn_impcast_integer_sign;
6020
6021 // Traditionally, gcc has warned about this under -Wsign-compare.
6022 // We also want to warn about it in -Wconversion.
6023 // So if -Wconversion is off, use a completely identical diagnostic
6024 // in the sign-compare group.
6025 // The conditional-checking code will
6026 if (ICContext) {
6027 DiagID = diag::warn_impcast_integer_sign_conditional;
6028 *ICContext = true;
6029 }
6030
John McCallacf0ee52010-10-08 02:01:28 +00006031 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006032 }
6033
Douglas Gregora78f1932011-02-22 02:45:07 +00006034 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006035 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6036 // type, to give us better diagnostics.
6037 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006038 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006039 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6040 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6041 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6042 SourceType = S.Context.getTypeDeclType(Enum);
6043 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6044 }
6045 }
6046
Douglas Gregora78f1932011-02-22 02:45:07 +00006047 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6048 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006049 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6050 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006051 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006052 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006053 return;
6054
Douglas Gregor364f7db2011-03-12 00:14:31 +00006055 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006056 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006057 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006058
John McCall263a48b2010-01-04 23:31:57 +00006059 return;
6060}
6061
David Blaikie18e9ac72012-05-15 21:57:38 +00006062void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6063 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006064
6065void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006066 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006067 E = E->IgnoreParenImpCasts();
6068
6069 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006070 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006071
John McCallacf0ee52010-10-08 02:01:28 +00006072 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006073 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006074 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006075 return;
6076}
6077
David Blaikie18e9ac72012-05-15 21:57:38 +00006078void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6079 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006080 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006081
6082 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006083 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6084 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006085
6086 // If -Wconversion would have warned about either of the candidates
6087 // for a signedness conversion to the context type...
6088 if (!Suspicious) return;
6089
6090 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006091 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006092 return;
6093
John McCallcc7e5bf2010-05-06 08:58:33 +00006094 // ...then check whether it would have warned about either of the
6095 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006096 if (E->getType() == T) return;
6097
6098 Suspicious = false;
6099 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6100 E->getType(), CC, &Suspicious);
6101 if (!Suspicious)
6102 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006103 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006104}
6105
6106/// AnalyzeImplicitConversions - Find and report any interesting
6107/// implicit conversions in the given expression. There are a couple
6108/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006109void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006110 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006111 Expr *E = OrigE->IgnoreParenImpCasts();
6112
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006113 if (E->isTypeDependent() || E->isValueDependent())
6114 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006115
John McCallcc7e5bf2010-05-06 08:58:33 +00006116 // For conditional operators, we analyze the arguments as if they
6117 // were being fed directly into the output.
6118 if (isa<ConditionalOperator>(E)) {
6119 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006120 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006121 return;
6122 }
6123
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006124 // Check implicit argument conversions for function calls.
6125 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6126 CheckImplicitArgumentConversions(S, Call, CC);
6127
John McCallcc7e5bf2010-05-06 08:58:33 +00006128 // Go ahead and check any implicit conversions we might have skipped.
6129 // The non-canonical typecheck is just an optimization;
6130 // CheckImplicitConversion will filter out dead implicit conversions.
6131 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006132 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006133
6134 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006135
6136 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006137 if (POE->getResultExpr())
6138 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006139 }
6140
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006141 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6142 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6143
John McCallcc7e5bf2010-05-06 08:58:33 +00006144 // Skip past explicit casts.
6145 if (isa<ExplicitCastExpr>(E)) {
6146 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006147 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006148 }
6149
John McCalld2a53122010-11-09 23:24:47 +00006150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6151 // Do a somewhat different check with comparison operators.
6152 if (BO->isComparisonOp())
6153 return AnalyzeComparison(S, BO);
6154
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006155 // And with simple assignments.
6156 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006157 return AnalyzeAssignment(S, BO);
6158 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006159
6160 // These break the otherwise-useful invariant below. Fortunately,
6161 // we don't really need to recurse into them, because any internal
6162 // expressions should have been analyzed already when they were
6163 // built into statements.
6164 if (isa<StmtExpr>(E)) return;
6165
6166 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006167 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006168
6169 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006170 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006171 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006172 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006173 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006174 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006175 if (!ChildExpr)
6176 continue;
6177
Richard Trieu955231d2014-01-25 01:10:35 +00006178 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006179 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006180 // Ignore checking string literals that are in logical and operators.
6181 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006182 continue;
6183 AnalyzeImplicitConversions(S, ChildExpr, CC);
6184 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006185}
6186
6187} // end anonymous namespace
6188
Richard Trieu3bb8b562014-02-26 02:36:06 +00006189enum {
6190 AddressOf,
6191 FunctionPointer,
6192 ArrayPointer
6193};
6194
6195/// \brief Diagnose pointers that are always non-null.
6196/// \param E the expression containing the pointer
6197/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6198/// compared to a null pointer
6199/// \param IsEqual True when the comparison is equal to a null pointer
6200/// \param Range Extra SourceRange to highlight in the diagnostic
6201void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6202 Expr::NullPointerConstantKind NullKind,
6203 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006204 if (!E)
6205 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006206
6207 // Don't warn inside macros.
6208 if (E->getExprLoc().isMacroID())
6209 return;
6210 E = E->IgnoreImpCasts();
6211
6212 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6213
Richard Trieuf7432752014-06-06 21:39:26 +00006214 if (isa<CXXThisExpr>(E)) {
6215 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6216 : diag::warn_this_bool_conversion;
6217 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6218 return;
6219 }
6220
Richard Trieu3bb8b562014-02-26 02:36:06 +00006221 bool IsAddressOf = false;
6222
6223 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6224 if (UO->getOpcode() != UO_AddrOf)
6225 return;
6226 IsAddressOf = true;
6227 E = UO->getSubExpr();
6228 }
6229
6230 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006231 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006232 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6233 D = R->getDecl();
6234 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6235 D = M->getMemberDecl();
6236 }
6237
6238 // Weak Decls can be null.
6239 if (!D || D->isWeak())
6240 return;
6241
6242 QualType T = D->getType();
6243 const bool IsArray = T->isArrayType();
6244 const bool IsFunction = T->isFunctionType();
6245
6246 if (IsAddressOf) {
6247 // Address of function is used to silence the function warning.
6248 if (IsFunction)
6249 return;
Richard Trieuf7432752014-06-06 21:39:26 +00006250
6251 if (T->isReferenceType()) {
6252 unsigned DiagID = IsCompare
6253 ? diag::warn_address_of_reference_null_compare
6254 : diag::warn_address_of_reference_bool_conversion;
6255 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006256 return;
Richard Trieuf7432752014-06-06 21:39:26 +00006257 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006258 }
6259
6260 // Found nothing.
6261 if (!IsAddressOf && !IsFunction && !IsArray)
6262 return;
6263
6264 // Pretty print the expression for the diagnostic.
6265 std::string Str;
6266 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006267 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006268
6269 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6270 : diag::warn_impcast_pointer_to_bool;
6271 unsigned DiagType;
6272 if (IsAddressOf)
6273 DiagType = AddressOf;
6274 else if (IsFunction)
6275 DiagType = FunctionPointer;
6276 else if (IsArray)
6277 DiagType = ArrayPointer;
6278 else
6279 llvm_unreachable("Could not determine diagnostic.");
6280 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6281 << Range << IsEqual;
6282
6283 if (!IsFunction)
6284 return;
6285
6286 // Suggest '&' to silence the function warning.
6287 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6288 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6289
6290 // Check to see if '()' fixit should be emitted.
6291 QualType ReturnType;
6292 UnresolvedSet<4> NonTemplateOverloads;
6293 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6294 if (ReturnType.isNull())
6295 return;
6296
6297 if (IsCompare) {
6298 // There are two cases here. If there is null constant, the only suggest
6299 // for a pointer return type. If the null is 0, then suggest if the return
6300 // type is a pointer or an integer type.
6301 if (!ReturnType->isPointerType()) {
6302 if (NullKind == Expr::NPCK_ZeroExpression ||
6303 NullKind == Expr::NPCK_ZeroLiteral) {
6304 if (!ReturnType->isIntegerType())
6305 return;
6306 } else {
6307 return;
6308 }
6309 }
6310 } else { // !IsCompare
6311 // For function to bool, only suggest if the function pointer has bool
6312 // return type.
6313 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6314 return;
6315 }
6316 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006317 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006318}
6319
6320
John McCallcc7e5bf2010-05-06 08:58:33 +00006321/// Diagnoses "dangerous" implicit conversions within the given
6322/// expression (which is a full expression). Implements -Wconversion
6323/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006324///
6325/// \param CC the "context" location of the implicit conversion, i.e.
6326/// the most location of the syntactic entity requiring the implicit
6327/// conversion
6328void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006329 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006330 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006331 return;
6332
6333 // Don't diagnose for value- or type-dependent expressions.
6334 if (E->isTypeDependent() || E->isValueDependent())
6335 return;
6336
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006337 // Check for array bounds violations in cases where the check isn't triggered
6338 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6339 // ArraySubscriptExpr is on the RHS of a variable initialization.
6340 CheckArrayAccess(E);
6341
John McCallacf0ee52010-10-08 02:01:28 +00006342 // This is not the right CC for (e.g.) a variable initialization.
6343 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006344}
6345
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006346/// Diagnose when expression is an integer constant expression and its evaluation
6347/// results in integer overflow
6348void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006349 if (isa<BinaryOperator>(E->IgnoreParens()))
6350 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006351}
6352
Richard Smithc406cb72013-01-17 01:17:56 +00006353namespace {
6354/// \brief Visitor for expressions which looks for unsequenced operations on the
6355/// same object.
6356class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006357 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6358
Richard Smithc406cb72013-01-17 01:17:56 +00006359 /// \brief A tree of sequenced regions within an expression. Two regions are
6360 /// unsequenced if one is an ancestor or a descendent of the other. When we
6361 /// finish processing an expression with sequencing, such as a comma
6362 /// expression, we fold its tree nodes into its parent, since they are
6363 /// unsequenced with respect to nodes we will visit later.
6364 class SequenceTree {
6365 struct Value {
6366 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6367 unsigned Parent : 31;
6368 bool Merged : 1;
6369 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006370 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006371
6372 public:
6373 /// \brief A region within an expression which may be sequenced with respect
6374 /// to some other region.
6375 class Seq {
6376 explicit Seq(unsigned N) : Index(N) {}
6377 unsigned Index;
6378 friend class SequenceTree;
6379 public:
6380 Seq() : Index(0) {}
6381 };
6382
6383 SequenceTree() { Values.push_back(Value(0)); }
6384 Seq root() const { return Seq(0); }
6385
6386 /// \brief Create a new sequence of operations, which is an unsequenced
6387 /// subset of \p Parent. This sequence of operations is sequenced with
6388 /// respect to other children of \p Parent.
6389 Seq allocate(Seq Parent) {
6390 Values.push_back(Value(Parent.Index));
6391 return Seq(Values.size() - 1);
6392 }
6393
6394 /// \brief Merge a sequence of operations into its parent.
6395 void merge(Seq S) {
6396 Values[S.Index].Merged = true;
6397 }
6398
6399 /// \brief Determine whether two operations are unsequenced. This operation
6400 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6401 /// should have been merged into its parent as appropriate.
6402 bool isUnsequenced(Seq Cur, Seq Old) {
6403 unsigned C = representative(Cur.Index);
6404 unsigned Target = representative(Old.Index);
6405 while (C >= Target) {
6406 if (C == Target)
6407 return true;
6408 C = Values[C].Parent;
6409 }
6410 return false;
6411 }
6412
6413 private:
6414 /// \brief Pick a representative for a sequence.
6415 unsigned representative(unsigned K) {
6416 if (Values[K].Merged)
6417 // Perform path compression as we go.
6418 return Values[K].Parent = representative(Values[K].Parent);
6419 return K;
6420 }
6421 };
6422
6423 /// An object for which we can track unsequenced uses.
6424 typedef NamedDecl *Object;
6425
6426 /// Different flavors of object usage which we track. We only track the
6427 /// least-sequenced usage of each kind.
6428 enum UsageKind {
6429 /// A read of an object. Multiple unsequenced reads are OK.
6430 UK_Use,
6431 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006432 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006433 UK_ModAsValue,
6434 /// A modification of an object which is not sequenced before the value
6435 /// computation of the expression, such as n++.
6436 UK_ModAsSideEffect,
6437
6438 UK_Count = UK_ModAsSideEffect + 1
6439 };
6440
6441 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006442 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006443 Expr *Use;
6444 SequenceTree::Seq Seq;
6445 };
6446
6447 struct UsageInfo {
6448 UsageInfo() : Diagnosed(false) {}
6449 Usage Uses[UK_Count];
6450 /// Have we issued a diagnostic for this variable already?
6451 bool Diagnosed;
6452 };
6453 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6454
6455 Sema &SemaRef;
6456 /// Sequenced regions within the expression.
6457 SequenceTree Tree;
6458 /// Declaration modifications and references which we have seen.
6459 UsageInfoMap UsageMap;
6460 /// The region we are currently within.
6461 SequenceTree::Seq Region;
6462 /// Filled in with declarations which were modified as a side-effect
6463 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006464 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006465 /// Expressions to check later. We defer checking these to reduce
6466 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006467 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006468
6469 /// RAII object wrapping the visitation of a sequenced subexpression of an
6470 /// expression. At the end of this process, the side-effects of the evaluation
6471 /// become sequenced with respect to the value computation of the result, so
6472 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6473 /// UK_ModAsValue.
6474 struct SequencedSubexpression {
6475 SequencedSubexpression(SequenceChecker &Self)
6476 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6477 Self.ModAsSideEffect = &ModAsSideEffect;
6478 }
6479 ~SequencedSubexpression() {
6480 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6481 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6482 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6483 Self.addUsage(U, ModAsSideEffect[I].first,
6484 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6485 }
6486 Self.ModAsSideEffect = OldModAsSideEffect;
6487 }
6488
6489 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006490 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6491 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006492 };
6493
Richard Smith40238f02013-06-20 22:21:56 +00006494 /// RAII object wrapping the visitation of a subexpression which we might
6495 /// choose to evaluate as a constant. If any subexpression is evaluated and
6496 /// found to be non-constant, this allows us to suppress the evaluation of
6497 /// the outer expression.
6498 class EvaluationTracker {
6499 public:
6500 EvaluationTracker(SequenceChecker &Self)
6501 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6502 Self.EvalTracker = this;
6503 }
6504 ~EvaluationTracker() {
6505 Self.EvalTracker = Prev;
6506 if (Prev)
6507 Prev->EvalOK &= EvalOK;
6508 }
6509
6510 bool evaluate(const Expr *E, bool &Result) {
6511 if (!EvalOK || E->isValueDependent())
6512 return false;
6513 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6514 return EvalOK;
6515 }
6516
6517 private:
6518 SequenceChecker &Self;
6519 EvaluationTracker *Prev;
6520 bool EvalOK;
6521 } *EvalTracker;
6522
Richard Smithc406cb72013-01-17 01:17:56 +00006523 /// \brief Find the object which is produced by the specified expression,
6524 /// if any.
6525 Object getObject(Expr *E, bool Mod) const {
6526 E = E->IgnoreParenCasts();
6527 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6528 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6529 return getObject(UO->getSubExpr(), Mod);
6530 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6531 if (BO->getOpcode() == BO_Comma)
6532 return getObject(BO->getRHS(), Mod);
6533 if (Mod && BO->isAssignmentOp())
6534 return getObject(BO->getLHS(), Mod);
6535 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6536 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6537 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6538 return ME->getMemberDecl();
6539 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6540 // FIXME: If this is a reference, map through to its value.
6541 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006542 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006543 }
6544
6545 /// \brief Note that an object was modified or used by an expression.
6546 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6547 Usage &U = UI.Uses[UK];
6548 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6549 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6550 ModAsSideEffect->push_back(std::make_pair(O, U));
6551 U.Use = Ref;
6552 U.Seq = Region;
6553 }
6554 }
6555 /// \brief Check whether a modification or use conflicts with a prior usage.
6556 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6557 bool IsModMod) {
6558 if (UI.Diagnosed)
6559 return;
6560
6561 const Usage &U = UI.Uses[OtherKind];
6562 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6563 return;
6564
6565 Expr *Mod = U.Use;
6566 Expr *ModOrUse = Ref;
6567 if (OtherKind == UK_Use)
6568 std::swap(Mod, ModOrUse);
6569
6570 SemaRef.Diag(Mod->getExprLoc(),
6571 IsModMod ? diag::warn_unsequenced_mod_mod
6572 : diag::warn_unsequenced_mod_use)
6573 << O << SourceRange(ModOrUse->getExprLoc());
6574 UI.Diagnosed = true;
6575 }
6576
6577 void notePreUse(Object O, Expr *Use) {
6578 UsageInfo &U = UsageMap[O];
6579 // Uses conflict with other modifications.
6580 checkUsage(O, U, Use, UK_ModAsValue, false);
6581 }
6582 void notePostUse(Object O, Expr *Use) {
6583 UsageInfo &U = UsageMap[O];
6584 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6585 addUsage(U, O, Use, UK_Use);
6586 }
6587
6588 void notePreMod(Object O, Expr *Mod) {
6589 UsageInfo &U = UsageMap[O];
6590 // Modifications conflict with other modifications and with uses.
6591 checkUsage(O, U, Mod, UK_ModAsValue, true);
6592 checkUsage(O, U, Mod, UK_Use, false);
6593 }
6594 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6595 UsageInfo &U = UsageMap[O];
6596 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6597 addUsage(U, O, Use, UK);
6598 }
6599
6600public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006601 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006602 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6603 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006604 Visit(E);
6605 }
6606
6607 void VisitStmt(Stmt *S) {
6608 // Skip all statements which aren't expressions for now.
6609 }
6610
6611 void VisitExpr(Expr *E) {
6612 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006613 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006614 }
6615
6616 void VisitCastExpr(CastExpr *E) {
6617 Object O = Object();
6618 if (E->getCastKind() == CK_LValueToRValue)
6619 O = getObject(E->getSubExpr(), false);
6620
6621 if (O)
6622 notePreUse(O, E);
6623 VisitExpr(E);
6624 if (O)
6625 notePostUse(O, E);
6626 }
6627
6628 void VisitBinComma(BinaryOperator *BO) {
6629 // C++11 [expr.comma]p1:
6630 // Every value computation and side effect associated with the left
6631 // expression is sequenced before every value computation and side
6632 // effect associated with the right expression.
6633 SequenceTree::Seq LHS = Tree.allocate(Region);
6634 SequenceTree::Seq RHS = Tree.allocate(Region);
6635 SequenceTree::Seq OldRegion = Region;
6636
6637 {
6638 SequencedSubexpression SeqLHS(*this);
6639 Region = LHS;
6640 Visit(BO->getLHS());
6641 }
6642
6643 Region = RHS;
6644 Visit(BO->getRHS());
6645
6646 Region = OldRegion;
6647
6648 // Forget that LHS and RHS are sequenced. They are both unsequenced
6649 // with respect to other stuff.
6650 Tree.merge(LHS);
6651 Tree.merge(RHS);
6652 }
6653
6654 void VisitBinAssign(BinaryOperator *BO) {
6655 // The modification is sequenced after the value computation of the LHS
6656 // and RHS, so check it before inspecting the operands and update the
6657 // map afterwards.
6658 Object O = getObject(BO->getLHS(), true);
6659 if (!O)
6660 return VisitExpr(BO);
6661
6662 notePreMod(O, BO);
6663
6664 // C++11 [expr.ass]p7:
6665 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6666 // only once.
6667 //
6668 // Therefore, for a compound assignment operator, O is considered used
6669 // everywhere except within the evaluation of E1 itself.
6670 if (isa<CompoundAssignOperator>(BO))
6671 notePreUse(O, BO);
6672
6673 Visit(BO->getLHS());
6674
6675 if (isa<CompoundAssignOperator>(BO))
6676 notePostUse(O, BO);
6677
6678 Visit(BO->getRHS());
6679
Richard Smith83e37bee2013-06-26 23:16:51 +00006680 // C++11 [expr.ass]p1:
6681 // the assignment is sequenced [...] before the value computation of the
6682 // assignment expression.
6683 // C11 6.5.16/3 has no such rule.
6684 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6685 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006686 }
6687 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6688 VisitBinAssign(CAO);
6689 }
6690
6691 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6692 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6693 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6694 Object O = getObject(UO->getSubExpr(), true);
6695 if (!O)
6696 return VisitExpr(UO);
6697
6698 notePreMod(O, UO);
6699 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006700 // C++11 [expr.pre.incr]p1:
6701 // the expression ++x is equivalent to x+=1
6702 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6703 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006704 }
6705
6706 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6707 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6708 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6709 Object O = getObject(UO->getSubExpr(), true);
6710 if (!O)
6711 return VisitExpr(UO);
6712
6713 notePreMod(O, UO);
6714 Visit(UO->getSubExpr());
6715 notePostMod(O, UO, UK_ModAsSideEffect);
6716 }
6717
6718 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6719 void VisitBinLOr(BinaryOperator *BO) {
6720 // The side-effects of the LHS of an '&&' are sequenced before the
6721 // value computation of the RHS, and hence before the value computation
6722 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6723 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006724 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006725 {
6726 SequencedSubexpression Sequenced(*this);
6727 Visit(BO->getLHS());
6728 }
6729
6730 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006731 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006732 if (!Result)
6733 Visit(BO->getRHS());
6734 } else {
6735 // Check for unsequenced operations in the RHS, treating it as an
6736 // entirely separate evaluation.
6737 //
6738 // FIXME: If there are operations in the RHS which are unsequenced
6739 // with respect to operations outside the RHS, and those operations
6740 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006741 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006742 }
Richard Smithc406cb72013-01-17 01:17:56 +00006743 }
6744 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006745 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006746 {
6747 SequencedSubexpression Sequenced(*this);
6748 Visit(BO->getLHS());
6749 }
6750
6751 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006752 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006753 if (Result)
6754 Visit(BO->getRHS());
6755 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006756 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006757 }
Richard Smithc406cb72013-01-17 01:17:56 +00006758 }
6759
6760 // Only visit the condition, unless we can be sure which subexpression will
6761 // be chosen.
6762 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006763 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006764 {
6765 SequencedSubexpression Sequenced(*this);
6766 Visit(CO->getCond());
6767 }
Richard Smithc406cb72013-01-17 01:17:56 +00006768
6769 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006770 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006771 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006772 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006773 WorkList.push_back(CO->getTrueExpr());
6774 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006775 }
Richard Smithc406cb72013-01-17 01:17:56 +00006776 }
6777
Richard Smithe3dbfe02013-06-30 10:40:20 +00006778 void VisitCallExpr(CallExpr *CE) {
6779 // C++11 [intro.execution]p15:
6780 // When calling a function [...], every value computation and side effect
6781 // associated with any argument expression, or with the postfix expression
6782 // designating the called function, is sequenced before execution of every
6783 // expression or statement in the body of the function [and thus before
6784 // the value computation of its result].
6785 SequencedSubexpression Sequenced(*this);
6786 Base::VisitCallExpr(CE);
6787
6788 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6789 }
6790
Richard Smithc406cb72013-01-17 01:17:56 +00006791 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006792 // This is a call, so all subexpressions are sequenced before the result.
6793 SequencedSubexpression Sequenced(*this);
6794
Richard Smithc406cb72013-01-17 01:17:56 +00006795 if (!CCE->isListInitialization())
6796 return VisitExpr(CCE);
6797
6798 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006799 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006800 SequenceTree::Seq Parent = Region;
6801 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6802 E = CCE->arg_end();
6803 I != E; ++I) {
6804 Region = Tree.allocate(Parent);
6805 Elts.push_back(Region);
6806 Visit(*I);
6807 }
6808
6809 // Forget that the initializers are sequenced.
6810 Region = Parent;
6811 for (unsigned I = 0; I < Elts.size(); ++I)
6812 Tree.merge(Elts[I]);
6813 }
6814
6815 void VisitInitListExpr(InitListExpr *ILE) {
6816 if (!SemaRef.getLangOpts().CPlusPlus11)
6817 return VisitExpr(ILE);
6818
6819 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006820 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006821 SequenceTree::Seq Parent = Region;
6822 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6823 Expr *E = ILE->getInit(I);
6824 if (!E) continue;
6825 Region = Tree.allocate(Parent);
6826 Elts.push_back(Region);
6827 Visit(E);
6828 }
6829
6830 // Forget that the initializers are sequenced.
6831 Region = Parent;
6832 for (unsigned I = 0; I < Elts.size(); ++I)
6833 Tree.merge(Elts[I]);
6834 }
6835};
6836}
6837
6838void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006839 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006840 WorkList.push_back(E);
6841 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006842 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006843 SequenceChecker(*this, Item, WorkList);
6844 }
Richard Smithc406cb72013-01-17 01:17:56 +00006845}
6846
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006847void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6848 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006849 CheckImplicitConversions(E, CheckLoc);
6850 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006851 if (!IsConstexpr && !E->isValueDependent())
6852 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006853}
6854
John McCall1f425642010-11-11 03:21:53 +00006855void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6856 FieldDecl *BitField,
6857 Expr *Init) {
6858 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6859}
6860
Mike Stump0c2ec772010-01-21 03:59:47 +00006861/// CheckParmsForFunctionDef - Check that the parameters of the given
6862/// function are appropriate for the definition of a function. This
6863/// takes care of any checks that cannot be performed on the
6864/// declaration itself, e.g., that the types of each of the function
6865/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006866bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6867 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006868 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006869 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006870 for (; P != PEnd; ++P) {
6871 ParmVarDecl *Param = *P;
6872
Mike Stump0c2ec772010-01-21 03:59:47 +00006873 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6874 // function declarator that is part of a function definition of
6875 // that function shall not have incomplete type.
6876 //
6877 // This is also C++ [dcl.fct]p6.
6878 if (!Param->isInvalidDecl() &&
6879 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006880 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006881 Param->setInvalidDecl();
6882 HasInvalidParm = true;
6883 }
6884
6885 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6886 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006887 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00006888 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006889 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006890 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006891 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006892
6893 // C99 6.7.5.3p12:
6894 // If the function declarator is not part of a definition of that
6895 // function, parameters may have incomplete type and may use the [*]
6896 // notation in their sequences of declarator specifiers to specify
6897 // variable length array types.
6898 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006899 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006900 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006901 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006902 // information is added for it.
6903 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006904 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006905 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006906 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006907 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006908
6909 // MSVC destroys objects passed by value in the callee. Therefore a
6910 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006911 // object's destructor. However, we don't perform any direct access check
6912 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006913 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6914 .getCXXABI()
6915 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006916 if (!Param->isInvalidDecl()) {
6917 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6918 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6919 if (!ClassDecl->isInvalidDecl() &&
6920 !ClassDecl->hasIrrelevantDestructor() &&
6921 !ClassDecl->isDependentContext()) {
6922 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6923 MarkFunctionReferenced(Param->getLocation(), Destructor);
6924 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6925 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006926 }
6927 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006928 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006929 }
6930
6931 return HasInvalidParm;
6932}
John McCall2b5c1b22010-08-12 21:44:57 +00006933
6934/// CheckCastAlign - Implements -Wcast-align, which warns when a
6935/// pointer cast increases the alignment requirements.
6936void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6937 // This is actually a lot of work to potentially be doing on every
6938 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006939 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00006940 return;
6941
6942 // Ignore dependent types.
6943 if (T->isDependentType() || Op->getType()->isDependentType())
6944 return;
6945
6946 // Require that the destination be a pointer type.
6947 const PointerType *DestPtr = T->getAs<PointerType>();
6948 if (!DestPtr) return;
6949
6950 // If the destination has alignment 1, we're done.
6951 QualType DestPointee = DestPtr->getPointeeType();
6952 if (DestPointee->isIncompleteType()) return;
6953 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6954 if (DestAlign.isOne()) return;
6955
6956 // Require that the source be a pointer type.
6957 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6958 if (!SrcPtr) return;
6959 QualType SrcPointee = SrcPtr->getPointeeType();
6960
6961 // Whitelist casts from cv void*. We already implicitly
6962 // whitelisted casts to cv void*, since they have alignment 1.
6963 // Also whitelist casts involving incomplete types, which implicitly
6964 // includes 'void'.
6965 if (SrcPointee->isIncompleteType()) return;
6966
6967 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6968 if (SrcAlign >= DestAlign) return;
6969
6970 Diag(TRange.getBegin(), diag::warn_cast_align)
6971 << Op->getType() << T
6972 << static_cast<unsigned>(SrcAlign.getQuantity())
6973 << static_cast<unsigned>(DestAlign.getQuantity())
6974 << TRange << Op->getSourceRange();
6975}
6976
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006977static const Type* getElementType(const Expr *BaseExpr) {
6978 const Type* EltType = BaseExpr->getType().getTypePtr();
6979 if (EltType->isAnyPointerType())
6980 return EltType->getPointeeType().getTypePtr();
6981 else if (EltType->isArrayType())
6982 return EltType->getBaseElementTypeUnsafe();
6983 return EltType;
6984}
6985
Chandler Carruth28389f02011-08-05 09:10:50 +00006986/// \brief Check whether this array fits the idiom of a size-one tail padded
6987/// array member of a struct.
6988///
6989/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6990/// commonly used to emulate flexible arrays in C89 code.
6991static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6992 const NamedDecl *ND) {
6993 if (Size != 1 || !ND) return false;
6994
6995 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6996 if (!FD) return false;
6997
6998 // Don't consider sizes resulting from macro expansions or template argument
6999 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007000
7001 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007002 while (TInfo) {
7003 TypeLoc TL = TInfo->getTypeLoc();
7004 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007005 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7006 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007007 TInfo = TDL->getTypeSourceInfo();
7008 continue;
7009 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007010 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7011 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007012 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7013 return false;
7014 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007015 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007016 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007017
7018 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007019 if (!RD) return false;
7020 if (RD->isUnion()) return false;
7021 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7022 if (!CRD->isStandardLayout()) return false;
7023 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007024
Benjamin Kramer8c543672011-08-06 03:04:42 +00007025 // See if this is the last field decl in the record.
7026 const Decl *D = FD;
7027 while ((D = D->getNextDeclInContext()))
7028 if (isa<FieldDecl>(D))
7029 return false;
7030 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007031}
7032
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007033void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007034 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007035 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007036 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007037 if (IndexExpr->isValueDependent())
7038 return;
7039
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007040 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007041 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007042 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007043 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007044 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007045 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007046
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007047 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007048 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007049 return;
Richard Smith13f67182011-12-16 19:31:14 +00007050 if (IndexNegated)
7051 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007052
Craig Topperc3ec1492014-05-26 06:22:03 +00007053 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007054 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7055 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007056 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007057 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007058
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007059 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007060 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007061 if (!size.isStrictlyPositive())
7062 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007063
7064 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007065 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007066 // Make sure we're comparing apples to apples when comparing index to size
7067 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7068 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007069 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007070 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007071 if (ptrarith_typesize != array_typesize) {
7072 // There's a cast to a different size type involved
7073 uint64_t ratio = array_typesize / ptrarith_typesize;
7074 // TODO: Be smarter about handling cases where array_typesize is not a
7075 // multiple of ptrarith_typesize
7076 if (ptrarith_typesize * ratio == array_typesize)
7077 size *= llvm::APInt(size.getBitWidth(), ratio);
7078 }
7079 }
7080
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007081 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007082 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007083 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007084 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007085
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007086 // For array subscripting the index must be less than size, but for pointer
7087 // arithmetic also allow the index (offset) to be equal to size since
7088 // computing the next address after the end of the array is legal and
7089 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007090 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007091 return;
7092
7093 // Also don't warn for arrays of size 1 which are members of some
7094 // structure. These are often used to approximate flexible arrays in C89
7095 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007096 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007097 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007098
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007099 // Suppress the warning if the subscript expression (as identified by the
7100 // ']' location) and the index expression are both from macro expansions
7101 // within a system header.
7102 if (ASE) {
7103 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7104 ASE->getRBracketLoc());
7105 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7106 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7107 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007108 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007109 return;
7110 }
7111 }
7112
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007113 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007114 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007115 DiagID = diag::warn_array_index_exceeds_bounds;
7116
7117 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7118 PDiag(DiagID) << index.toString(10, true)
7119 << size.toString(10, true)
7120 << (unsigned)size.getLimitedValue(~0U)
7121 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007122 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007123 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007124 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007125 DiagID = diag::warn_ptr_arith_precedes_bounds;
7126 if (index.isNegative()) index = -index;
7127 }
7128
7129 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7130 PDiag(DiagID) << index.toString(10, true)
7131 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007132 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007133
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007134 if (!ND) {
7135 // Try harder to find a NamedDecl to point at in the note.
7136 while (const ArraySubscriptExpr *ASE =
7137 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7138 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7139 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7140 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7141 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7142 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7143 }
7144
Chandler Carruth1af88f12011-02-17 21:10:52 +00007145 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007146 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7147 PDiag(diag::note_array_index_out_of_bounds)
7148 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007149}
7150
Ted Kremenekdf26df72011-03-01 18:41:00 +00007151void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007152 int AllowOnePastEnd = 0;
7153 while (expr) {
7154 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007155 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007156 case Stmt::ArraySubscriptExprClass: {
7157 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007158 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007159 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007160 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007161 }
7162 case Stmt::UnaryOperatorClass: {
7163 // Only unwrap the * and & unary operators
7164 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7165 expr = UO->getSubExpr();
7166 switch (UO->getOpcode()) {
7167 case UO_AddrOf:
7168 AllowOnePastEnd++;
7169 break;
7170 case UO_Deref:
7171 AllowOnePastEnd--;
7172 break;
7173 default:
7174 return;
7175 }
7176 break;
7177 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007178 case Stmt::ConditionalOperatorClass: {
7179 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7180 if (const Expr *lhs = cond->getLHS())
7181 CheckArrayAccess(lhs);
7182 if (const Expr *rhs = cond->getRHS())
7183 CheckArrayAccess(rhs);
7184 return;
7185 }
7186 default:
7187 return;
7188 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007189 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007190}
John McCall31168b02011-06-15 23:02:42 +00007191
7192//===--- CHECK: Objective-C retain cycles ----------------------------------//
7193
7194namespace {
7195 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007196 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007197 VarDecl *Variable;
7198 SourceRange Range;
7199 SourceLocation Loc;
7200 bool Indirect;
7201
7202 void setLocsFrom(Expr *e) {
7203 Loc = e->getExprLoc();
7204 Range = e->getSourceRange();
7205 }
7206 };
7207}
7208
7209/// Consider whether capturing the given variable can possibly lead to
7210/// a retain cycle.
7211static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007212 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007213 // lifetime. In MRR, it's captured strongly if the variable is
7214 // __block and has an appropriate type.
7215 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7216 return false;
7217
7218 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007219 if (ref)
7220 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007221 return true;
7222}
7223
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007224static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007225 while (true) {
7226 e = e->IgnoreParens();
7227 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7228 switch (cast->getCastKind()) {
7229 case CK_BitCast:
7230 case CK_LValueBitCast:
7231 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007232 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007233 e = cast->getSubExpr();
7234 continue;
7235
John McCall31168b02011-06-15 23:02:42 +00007236 default:
7237 return false;
7238 }
7239 }
7240
7241 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7242 ObjCIvarDecl *ivar = ref->getDecl();
7243 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7244 return false;
7245
7246 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007247 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007248 return false;
7249
7250 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7251 owner.Indirect = true;
7252 return true;
7253 }
7254
7255 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7256 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7257 if (!var) return false;
7258 return considerVariable(var, ref, owner);
7259 }
7260
John McCall31168b02011-06-15 23:02:42 +00007261 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7262 if (member->isArrow()) return false;
7263
7264 // Don't count this as an indirect ownership.
7265 e = member->getBase();
7266 continue;
7267 }
7268
John McCallfe96e0b2011-11-06 09:01:30 +00007269 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7270 // Only pay attention to pseudo-objects on property references.
7271 ObjCPropertyRefExpr *pre
7272 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7273 ->IgnoreParens());
7274 if (!pre) return false;
7275 if (pre->isImplicitProperty()) return false;
7276 ObjCPropertyDecl *property = pre->getExplicitProperty();
7277 if (!property->isRetaining() &&
7278 !(property->getPropertyIvarDecl() &&
7279 property->getPropertyIvarDecl()->getType()
7280 .getObjCLifetime() == Qualifiers::OCL_Strong))
7281 return false;
7282
7283 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007284 if (pre->isSuperReceiver()) {
7285 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7286 if (!owner.Variable)
7287 return false;
7288 owner.Loc = pre->getLocation();
7289 owner.Range = pre->getSourceRange();
7290 return true;
7291 }
John McCallfe96e0b2011-11-06 09:01:30 +00007292 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7293 ->getSourceExpr());
7294 continue;
7295 }
7296
John McCall31168b02011-06-15 23:02:42 +00007297 // Array ivars?
7298
7299 return false;
7300 }
7301}
7302
7303namespace {
7304 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7305 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7306 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007307 Context(Context), Variable(variable), Capturer(nullptr),
7308 VarWillBeReased(false) {}
7309 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00007310 VarDecl *Variable;
7311 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007312 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00007313
7314 void VisitDeclRefExpr(DeclRefExpr *ref) {
7315 if (ref->getDecl() == Variable && !Capturer)
7316 Capturer = ref;
7317 }
7318
John McCall31168b02011-06-15 23:02:42 +00007319 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7320 if (Capturer) return;
7321 Visit(ref->getBase());
7322 if (Capturer && ref->isFreeIvar())
7323 Capturer = ref;
7324 }
7325
7326 void VisitBlockExpr(BlockExpr *block) {
7327 // Look inside nested blocks
7328 if (block->getBlockDecl()->capturesVariable(Variable))
7329 Visit(block->getBlockDecl()->getBody());
7330 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007331
7332 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7333 if (Capturer) return;
7334 if (OVE->getSourceExpr())
7335 Visit(OVE->getSourceExpr());
7336 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007337 void VisitBinaryOperator(BinaryOperator *BinOp) {
7338 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
7339 return;
7340 Expr *LHS = BinOp->getLHS();
7341 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
7342 if (DRE->getDecl() != Variable)
7343 return;
7344 if (Expr *RHS = BinOp->getRHS()) {
7345 RHS = RHS->IgnoreParenCasts();
7346 llvm::APSInt Value;
7347 VarWillBeReased =
7348 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
7349 }
7350 }
7351 }
John McCall31168b02011-06-15 23:02:42 +00007352 };
7353}
7354
7355/// Check whether the given argument is a block which captures a
7356/// variable.
7357static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7358 assert(owner.Variable && owner.Loc.isValid());
7359
7360 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007361
7362 // Look through [^{...} copy] and Block_copy(^{...}).
7363 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7364 Selector Cmd = ME->getSelector();
7365 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7366 e = ME->getInstanceReceiver();
7367 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007368 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007369 e = e->IgnoreParenCasts();
7370 }
7371 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7372 if (CE->getNumArgs() == 1) {
7373 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007374 if (Fn) {
7375 const IdentifierInfo *FnI = Fn->getIdentifier();
7376 if (FnI && FnI->isStr("_Block_copy")) {
7377 e = CE->getArg(0)->IgnoreParenCasts();
7378 }
7379 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007380 }
7381 }
7382
John McCall31168b02011-06-15 23:02:42 +00007383 BlockExpr *block = dyn_cast<BlockExpr>(e);
7384 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007385 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007386
7387 FindCaptureVisitor visitor(S.Context, owner.Variable);
7388 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00007389 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00007390}
7391
7392static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7393 RetainCycleOwner &owner) {
7394 assert(capturer);
7395 assert(owner.Variable && owner.Loc.isValid());
7396
7397 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7398 << owner.Variable << capturer->getSourceRange();
7399 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7400 << owner.Indirect << owner.Range;
7401}
7402
7403/// Check for a keyword selector that starts with the word 'add' or
7404/// 'set'.
7405static bool isSetterLikeSelector(Selector sel) {
7406 if (sel.isUnarySelector()) return false;
7407
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007408 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007409 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007410 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007411 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007412 else if (str.startswith("add")) {
7413 // Specially whitelist 'addOperationWithBlock:'.
7414 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7415 return false;
7416 str = str.substr(3);
7417 }
John McCall31168b02011-06-15 23:02:42 +00007418 else
7419 return false;
7420
7421 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007422 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007423}
7424
7425/// Check a message send to see if it's likely to cause a retain cycle.
7426void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7427 // Only check instance methods whose selector looks like a setter.
7428 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7429 return;
7430
7431 // Try to find a variable that the receiver is strongly owned by.
7432 RetainCycleOwner owner;
7433 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007434 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007435 return;
7436 } else {
7437 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7438 owner.Variable = getCurMethodDecl()->getSelfDecl();
7439 owner.Loc = msg->getSuperLoc();
7440 owner.Range = msg->getSuperLoc();
7441 }
7442
7443 // Check whether the receiver is captured by any of the arguments.
7444 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7445 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7446 return diagnoseRetainCycle(*this, capturer, owner);
7447}
7448
7449/// Check a property assign to see if it's likely to cause a retain cycle.
7450void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7451 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007452 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007453 return;
7454
7455 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7456 diagnoseRetainCycle(*this, capturer, owner);
7457}
7458
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007459void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7460 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007461 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007462 return;
7463
7464 // Because we don't have an expression for the variable, we have to set the
7465 // location explicitly here.
7466 Owner.Loc = Var->getLocation();
7467 Owner.Range = Var->getSourceRange();
7468
7469 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7470 diagnoseRetainCycle(*this, Capturer, Owner);
7471}
7472
Ted Kremenek9304da92012-12-21 08:04:28 +00007473static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7474 Expr *RHS, bool isProperty) {
7475 // Check if RHS is an Objective-C object literal, which also can get
7476 // immediately zapped in a weak reference. Note that we explicitly
7477 // allow ObjCStringLiterals, since those are designed to never really die.
7478 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007479
Ted Kremenek64873352012-12-21 22:46:35 +00007480 // This enum needs to match with the 'select' in
7481 // warn_objc_arc_literal_assign (off-by-1).
7482 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7483 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7484 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007485
7486 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007487 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007488 << (isProperty ? 0 : 1)
7489 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007490
7491 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007492}
7493
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007494static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7495 Qualifiers::ObjCLifetime LT,
7496 Expr *RHS, bool isProperty) {
7497 // Strip off any implicit cast added to get to the one ARC-specific.
7498 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7499 if (cast->getCastKind() == CK_ARCConsumeObject) {
7500 S.Diag(Loc, diag::warn_arc_retained_assign)
7501 << (LT == Qualifiers::OCL_ExplicitNone)
7502 << (isProperty ? 0 : 1)
7503 << RHS->getSourceRange();
7504 return true;
7505 }
7506 RHS = cast->getSubExpr();
7507 }
7508
7509 if (LT == Qualifiers::OCL_Weak &&
7510 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7511 return true;
7512
7513 return false;
7514}
7515
Ted Kremenekb36234d2012-12-21 08:04:20 +00007516bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7517 QualType LHS, Expr *RHS) {
7518 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7519
7520 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7521 return false;
7522
7523 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7524 return true;
7525
7526 return false;
7527}
7528
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007529void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7530 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007531 QualType LHSType;
7532 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007533 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007534 ObjCPropertyRefExpr *PRE
7535 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7536 if (PRE && !PRE->isImplicitProperty()) {
7537 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7538 if (PD)
7539 LHSType = PD->getType();
7540 }
7541
7542 if (LHSType.isNull())
7543 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007544
7545 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7546
7547 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007548 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00007549 getCurFunction()->markSafeWeakUse(LHS);
7550 }
7551
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007552 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7553 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007554
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007555 // FIXME. Check for other life times.
7556 if (LT != Qualifiers::OCL_None)
7557 return;
7558
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007559 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007560 if (PRE->isImplicitProperty())
7561 return;
7562 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7563 if (!PD)
7564 return;
7565
Bill Wendling44426052012-12-20 19:22:21 +00007566 unsigned Attributes = PD->getPropertyAttributes();
7567 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007568 // when 'assign' attribute was not explicitly specified
7569 // by user, ignore it and rely on property type itself
7570 // for lifetime info.
7571 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7572 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7573 LHSType->isObjCRetainableType())
7574 return;
7575
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007576 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007577 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007578 Diag(Loc, diag::warn_arc_retained_property_assign)
7579 << RHS->getSourceRange();
7580 return;
7581 }
7582 RHS = cast->getSubExpr();
7583 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007584 }
Bill Wendling44426052012-12-20 19:22:21 +00007585 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007586 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7587 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007588 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007589 }
7590}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007591
7592//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7593
7594namespace {
7595bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7596 SourceLocation StmtLoc,
7597 const NullStmt *Body) {
7598 // Do not warn if the body is a macro that expands to nothing, e.g:
7599 //
7600 // #define CALL(x)
7601 // if (condition)
7602 // CALL(0);
7603 //
7604 if (Body->hasLeadingEmptyMacro())
7605 return false;
7606
7607 // Get line numbers of statement and body.
7608 bool StmtLineInvalid;
7609 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7610 &StmtLineInvalid);
7611 if (StmtLineInvalid)
7612 return false;
7613
7614 bool BodyLineInvalid;
7615 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7616 &BodyLineInvalid);
7617 if (BodyLineInvalid)
7618 return false;
7619
7620 // Warn if null statement and body are on the same line.
7621 if (StmtLine != BodyLine)
7622 return false;
7623
7624 return true;
7625}
7626} // Unnamed namespace
7627
7628void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7629 const Stmt *Body,
7630 unsigned DiagID) {
7631 // Since this is a syntactic check, don't emit diagnostic for template
7632 // instantiations, this just adds noise.
7633 if (CurrentInstantiationScope)
7634 return;
7635
7636 // The body should be a null statement.
7637 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7638 if (!NBody)
7639 return;
7640
7641 // Do the usual checks.
7642 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7643 return;
7644
7645 Diag(NBody->getSemiLoc(), DiagID);
7646 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7647}
7648
7649void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7650 const Stmt *PossibleBody) {
7651 assert(!CurrentInstantiationScope); // Ensured by caller
7652
7653 SourceLocation StmtLoc;
7654 const Stmt *Body;
7655 unsigned DiagID;
7656 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7657 StmtLoc = FS->getRParenLoc();
7658 Body = FS->getBody();
7659 DiagID = diag::warn_empty_for_body;
7660 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7661 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7662 Body = WS->getBody();
7663 DiagID = diag::warn_empty_while_body;
7664 } else
7665 return; // Neither `for' nor `while'.
7666
7667 // The body should be a null statement.
7668 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7669 if (!NBody)
7670 return;
7671
7672 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007673 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007674 return;
7675
7676 // Do the usual checks.
7677 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7678 return;
7679
7680 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7681 // noise level low, emit diagnostics only if for/while is followed by a
7682 // CompoundStmt, e.g.:
7683 // for (int i = 0; i < n; i++);
7684 // {
7685 // a(i);
7686 // }
7687 // or if for/while is followed by a statement with more indentation
7688 // than for/while itself:
7689 // for (int i = 0; i < n; i++);
7690 // a(i);
7691 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7692 if (!ProbableTypo) {
7693 bool BodyColInvalid;
7694 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7695 PossibleBody->getLocStart(),
7696 &BodyColInvalid);
7697 if (BodyColInvalid)
7698 return;
7699
7700 bool StmtColInvalid;
7701 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7702 S->getLocStart(),
7703 &StmtColInvalid);
7704 if (StmtColInvalid)
7705 return;
7706
7707 if (BodyCol > StmtCol)
7708 ProbableTypo = true;
7709 }
7710
7711 if (ProbableTypo) {
7712 Diag(NBody->getSemiLoc(), DiagID);
7713 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7714 }
7715}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007716
7717//===--- Layout compatibility ----------------------------------------------//
7718
7719namespace {
7720
7721bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7722
7723/// \brief Check if two enumeration types are layout-compatible.
7724bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7725 // C++11 [dcl.enum] p8:
7726 // Two enumeration types are layout-compatible if they have the same
7727 // underlying type.
7728 return ED1->isComplete() && ED2->isComplete() &&
7729 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7730}
7731
7732/// \brief Check if two fields are layout-compatible.
7733bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7734 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7735 return false;
7736
7737 if (Field1->isBitField() != Field2->isBitField())
7738 return false;
7739
7740 if (Field1->isBitField()) {
7741 // Make sure that the bit-fields are the same length.
7742 unsigned Bits1 = Field1->getBitWidthValue(C);
7743 unsigned Bits2 = Field2->getBitWidthValue(C);
7744
7745 if (Bits1 != Bits2)
7746 return false;
7747 }
7748
7749 return true;
7750}
7751
7752/// \brief Check if two standard-layout structs are layout-compatible.
7753/// (C++11 [class.mem] p17)
7754bool isLayoutCompatibleStruct(ASTContext &C,
7755 RecordDecl *RD1,
7756 RecordDecl *RD2) {
7757 // If both records are C++ classes, check that base classes match.
7758 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7759 // If one of records is a CXXRecordDecl we are in C++ mode,
7760 // thus the other one is a CXXRecordDecl, too.
7761 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7762 // Check number of base classes.
7763 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7764 return false;
7765
7766 // Check the base classes.
7767 for (CXXRecordDecl::base_class_const_iterator
7768 Base1 = D1CXX->bases_begin(),
7769 BaseEnd1 = D1CXX->bases_end(),
7770 Base2 = D2CXX->bases_begin();
7771 Base1 != BaseEnd1;
7772 ++Base1, ++Base2) {
7773 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7774 return false;
7775 }
7776 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7777 // If only RD2 is a C++ class, it should have zero base classes.
7778 if (D2CXX->getNumBases() > 0)
7779 return false;
7780 }
7781
7782 // Check the fields.
7783 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7784 Field2End = RD2->field_end(),
7785 Field1 = RD1->field_begin(),
7786 Field1End = RD1->field_end();
7787 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7788 if (!isLayoutCompatible(C, *Field1, *Field2))
7789 return false;
7790 }
7791 if (Field1 != Field1End || Field2 != Field2End)
7792 return false;
7793
7794 return true;
7795}
7796
7797/// \brief Check if two standard-layout unions are layout-compatible.
7798/// (C++11 [class.mem] p18)
7799bool isLayoutCompatibleUnion(ASTContext &C,
7800 RecordDecl *RD1,
7801 RecordDecl *RD2) {
7802 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007803 for (auto *Field2 : RD2->fields())
7804 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007805
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007806 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007807 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7808 I = UnmatchedFields.begin(),
7809 E = UnmatchedFields.end();
7810
7811 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007812 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007813 bool Result = UnmatchedFields.erase(*I);
7814 (void) Result;
7815 assert(Result);
7816 break;
7817 }
7818 }
7819 if (I == E)
7820 return false;
7821 }
7822
7823 return UnmatchedFields.empty();
7824}
7825
7826bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7827 if (RD1->isUnion() != RD2->isUnion())
7828 return false;
7829
7830 if (RD1->isUnion())
7831 return isLayoutCompatibleUnion(C, RD1, RD2);
7832 else
7833 return isLayoutCompatibleStruct(C, RD1, RD2);
7834}
7835
7836/// \brief Check if two types are layout-compatible in C++11 sense.
7837bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7838 if (T1.isNull() || T2.isNull())
7839 return false;
7840
7841 // C++11 [basic.types] p11:
7842 // If two types T1 and T2 are the same type, then T1 and T2 are
7843 // layout-compatible types.
7844 if (C.hasSameType(T1, T2))
7845 return true;
7846
7847 T1 = T1.getCanonicalType().getUnqualifiedType();
7848 T2 = T2.getCanonicalType().getUnqualifiedType();
7849
7850 const Type::TypeClass TC1 = T1->getTypeClass();
7851 const Type::TypeClass TC2 = T2->getTypeClass();
7852
7853 if (TC1 != TC2)
7854 return false;
7855
7856 if (TC1 == Type::Enum) {
7857 return isLayoutCompatible(C,
7858 cast<EnumType>(T1)->getDecl(),
7859 cast<EnumType>(T2)->getDecl());
7860 } else if (TC1 == Type::Record) {
7861 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7862 return false;
7863
7864 return isLayoutCompatible(C,
7865 cast<RecordType>(T1)->getDecl(),
7866 cast<RecordType>(T2)->getDecl());
7867 }
7868
7869 return false;
7870}
7871}
7872
7873//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7874
7875namespace {
7876/// \brief Given a type tag expression find the type tag itself.
7877///
7878/// \param TypeExpr Type tag expression, as it appears in user's code.
7879///
7880/// \param VD Declaration of an identifier that appears in a type tag.
7881///
7882/// \param MagicValue Type tag magic value.
7883bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7884 const ValueDecl **VD, uint64_t *MagicValue) {
7885 while(true) {
7886 if (!TypeExpr)
7887 return false;
7888
7889 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7890
7891 switch (TypeExpr->getStmtClass()) {
7892 case Stmt::UnaryOperatorClass: {
7893 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7894 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7895 TypeExpr = UO->getSubExpr();
7896 continue;
7897 }
7898 return false;
7899 }
7900
7901 case Stmt::DeclRefExprClass: {
7902 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7903 *VD = DRE->getDecl();
7904 return true;
7905 }
7906
7907 case Stmt::IntegerLiteralClass: {
7908 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7909 llvm::APInt MagicValueAPInt = IL->getValue();
7910 if (MagicValueAPInt.getActiveBits() <= 64) {
7911 *MagicValue = MagicValueAPInt.getZExtValue();
7912 return true;
7913 } else
7914 return false;
7915 }
7916
7917 case Stmt::BinaryConditionalOperatorClass:
7918 case Stmt::ConditionalOperatorClass: {
7919 const AbstractConditionalOperator *ACO =
7920 cast<AbstractConditionalOperator>(TypeExpr);
7921 bool Result;
7922 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7923 if (Result)
7924 TypeExpr = ACO->getTrueExpr();
7925 else
7926 TypeExpr = ACO->getFalseExpr();
7927 continue;
7928 }
7929 return false;
7930 }
7931
7932 case Stmt::BinaryOperatorClass: {
7933 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7934 if (BO->getOpcode() == BO_Comma) {
7935 TypeExpr = BO->getRHS();
7936 continue;
7937 }
7938 return false;
7939 }
7940
7941 default:
7942 return false;
7943 }
7944 }
7945}
7946
7947/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7948///
7949/// \param TypeExpr Expression that specifies a type tag.
7950///
7951/// \param MagicValues Registered magic values.
7952///
7953/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7954/// kind.
7955///
7956/// \param TypeInfo Information about the corresponding C type.
7957///
7958/// \returns true if the corresponding C type was found.
7959bool GetMatchingCType(
7960 const IdentifierInfo *ArgumentKind,
7961 const Expr *TypeExpr, const ASTContext &Ctx,
7962 const llvm::DenseMap<Sema::TypeTagMagicValue,
7963 Sema::TypeTagData> *MagicValues,
7964 bool &FoundWrongKind,
7965 Sema::TypeTagData &TypeInfo) {
7966 FoundWrongKind = false;
7967
7968 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00007969 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007970
7971 uint64_t MagicValue;
7972
7973 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7974 return false;
7975
7976 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007977 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007978 if (I->getArgumentKind() != ArgumentKind) {
7979 FoundWrongKind = true;
7980 return false;
7981 }
7982 TypeInfo.Type = I->getMatchingCType();
7983 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7984 TypeInfo.MustBeNull = I->getMustBeNull();
7985 return true;
7986 }
7987 return false;
7988 }
7989
7990 if (!MagicValues)
7991 return false;
7992
7993 llvm::DenseMap<Sema::TypeTagMagicValue,
7994 Sema::TypeTagData>::const_iterator I =
7995 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7996 if (I == MagicValues->end())
7997 return false;
7998
7999 TypeInfo = I->second;
8000 return true;
8001}
8002} // unnamed namespace
8003
8004void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8005 uint64_t MagicValue, QualType Type,
8006 bool LayoutCompatible,
8007 bool MustBeNull) {
8008 if (!TypeTagForDatatypeMagicValues)
8009 TypeTagForDatatypeMagicValues.reset(
8010 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8011
8012 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8013 (*TypeTagForDatatypeMagicValues)[Magic] =
8014 TypeTagData(Type, LayoutCompatible, MustBeNull);
8015}
8016
8017namespace {
8018bool IsSameCharType(QualType T1, QualType T2) {
8019 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8020 if (!BT1)
8021 return false;
8022
8023 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8024 if (!BT2)
8025 return false;
8026
8027 BuiltinType::Kind T1Kind = BT1->getKind();
8028 BuiltinType::Kind T2Kind = BT2->getKind();
8029
8030 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
8031 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
8032 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8033 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8034}
8035} // unnamed namespace
8036
8037void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8038 const Expr * const *ExprArgs) {
8039 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8040 bool IsPointerAttr = Attr->getIsPointer();
8041
8042 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8043 bool FoundWrongKind;
8044 TypeTagData TypeInfo;
8045 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8046 TypeTagForDatatypeMagicValues.get(),
8047 FoundWrongKind, TypeInfo)) {
8048 if (FoundWrongKind)
8049 Diag(TypeTagExpr->getExprLoc(),
8050 diag::warn_type_tag_for_datatype_wrong_kind)
8051 << TypeTagExpr->getSourceRange();
8052 return;
8053 }
8054
8055 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8056 if (IsPointerAttr) {
8057 // Skip implicit cast of pointer to `void *' (as a function argument).
8058 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00008059 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008060 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008061 ArgumentExpr = ICE->getSubExpr();
8062 }
8063 QualType ArgumentType = ArgumentExpr->getType();
8064
8065 // Passing a `void*' pointer shouldn't trigger a warning.
8066 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8067 return;
8068
8069 if (TypeInfo.MustBeNull) {
8070 // Type tag with matching void type requires a null pointer.
8071 if (!ArgumentExpr->isNullPointerConstant(Context,
8072 Expr::NPC_ValueDependentIsNotNull)) {
8073 Diag(ArgumentExpr->getExprLoc(),
8074 diag::warn_type_safety_null_pointer_required)
8075 << ArgumentKind->getName()
8076 << ArgumentExpr->getSourceRange()
8077 << TypeTagExpr->getSourceRange();
8078 }
8079 return;
8080 }
8081
8082 QualType RequiredType = TypeInfo.Type;
8083 if (IsPointerAttr)
8084 RequiredType = Context.getPointerType(RequiredType);
8085
8086 bool mismatch = false;
8087 if (!TypeInfo.LayoutCompatible) {
8088 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8089
8090 // C++11 [basic.fundamental] p1:
8091 // Plain char, signed char, and unsigned char are three distinct types.
8092 //
8093 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8094 // char' depending on the current char signedness mode.
8095 if (mismatch)
8096 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8097 RequiredType->getPointeeType())) ||
8098 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8099 mismatch = false;
8100 } else
8101 if (IsPointerAttr)
8102 mismatch = !isLayoutCompatible(Context,
8103 ArgumentType->getPointeeType(),
8104 RequiredType->getPointeeType());
8105 else
8106 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8107
8108 if (mismatch)
8109 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008110 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008111 << TypeInfo.LayoutCompatible << RequiredType
8112 << ArgumentExpr->getSourceRange()
8113 << TypeTagExpr->getSourceRange();
8114}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008115