blob: 60514efd55c96de9d743a03f55fb3ff60f0315e8 [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;
Nate Begeman4904e322010-06-08 02:47:44 +0000299 }
300
301 // Since the target specific builtins for each arch overlap, only check those
302 // of the arch we are compiling for.
303 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000304 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000305 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000306 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000307 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000308 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000309 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
310 return ExprError();
311 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000312 case llvm::Triple::aarch64:
313 case llvm::Triple::aarch64_be:
Tim Northovera2ee4332014-03-29 15:09:45 +0000314 case llvm::Triple::arm64:
James Molloyfa403682014-04-30 10:11:40 +0000315 case llvm::Triple::arm64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000316 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000317 return ExprError();
318 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000319 case llvm::Triple::mips:
320 case llvm::Triple::mipsel:
321 case llvm::Triple::mips64:
322 case llvm::Triple::mips64el:
323 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000326 case llvm::Triple::x86:
327 case llvm::Triple::x86_64:
328 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
329 return ExprError();
330 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000331 default:
332 break;
333 }
334 }
335
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000336 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000337}
338
Nate Begeman91e1fea2010-06-14 05:21:25 +0000339// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000340static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000341 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000342 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 switch (Type.getEltType()) {
344 case NeonTypeFlags::Int8:
345 case NeonTypeFlags::Poly8:
346 return shift ? 7 : (8 << IsQuad) - 1;
347 case NeonTypeFlags::Int16:
348 case NeonTypeFlags::Poly16:
349 return shift ? 15 : (4 << IsQuad) - 1;
350 case NeonTypeFlags::Int32:
351 return shift ? 31 : (2 << IsQuad) - 1;
352 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000353 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000354 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000355 case NeonTypeFlags::Poly128:
356 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000357 case NeonTypeFlags::Float16:
358 assert(!shift && "cannot shift float types!");
359 return (4 << IsQuad) - 1;
360 case NeonTypeFlags::Float32:
361 assert(!shift && "cannot shift float types!");
362 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000363 case NeonTypeFlags::Float64:
364 assert(!shift && "cannot shift float types!");
365 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000366 }
David Blaikie8a40f702012-01-17 06:56:22 +0000367 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000368}
369
Bob Wilsone4d77232011-11-08 05:04:11 +0000370/// getNeonEltType - Return the QualType corresponding to the elements of
371/// the vector type specified by the NeonTypeFlags. This is used to check
372/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000373static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000374 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000375 switch (Flags.getEltType()) {
376 case NeonTypeFlags::Int8:
377 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
378 case NeonTypeFlags::Int16:
379 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
380 case NeonTypeFlags::Int32:
381 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
382 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000383 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000384 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
385 else
386 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
387 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000388 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000389 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000390 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000391 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000392 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000393 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000394 case NeonTypeFlags::Poly128:
395 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000396 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000397 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000398 case NeonTypeFlags::Float32:
399 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000400 case NeonTypeFlags::Float64:
401 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000402 }
David Blaikie8a40f702012-01-17 06:56:22 +0000403 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000404}
405
Tim Northover12670412014-02-19 10:37:05 +0000406bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000407 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000408 uint64_t mask = 0;
409 unsigned TV = 0;
410 int PtrArgNum = -1;
411 bool HasConstPtr = false;
412 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000413#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000414#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000415#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000416 }
417
418 // For NEON intrinsics which are overloaded on vector element type, validate
419 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000420 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000421 if (mask) {
422 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
423 return true;
424
425 TV = Result.getLimitedValue(64);
426 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
427 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000428 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000429 }
430
431 if (PtrArgNum >= 0) {
432 // Check that pointer arguments have the specified type.
433 Expr *Arg = TheCall->getArg(PtrArgNum);
434 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
435 Arg = ICE->getSubExpr();
436 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
437 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000438
Tim Northovera2ee4332014-03-29 15:09:45 +0000439 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
440 bool IsPolyUnsigned =
441 Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::arm64;
442 bool IsInt64Long =
443 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
444 QualType EltTy =
445 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000446 if (HasConstPtr)
447 EltTy = EltTy.withConst();
448 QualType LHSTy = Context.getPointerType(EltTy);
449 AssignConvertType ConvTy;
450 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
451 if (RHS.isInvalid())
452 return true;
453 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
454 RHS.get(), AA_Assigning))
455 return true;
456 }
457
458 // For NEON intrinsics which take an immediate value as part of the
459 // instruction, range check them here.
460 unsigned i = 0, l = 0, u = 0;
461 switch (BuiltinID) {
462 default:
463 return false;
Tim Northover12670412014-02-19 10:37:05 +0000464#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000465#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000466#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000467 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000468
Richard Sandiford28940af2014-04-16 08:47:51 +0000469 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000470}
471
Tim Northovera2ee4332014-03-29 15:09:45 +0000472bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
473 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000474 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000475 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000476 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
477 BuiltinID == AArch64::BI__builtin_arm_strex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000478 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000479 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000480 BuiltinID == AArch64::BI__builtin_arm_ldrex;
Tim Northover6aacd492013-07-16 09:47:53 +0000481
482 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
483
484 // Ensure that we have the proper number of arguments.
485 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
486 return true;
487
488 // Inspect the pointer argument of the atomic builtin. This should always be
489 // a pointer type, whose element is an integral scalar or pointer type.
490 // Because it is a pointer type, we don't have to worry about any implicit
491 // casts here.
492 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
493 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
494 if (PointerArgRes.isInvalid())
495 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000496 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000497
498 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
499 if (!pointerType) {
500 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
501 << PointerArg->getType() << PointerArg->getSourceRange();
502 return true;
503 }
504
505 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
506 // task is to insert the appropriate casts into the AST. First work out just
507 // what the appropriate type is.
508 QualType ValType = pointerType->getPointeeType();
509 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
510 if (IsLdrex)
511 AddrType.addConst();
512
513 // Issue a warning if the cast is dodgy.
514 CastKind CastNeeded = CK_NoOp;
515 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
516 CastNeeded = CK_BitCast;
517 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
518 << PointerArg->getType()
519 << Context.getPointerType(AddrType)
520 << AA_Passing << PointerArg->getSourceRange();
521 }
522
523 // Finally, do the cast and replace the argument with the corrected version.
524 AddrType = Context.getPointerType(AddrType);
525 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
526 if (PointerArgRes.isInvalid())
527 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000528 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000529
530 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
531
532 // In general, we allow ints, floats and pointers to be loaded and stored.
533 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
534 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
535 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000541 if (Context.getTypeSize(ValType) > MaxWidth) {
542 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000543 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
544 << PointerArg->getType() << PointerArg->getSourceRange();
545 return true;
546 }
547
548 switch (ValType.getObjCLifetime()) {
549 case Qualifiers::OCL_None:
550 case Qualifiers::OCL_ExplicitNone:
551 // okay
552 break;
553
554 case Qualifiers::OCL_Weak:
555 case Qualifiers::OCL_Strong:
556 case Qualifiers::OCL_Autoreleasing:
557 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
558 << ValType << PointerArg->getSourceRange();
559 return true;
560 }
561
562
563 if (IsLdrex) {
564 TheCall->setType(ValType);
565 return false;
566 }
567
568 // Initialize the argument to be stored.
569 ExprResult ValArg = TheCall->getArg(0);
570 InitializedEntity Entity = InitializedEntity::InitializeParameter(
571 Context, ValType, /*consume*/ false);
572 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
573 if (ValArg.isInvalid())
574 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000575 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000576
577 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
578 // but the custom checker bypasses all default analysis.
579 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000580 return false;
581}
582
Nate Begeman4904e322010-06-08 02:47:44 +0000583bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000584 llvm::APSInt Result;
585
Tim Northover6aacd492013-07-16 09:47:53 +0000586 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
587 BuiltinID == ARM::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000588 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000589 }
590
Tim Northover12670412014-02-19 10:37:05 +0000591 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
592 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000593
Bob Wilsond836d3d2014-03-09 23:02:27 +0000594 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000595 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000596 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000597 switch (BuiltinID) {
598 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000599 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
600 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000601 case ARM::BI__builtin_arm_vcvtr_f:
602 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000603 case ARM::BI__builtin_arm_dmb:
604 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000605 }
Nate Begemand773fe62010-06-13 04:47:52 +0000606
Nate Begemanf568b072010-08-03 21:32:34 +0000607 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000608 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000609}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000610
Tim Northover573cbee2014-05-24 12:52:07 +0000611bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000612 CallExpr *TheCall) {
613 llvm::APSInt Result;
614
Tim Northover573cbee2014-05-24 12:52:07 +0000615 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
616 BuiltinID == AArch64::BI__builtin_arm_strex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000617 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
618 }
619
620 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
621 return true;
622
623 return false;
624}
625
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000626bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
627 unsigned i = 0, l = 0, u = 0;
628 switch (BuiltinID) {
629 default: return false;
630 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
631 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000632 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
633 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
634 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
635 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
636 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000637 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000638
Richard Sandiford28940af2014-04-16 08:47:51 +0000639 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000640}
641
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000642bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
643 switch (BuiltinID) {
644 case X86::BI_mm_prefetch:
Richard Sandiford28940af2014-04-16 08:47:51 +0000645 // This is declared to take (const char*, int)
646 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000647 }
648 return false;
649}
650
Richard Smith55ce3522012-06-25 20:30:08 +0000651/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
652/// parameter with the FormatAttr's correct format_idx and firstDataArg.
653/// Returns true when the format fits the function and the FormatStringInfo has
654/// been populated.
655bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
656 FormatStringInfo *FSI) {
657 FSI->HasVAListArg = Format->getFirstArg() == 0;
658 FSI->FormatIdx = Format->getFormatIdx() - 1;
659 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000660
Richard Smith55ce3522012-06-25 20:30:08 +0000661 // The way the format attribute works in GCC, the implicit this argument
662 // of member functions is counted. However, it doesn't appear in our own
663 // lists, so decrement format_idx in that case.
664 if (IsCXXMember) {
665 if(FSI->FormatIdx == 0)
666 return false;
667 --FSI->FormatIdx;
668 if (FSI->FirstDataArg != 0)
669 --FSI->FirstDataArg;
670 }
671 return true;
672}
Mike Stump11289f42009-09-09 15:08:12 +0000673
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000674/// Checks if a the given expression evaluates to null.
675///
676/// \brief Returns true if the value evaluates to null.
677static bool CheckNonNullExpr(Sema &S,
678 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000679 // As a special case, transparent unions initialized with zero are
680 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000681 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000682 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
683 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000684 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000685 if (const InitListExpr *ILE =
686 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000687 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000688 }
689
690 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000691 return (!Expr->isValueDependent() &&
692 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
693 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000694}
695
696static void CheckNonNullArgument(Sema &S,
697 const Expr *ArgExpr,
698 SourceLocation CallSiteLoc) {
699 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000700 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
701}
702
Ted Kremenek2bc73332014-01-17 06:24:43 +0000703static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000704 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000705 const Expr * const *ExprArgs,
706 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000707 // Check the attributes attached to the method/function itself.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000708 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Aaron Ballmana82eaa72014-05-02 13:35:42 +0000709 for (const auto &Val : NonNull->args())
710 CheckNonNullArgument(S, ExprArgs[Val], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000711 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000712
713 // Check the attributes on the parameters.
714 ArrayRef<ParmVarDecl*> parms;
715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
716 parms = FD->parameters();
717 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
718 parms = MD->parameters();
719
720 unsigned argIndex = 0;
721 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
722 I != E; ++I, ++argIndex) {
723 const ParmVarDecl *PVD = *I;
724 if (PVD->hasAttr<NonNullAttr>())
725 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
726 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000727}
728
Richard Smith55ce3522012-06-25 20:30:08 +0000729/// Handles the checks for format strings, non-POD arguments to vararg
730/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000731void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
732 unsigned NumParams, bool IsMemberFunction,
733 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000734 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000735 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000736 if (CurContext->isDependentContext())
737 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000738
Ted Kremenekb8176da2010-09-09 04:33:05 +0000739 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000740 llvm::SmallBitVector CheckedVarArgs;
741 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000742 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000743 // Only create vector if there are format attributes.
744 CheckedVarArgs.resize(Args.size());
745
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000746 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000747 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000748 }
Richard Smithd7293d72013-08-05 18:49:43 +0000749 }
Richard Smith55ce3522012-06-25 20:30:08 +0000750
751 // Refuse POD arguments that weren't caught by the format string
752 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000753 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000754 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000755 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000756 if (const Expr *Arg = Args[ArgIdx]) {
757 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
758 checkVariadicArgument(Arg, CallType);
759 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000760 }
Richard Smithd7293d72013-08-05 18:49:43 +0000761 }
Mike Stump11289f42009-09-09 15:08:12 +0000762
Richard Trieu41bc0992013-06-22 00:20:41 +0000763 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000764 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000765
Richard Trieu41bc0992013-06-22 00:20:41 +0000766 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000767 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
768 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000769 }
Richard Smith55ce3522012-06-25 20:30:08 +0000770}
771
772/// CheckConstructorCall - Check a constructor call for correctness and safety
773/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000774void Sema::CheckConstructorCall(FunctionDecl *FDecl,
775 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000776 const FunctionProtoType *Proto,
777 SourceLocation Loc) {
778 VariadicCallType CallType =
779 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000780 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000781 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
782}
783
784/// CheckFunctionCall - Check a direct function call for various correctness
785/// and safety properties not strictly enforced by the C type system.
786bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
787 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000788 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
789 isa<CXXMethodDecl>(FDecl);
790 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
791 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000792 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
793 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000794 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000795 Expr** Args = TheCall->getArgs();
796 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000797 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000798 // If this is a call to a member operator, hide the first argument
799 // from checkCall.
800 // FIXME: Our choice of AST representation here is less than ideal.
801 ++Args;
802 --NumArgs;
803 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000804 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000805 IsMemberFunction, TheCall->getRParenLoc(),
806 TheCall->getCallee()->getSourceRange(), CallType);
807
808 IdentifierInfo *FnInfo = FDecl->getIdentifier();
809 // None of the checks below are needed for functions that don't have
810 // simple names (e.g., C++ conversion functions).
811 if (!FnInfo)
812 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000813
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000814 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
815
Anna Zaks22122702012-01-17 00:37:07 +0000816 unsigned CMId = FDecl->getMemoryFunctionKind();
817 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000818 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000819
Anna Zaks201d4892012-01-13 21:52:01 +0000820 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000821 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000822 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000823 else if (CMId == Builtin::BIstrncat)
824 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000825 else
Anna Zaks22122702012-01-17 00:37:07 +0000826 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000827
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000828 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000829}
830
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000831bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000832 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000833 VariadicCallType CallType =
834 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000835
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000836 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000837 /*IsMemberFunction=*/false,
838 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000839
840 return false;
841}
842
Richard Trieu664c4c62013-06-20 21:03:13 +0000843bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
844 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000845 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
846 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000847 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000848
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000849 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000850 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000851 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000852
Richard Trieu664c4c62013-06-20 21:03:13 +0000853 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000854 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000855 CallType = VariadicDoesNotApply;
856 } else if (Ty->isBlockPointerType()) {
857 CallType = VariadicBlock;
858 } else { // Ty->isFunctionPointerType()
859 CallType = VariadicFunction;
860 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000861 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000862
Alp Toker9cacbab2014-01-20 20:26:09 +0000863 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
864 TheCall->getNumArgs()),
865 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000866 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000867
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000868 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000869}
870
Richard Trieu41bc0992013-06-22 00:20:41 +0000871/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
872/// such as function pointers returned from functions.
873bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000874 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +0000875 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000876 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000877
Craig Topperc3ec1492014-05-26 06:22:03 +0000878 checkCall(/*FDecl=*/nullptr,
879 llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
880 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +0000881 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000882 TheCall->getCallee()->getSourceRange(), CallType);
883
884 return false;
885}
886
Tim Northovere94a34c2014-03-11 10:49:14 +0000887static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
888 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
889 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
890 return false;
891
892 switch (Op) {
893 case AtomicExpr::AO__c11_atomic_init:
894 llvm_unreachable("There is no ordering argument for an init");
895
896 case AtomicExpr::AO__c11_atomic_load:
897 case AtomicExpr::AO__atomic_load_n:
898 case AtomicExpr::AO__atomic_load:
899 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
900 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
901
902 case AtomicExpr::AO__c11_atomic_store:
903 case AtomicExpr::AO__atomic_store:
904 case AtomicExpr::AO__atomic_store_n:
905 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
906 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
907 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
908
909 default:
910 return true;
911 }
912}
913
Richard Smithfeea8832012-04-12 05:08:17 +0000914ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
915 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000916 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
917 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000918
Richard Smithfeea8832012-04-12 05:08:17 +0000919 // All these operations take one of the following forms:
920 enum {
921 // C __c11_atomic_init(A *, C)
922 Init,
923 // C __c11_atomic_load(A *, int)
924 Load,
925 // void __atomic_load(A *, CP, int)
926 Copy,
927 // C __c11_atomic_add(A *, M, int)
928 Arithmetic,
929 // C __atomic_exchange_n(A *, CP, int)
930 Xchg,
931 // void __atomic_exchange(A *, C *, CP, int)
932 GNUXchg,
933 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
934 C11CmpXchg,
935 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
936 GNUCmpXchg
937 } Form = Init;
938 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
939 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
940 // where:
941 // C is an appropriate type,
942 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
943 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
944 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
945 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000946
Richard Smithfeea8832012-04-12 05:08:17 +0000947 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
948 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
949 && "need to update code for modified C11 atomics");
950 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
951 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
952 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
953 Op == AtomicExpr::AO__atomic_store_n ||
954 Op == AtomicExpr::AO__atomic_exchange_n ||
955 Op == AtomicExpr::AO__atomic_compare_exchange_n;
956 bool IsAddSub = false;
957
958 switch (Op) {
959 case AtomicExpr::AO__c11_atomic_init:
960 Form = Init;
961 break;
962
963 case AtomicExpr::AO__c11_atomic_load:
964 case AtomicExpr::AO__atomic_load_n:
965 Form = Load;
966 break;
967
968 case AtomicExpr::AO__c11_atomic_store:
969 case AtomicExpr::AO__atomic_load:
970 case AtomicExpr::AO__atomic_store:
971 case AtomicExpr::AO__atomic_store_n:
972 Form = Copy;
973 break;
974
975 case AtomicExpr::AO__c11_atomic_fetch_add:
976 case AtomicExpr::AO__c11_atomic_fetch_sub:
977 case AtomicExpr::AO__atomic_fetch_add:
978 case AtomicExpr::AO__atomic_fetch_sub:
979 case AtomicExpr::AO__atomic_add_fetch:
980 case AtomicExpr::AO__atomic_sub_fetch:
981 IsAddSub = true;
982 // Fall through.
983 case AtomicExpr::AO__c11_atomic_fetch_and:
984 case AtomicExpr::AO__c11_atomic_fetch_or:
985 case AtomicExpr::AO__c11_atomic_fetch_xor:
986 case AtomicExpr::AO__atomic_fetch_and:
987 case AtomicExpr::AO__atomic_fetch_or:
988 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +0000989 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +0000990 case AtomicExpr::AO__atomic_and_fetch:
991 case AtomicExpr::AO__atomic_or_fetch:
992 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +0000993 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +0000994 Form = Arithmetic;
995 break;
996
997 case AtomicExpr::AO__c11_atomic_exchange:
998 case AtomicExpr::AO__atomic_exchange_n:
999 Form = Xchg;
1000 break;
1001
1002 case AtomicExpr::AO__atomic_exchange:
1003 Form = GNUXchg;
1004 break;
1005
1006 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1007 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1008 Form = C11CmpXchg;
1009 break;
1010
1011 case AtomicExpr::AO__atomic_compare_exchange:
1012 case AtomicExpr::AO__atomic_compare_exchange_n:
1013 Form = GNUCmpXchg;
1014 break;
1015 }
1016
1017 // Check we have the right number of arguments.
1018 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001019 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001020 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001021 << TheCall->getCallee()->getSourceRange();
1022 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001023 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1024 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001025 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001026 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001027 << TheCall->getCallee()->getSourceRange();
1028 return ExprError();
1029 }
1030
Richard Smithfeea8832012-04-12 05:08:17 +00001031 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001032 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001033 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1034 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1035 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001036 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001037 << Ptr->getType() << Ptr->getSourceRange();
1038 return ExprError();
1039 }
1040
Richard Smithfeea8832012-04-12 05:08:17 +00001041 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1042 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1043 QualType ValType = AtomTy; // 'C'
1044 if (IsC11) {
1045 if (!AtomTy->isAtomicType()) {
1046 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1047 << Ptr->getType() << Ptr->getSourceRange();
1048 return ExprError();
1049 }
Richard Smithe00921a2012-09-15 06:09:58 +00001050 if (AtomTy.isConstQualified()) {
1051 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1052 << Ptr->getType() << Ptr->getSourceRange();
1053 return ExprError();
1054 }
Richard Smithfeea8832012-04-12 05:08:17 +00001055 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001056 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001057
Richard Smithfeea8832012-04-12 05:08:17 +00001058 // For an arithmetic operation, the implied arithmetic must be well-formed.
1059 if (Form == Arithmetic) {
1060 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1061 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1062 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1063 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1064 return ExprError();
1065 }
1066 if (!IsAddSub && !ValType->isIntegerType()) {
1067 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1068 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1069 return ExprError();
1070 }
1071 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1072 // For __atomic_*_n operations, the value type must be a scalar integral or
1073 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001074 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001075 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1076 return ExprError();
1077 }
1078
Eli Friedmanaa769812013-09-11 03:49:34 +00001079 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1080 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001081 // For GNU atomics, require a trivially-copyable type. This is not part of
1082 // the GNU atomics specification, but we enforce it for sanity.
1083 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001084 << Ptr->getType() << Ptr->getSourceRange();
1085 return ExprError();
1086 }
1087
Richard Smithfeea8832012-04-12 05:08:17 +00001088 // FIXME: For any builtin other than a load, the ValType must not be
1089 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001090
1091 switch (ValType.getObjCLifetime()) {
1092 case Qualifiers::OCL_None:
1093 case Qualifiers::OCL_ExplicitNone:
1094 // okay
1095 break;
1096
1097 case Qualifiers::OCL_Weak:
1098 case Qualifiers::OCL_Strong:
1099 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001100 // FIXME: Can this happen? By this point, ValType should be known
1101 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001102 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1103 << ValType << Ptr->getSourceRange();
1104 return ExprError();
1105 }
1106
1107 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001108 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001109 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001110 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001111 ResultType = Context.BoolTy;
1112
Richard Smithfeea8832012-04-12 05:08:17 +00001113 // The type of a parameter passed 'by value'. In the GNU atomics, such
1114 // arguments are actually passed as pointers.
1115 QualType ByValType = ValType; // 'CP'
1116 if (!IsC11 && !IsN)
1117 ByValType = Ptr->getType();
1118
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001119 // The first argument --- the pointer --- has a fixed type; we
1120 // deduce the types of the rest of the arguments accordingly. Walk
1121 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001122 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001123 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001124 if (i < NumVals[Form] + 1) {
1125 switch (i) {
1126 case 1:
1127 // The second argument is the non-atomic operand. For arithmetic, this
1128 // is always passed by value, and for a compare_exchange it is always
1129 // passed by address. For the rest, GNU uses by-address and C11 uses
1130 // by-value.
1131 assert(Form != Load);
1132 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1133 Ty = ValType;
1134 else if (Form == Copy || Form == Xchg)
1135 Ty = ByValType;
1136 else if (Form == Arithmetic)
1137 Ty = Context.getPointerDiffType();
1138 else
1139 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1140 break;
1141 case 2:
1142 // The third argument to compare_exchange / GNU exchange is a
1143 // (pointer to a) desired value.
1144 Ty = ByValType;
1145 break;
1146 case 3:
1147 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1148 Ty = Context.BoolTy;
1149 break;
1150 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001151 } else {
1152 // The order(s) are always converted to int.
1153 Ty = Context.IntTy;
1154 }
Richard Smithfeea8832012-04-12 05:08:17 +00001155
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001156 InitializedEntity Entity =
1157 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001158 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001159 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1160 if (Arg.isInvalid())
1161 return true;
1162 TheCall->setArg(i, Arg.get());
1163 }
1164
Richard Smithfeea8832012-04-12 05:08:17 +00001165 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001166 SmallVector<Expr*, 5> SubExprs;
1167 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001168 switch (Form) {
1169 case Init:
1170 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001171 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001172 break;
1173 case Load:
1174 SubExprs.push_back(TheCall->getArg(1)); // Order
1175 break;
1176 case Copy:
1177 case Arithmetic:
1178 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001179 SubExprs.push_back(TheCall->getArg(2)); // Order
1180 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001181 break;
1182 case GNUXchg:
1183 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1184 SubExprs.push_back(TheCall->getArg(3)); // Order
1185 SubExprs.push_back(TheCall->getArg(1)); // Val1
1186 SubExprs.push_back(TheCall->getArg(2)); // Val2
1187 break;
1188 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001189 SubExprs.push_back(TheCall->getArg(3)); // Order
1190 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001191 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001192 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001193 break;
1194 case GNUCmpXchg:
1195 SubExprs.push_back(TheCall->getArg(4)); // Order
1196 SubExprs.push_back(TheCall->getArg(1)); // Val1
1197 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1198 SubExprs.push_back(TheCall->getArg(2)); // Val2
1199 SubExprs.push_back(TheCall->getArg(3)); // Weak
1200 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001201 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001202
1203 if (SubExprs.size() >= 2 && Form != Init) {
1204 llvm::APSInt Result(32);
1205 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1206 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001207 Diag(SubExprs[1]->getLocStart(),
1208 diag::warn_atomic_op_has_invalid_memory_order)
1209 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001210 }
1211
Fariborz Jahanian615de762013-05-28 17:37:39 +00001212 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1213 SubExprs, ResultType, Op,
1214 TheCall->getRParenLoc());
1215
1216 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1217 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1218 Context.AtomicUsesUnsupportedLibcall(AE))
1219 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1220 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001221
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001222 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001223}
1224
1225
John McCall29ad95b2011-08-27 01:09:30 +00001226/// checkBuiltinArgument - Given a call to a builtin function, perform
1227/// normal type-checking on the given argument, updating the call in
1228/// place. This is useful when a builtin function requires custom
1229/// type-checking for some of its arguments but not necessarily all of
1230/// them.
1231///
1232/// Returns true on error.
1233static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1234 FunctionDecl *Fn = E->getDirectCallee();
1235 assert(Fn && "builtin call without direct callee!");
1236
1237 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1238 InitializedEntity Entity =
1239 InitializedEntity::InitializeParameter(S.Context, Param);
1240
1241 ExprResult Arg = E->getArg(0);
1242 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1243 if (Arg.isInvalid())
1244 return true;
1245
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001246 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001247 return false;
1248}
1249
Chris Lattnerdc046542009-05-08 06:58:22 +00001250/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1251/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1252/// type of its first argument. The main ActOnCallExpr routines have already
1253/// promoted the types of arguments because all of these calls are prototyped as
1254/// void(...).
1255///
1256/// This function goes through and does final semantic checking for these
1257/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001258ExprResult
1259Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001260 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001261 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1262 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1263
1264 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001265 if (TheCall->getNumArgs() < 1) {
1266 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1267 << 0 << 1 << TheCall->getNumArgs()
1268 << TheCall->getCallee()->getSourceRange();
1269 return ExprError();
1270 }
Mike Stump11289f42009-09-09 15:08:12 +00001271
Chris Lattnerdc046542009-05-08 06:58:22 +00001272 // Inspect the first argument of the atomic builtin. This should always be
1273 // a pointer type, whose element is an integral scalar or pointer type.
1274 // Because it is a pointer type, we don't have to worry about any implicit
1275 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001276 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001277 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001278 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1279 if (FirstArgResult.isInvalid())
1280 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001281 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001282 TheCall->setArg(0, FirstArg);
1283
John McCall31168b02011-06-15 23:02:42 +00001284 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1285 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001286 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1287 << FirstArg->getType() << FirstArg->getSourceRange();
1288 return ExprError();
1289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
John McCall31168b02011-06-15 23:02:42 +00001291 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001292 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001293 !ValType->isBlockPointerType()) {
1294 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1295 << FirstArg->getType() << FirstArg->getSourceRange();
1296 return ExprError();
1297 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001298
John McCall31168b02011-06-15 23:02:42 +00001299 switch (ValType.getObjCLifetime()) {
1300 case Qualifiers::OCL_None:
1301 case Qualifiers::OCL_ExplicitNone:
1302 // okay
1303 break;
1304
1305 case Qualifiers::OCL_Weak:
1306 case Qualifiers::OCL_Strong:
1307 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001308 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001309 << ValType << FirstArg->getSourceRange();
1310 return ExprError();
1311 }
1312
John McCallb50451a2011-10-05 07:41:44 +00001313 // Strip any qualifiers off ValType.
1314 ValType = ValType.getUnqualifiedType();
1315
Chandler Carruth3973af72010-07-18 20:54:12 +00001316 // The majority of builtins return a value, but a few have special return
1317 // types, so allow them to override appropriately below.
1318 QualType ResultType = ValType;
1319
Chris Lattnerdc046542009-05-08 06:58:22 +00001320 // We need to figure out which concrete builtin this maps onto. For example,
1321 // __sync_fetch_and_add with a 2 byte object turns into
1322 // __sync_fetch_and_add_2.
1323#define BUILTIN_ROW(x) \
1324 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1325 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Chris Lattnerdc046542009-05-08 06:58:22 +00001327 static const unsigned BuiltinIndices[][5] = {
1328 BUILTIN_ROW(__sync_fetch_and_add),
1329 BUILTIN_ROW(__sync_fetch_and_sub),
1330 BUILTIN_ROW(__sync_fetch_and_or),
1331 BUILTIN_ROW(__sync_fetch_and_and),
1332 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattnerdc046542009-05-08 06:58:22 +00001334 BUILTIN_ROW(__sync_add_and_fetch),
1335 BUILTIN_ROW(__sync_sub_and_fetch),
1336 BUILTIN_ROW(__sync_and_and_fetch),
1337 BUILTIN_ROW(__sync_or_and_fetch),
1338 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001339
Chris Lattnerdc046542009-05-08 06:58:22 +00001340 BUILTIN_ROW(__sync_val_compare_and_swap),
1341 BUILTIN_ROW(__sync_bool_compare_and_swap),
1342 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001343 BUILTIN_ROW(__sync_lock_release),
1344 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001345 };
Mike Stump11289f42009-09-09 15:08:12 +00001346#undef BUILTIN_ROW
1347
Chris Lattnerdc046542009-05-08 06:58:22 +00001348 // Determine the index of the size.
1349 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001350 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001351 case 1: SizeIndex = 0; break;
1352 case 2: SizeIndex = 1; break;
1353 case 4: SizeIndex = 2; break;
1354 case 8: SizeIndex = 3; break;
1355 case 16: SizeIndex = 4; break;
1356 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001357 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1358 << FirstArg->getType() << FirstArg->getSourceRange();
1359 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001360 }
Mike Stump11289f42009-09-09 15:08:12 +00001361
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 // Each of these builtins has one pointer argument, followed by some number of
1363 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1364 // that we ignore. Find out which row of BuiltinIndices to read from as well
1365 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001366 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001367 unsigned BuiltinIndex, NumFixed = 1;
1368 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001369 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001370 case Builtin::BI__sync_fetch_and_add:
1371 case Builtin::BI__sync_fetch_and_add_1:
1372 case Builtin::BI__sync_fetch_and_add_2:
1373 case Builtin::BI__sync_fetch_and_add_4:
1374 case Builtin::BI__sync_fetch_and_add_8:
1375 case Builtin::BI__sync_fetch_and_add_16:
1376 BuiltinIndex = 0;
1377 break;
1378
1379 case Builtin::BI__sync_fetch_and_sub:
1380 case Builtin::BI__sync_fetch_and_sub_1:
1381 case Builtin::BI__sync_fetch_and_sub_2:
1382 case Builtin::BI__sync_fetch_and_sub_4:
1383 case Builtin::BI__sync_fetch_and_sub_8:
1384 case Builtin::BI__sync_fetch_and_sub_16:
1385 BuiltinIndex = 1;
1386 break;
1387
1388 case Builtin::BI__sync_fetch_and_or:
1389 case Builtin::BI__sync_fetch_and_or_1:
1390 case Builtin::BI__sync_fetch_and_or_2:
1391 case Builtin::BI__sync_fetch_and_or_4:
1392 case Builtin::BI__sync_fetch_and_or_8:
1393 case Builtin::BI__sync_fetch_and_or_16:
1394 BuiltinIndex = 2;
1395 break;
1396
1397 case Builtin::BI__sync_fetch_and_and:
1398 case Builtin::BI__sync_fetch_and_and_1:
1399 case Builtin::BI__sync_fetch_and_and_2:
1400 case Builtin::BI__sync_fetch_and_and_4:
1401 case Builtin::BI__sync_fetch_and_and_8:
1402 case Builtin::BI__sync_fetch_and_and_16:
1403 BuiltinIndex = 3;
1404 break;
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregor73722482011-11-28 16:30:08 +00001406 case Builtin::BI__sync_fetch_and_xor:
1407 case Builtin::BI__sync_fetch_and_xor_1:
1408 case Builtin::BI__sync_fetch_and_xor_2:
1409 case Builtin::BI__sync_fetch_and_xor_4:
1410 case Builtin::BI__sync_fetch_and_xor_8:
1411 case Builtin::BI__sync_fetch_and_xor_16:
1412 BuiltinIndex = 4;
1413 break;
1414
1415 case Builtin::BI__sync_add_and_fetch:
1416 case Builtin::BI__sync_add_and_fetch_1:
1417 case Builtin::BI__sync_add_and_fetch_2:
1418 case Builtin::BI__sync_add_and_fetch_4:
1419 case Builtin::BI__sync_add_and_fetch_8:
1420 case Builtin::BI__sync_add_and_fetch_16:
1421 BuiltinIndex = 5;
1422 break;
1423
1424 case Builtin::BI__sync_sub_and_fetch:
1425 case Builtin::BI__sync_sub_and_fetch_1:
1426 case Builtin::BI__sync_sub_and_fetch_2:
1427 case Builtin::BI__sync_sub_and_fetch_4:
1428 case Builtin::BI__sync_sub_and_fetch_8:
1429 case Builtin::BI__sync_sub_and_fetch_16:
1430 BuiltinIndex = 6;
1431 break;
1432
1433 case Builtin::BI__sync_and_and_fetch:
1434 case Builtin::BI__sync_and_and_fetch_1:
1435 case Builtin::BI__sync_and_and_fetch_2:
1436 case Builtin::BI__sync_and_and_fetch_4:
1437 case Builtin::BI__sync_and_and_fetch_8:
1438 case Builtin::BI__sync_and_and_fetch_16:
1439 BuiltinIndex = 7;
1440 break;
1441
1442 case Builtin::BI__sync_or_and_fetch:
1443 case Builtin::BI__sync_or_and_fetch_1:
1444 case Builtin::BI__sync_or_and_fetch_2:
1445 case Builtin::BI__sync_or_and_fetch_4:
1446 case Builtin::BI__sync_or_and_fetch_8:
1447 case Builtin::BI__sync_or_and_fetch_16:
1448 BuiltinIndex = 8;
1449 break;
1450
1451 case Builtin::BI__sync_xor_and_fetch:
1452 case Builtin::BI__sync_xor_and_fetch_1:
1453 case Builtin::BI__sync_xor_and_fetch_2:
1454 case Builtin::BI__sync_xor_and_fetch_4:
1455 case Builtin::BI__sync_xor_and_fetch_8:
1456 case Builtin::BI__sync_xor_and_fetch_16:
1457 BuiltinIndex = 9;
1458 break;
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerdc046542009-05-08 06:58:22 +00001460 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001461 case Builtin::BI__sync_val_compare_and_swap_1:
1462 case Builtin::BI__sync_val_compare_and_swap_2:
1463 case Builtin::BI__sync_val_compare_and_swap_4:
1464 case Builtin::BI__sync_val_compare_and_swap_8:
1465 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001466 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001467 NumFixed = 2;
1468 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001469
Chris Lattnerdc046542009-05-08 06:58:22 +00001470 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001471 case Builtin::BI__sync_bool_compare_and_swap_1:
1472 case Builtin::BI__sync_bool_compare_and_swap_2:
1473 case Builtin::BI__sync_bool_compare_and_swap_4:
1474 case Builtin::BI__sync_bool_compare_and_swap_8:
1475 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001476 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001477 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001478 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001479 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001480
1481 case Builtin::BI__sync_lock_test_and_set:
1482 case Builtin::BI__sync_lock_test_and_set_1:
1483 case Builtin::BI__sync_lock_test_and_set_2:
1484 case Builtin::BI__sync_lock_test_and_set_4:
1485 case Builtin::BI__sync_lock_test_and_set_8:
1486 case Builtin::BI__sync_lock_test_and_set_16:
1487 BuiltinIndex = 12;
1488 break;
1489
Chris Lattnerdc046542009-05-08 06:58:22 +00001490 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001491 case Builtin::BI__sync_lock_release_1:
1492 case Builtin::BI__sync_lock_release_2:
1493 case Builtin::BI__sync_lock_release_4:
1494 case Builtin::BI__sync_lock_release_8:
1495 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001496 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001497 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001498 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001499 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001500
1501 case Builtin::BI__sync_swap:
1502 case Builtin::BI__sync_swap_1:
1503 case Builtin::BI__sync_swap_2:
1504 case Builtin::BI__sync_swap_4:
1505 case Builtin::BI__sync_swap_8:
1506 case Builtin::BI__sync_swap_16:
1507 BuiltinIndex = 14;
1508 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001509 }
Mike Stump11289f42009-09-09 15:08:12 +00001510
Chris Lattnerdc046542009-05-08 06:58:22 +00001511 // Now that we know how many fixed arguments we expect, first check that we
1512 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001513 if (TheCall->getNumArgs() < 1+NumFixed) {
1514 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1515 << 0 << 1+NumFixed << TheCall->getNumArgs()
1516 << TheCall->getCallee()->getSourceRange();
1517 return ExprError();
1518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Chris Lattner5b9241b2009-05-08 15:36:58 +00001520 // Get the decl for the concrete builtin from this, we can tell what the
1521 // concrete integer type we should convert to is.
1522 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1523 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001524 FunctionDecl *NewBuiltinDecl;
1525 if (NewBuiltinID == BuiltinID)
1526 NewBuiltinDecl = FDecl;
1527 else {
1528 // Perform builtin lookup to avoid redeclaring it.
1529 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1530 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1531 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1532 assert(Res.getFoundDecl());
1533 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001534 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001535 return ExprError();
1536 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001537
John McCallcf142162010-08-07 06:22:56 +00001538 // The first argument --- the pointer --- has a fixed type; we
1539 // deduce the types of the rest of the arguments accordingly. Walk
1540 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001541 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001542 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001543
Chris Lattnerdc046542009-05-08 06:58:22 +00001544 // GCC does an implicit conversion to the pointer or integer ValType. This
1545 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001546 // Initialize the argument.
1547 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1548 ValType, /*consume*/ false);
1549 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001550 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001551 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001552
Chris Lattnerdc046542009-05-08 06:58:22 +00001553 // Okay, we have something that *can* be converted to the right type. Check
1554 // to see if there is a potentially weird extension going on here. This can
1555 // happen when you do an atomic operation on something like an char* and
1556 // pass in 42. The 42 gets converted to char. This is even more strange
1557 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001558 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001559 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001560 }
Mike Stump11289f42009-09-09 15:08:12 +00001561
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001562 ASTContext& Context = this->getASTContext();
1563
1564 // Create a new DeclRefExpr to refer to the new decl.
1565 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1566 Context,
1567 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001568 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001569 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001570 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001571 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001572 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001573 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001574
Chris Lattnerdc046542009-05-08 06:58:22 +00001575 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001576 // FIXME: This loses syntactic information.
1577 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1578 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1579 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001580 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001582 // Change the result type of the call to match the original value type. This
1583 // is arbitrary, but the codegen for these builtins ins design to handle it
1584 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001585 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001586
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001587 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001588}
1589
Chris Lattner6436fb62009-02-18 06:01:06 +00001590/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001591/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001592/// Note: It might also make sense to do the UTF-16 conversion here (would
1593/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001594bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001595 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001596 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1597
Douglas Gregorfb65e592011-07-27 05:40:30 +00001598 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001599 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1600 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001601 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001602 }
Mike Stump11289f42009-09-09 15:08:12 +00001603
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001604 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001605 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001606 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001607 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001608 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001609 UTF16 *ToPtr = &ToBuf[0];
1610
1611 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1612 &ToPtr, ToPtr + NumBytes,
1613 strictConversion);
1614 // Check for conversion failure.
1615 if (Result != conversionOK)
1616 Diag(Arg->getLocStart(),
1617 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1618 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001619 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001620}
1621
Chris Lattnere202e6a2007-12-20 00:05:45 +00001622/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1623/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001624bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1625 Expr *Fn = TheCall->getCallee();
1626 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001627 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001628 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001629 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1630 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001631 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001632 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001633 return true;
1634 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001635
1636 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001637 return Diag(TheCall->getLocEnd(),
1638 diag::err_typecheck_call_too_few_args_at_least)
1639 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001640 }
1641
John McCall29ad95b2011-08-27 01:09:30 +00001642 // Type-check the first argument normally.
1643 if (checkBuiltinArgument(*this, TheCall, 0))
1644 return true;
1645
Chris Lattnere202e6a2007-12-20 00:05:45 +00001646 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001647 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001648 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001649 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001650 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001651 else if (FunctionDecl *FD = getCurFunctionDecl())
1652 isVariadic = FD->isVariadic();
1653 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001654 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001655
Chris Lattnere202e6a2007-12-20 00:05:45 +00001656 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001657 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1658 return true;
1659 }
Mike Stump11289f42009-09-09 15:08:12 +00001660
Chris Lattner43be2e62007-12-19 23:59:04 +00001661 // Verify that the second argument to the builtin is the last argument of the
1662 // current function or method.
1663 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001664 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001665
Nico Weber9eea7642013-05-24 23:31:57 +00001666 // These are valid if SecondArgIsLastNamedArgument is false after the next
1667 // block.
1668 QualType Type;
1669 SourceLocation ParamLoc;
1670
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001671 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1672 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001673 // FIXME: This isn't correct for methods (results in bogus warning).
1674 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001675 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001676 if (CurBlock)
1677 LastArg = *(CurBlock->TheDecl->param_end()-1);
1678 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001679 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001680 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001681 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001682 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001683
1684 Type = PV->getType();
1685 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001686 }
1687 }
Mike Stump11289f42009-09-09 15:08:12 +00001688
Chris Lattner43be2e62007-12-19 23:59:04 +00001689 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001690 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001691 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001692 else if (Type->isReferenceType()) {
1693 Diag(Arg->getLocStart(),
1694 diag::warn_va_start_of_reference_type_is_undefined);
1695 Diag(ParamLoc, diag::note_parameter_type) << Type;
1696 }
1697
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001698 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001699 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001700}
Chris Lattner43be2e62007-12-19 23:59:04 +00001701
Chris Lattner2da14fb2007-12-20 00:26:33 +00001702/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1703/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001704bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1705 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001706 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001707 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001708 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001709 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001710 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001711 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001712 << SourceRange(TheCall->getArg(2)->getLocStart(),
1713 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001714
John Wiegley01296292011-04-08 18:41:53 +00001715 ExprResult OrigArg0 = TheCall->getArg(0);
1716 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001717
Chris Lattner2da14fb2007-12-20 00:26:33 +00001718 // Do standard promotions between the two arguments, returning their common
1719 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001720 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001721 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1722 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001723
1724 // Make sure any conversions are pushed back into the call; this is
1725 // type safe since unordered compare builtins are declared as "_Bool
1726 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001727 TheCall->setArg(0, OrigArg0.get());
1728 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001729
John Wiegley01296292011-04-08 18:41:53 +00001730 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001731 return false;
1732
Chris Lattner2da14fb2007-12-20 00:26:33 +00001733 // If the common type isn't a real floating type, then the arguments were
1734 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001735 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001736 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001737 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001738 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1739 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001740
Chris Lattner2da14fb2007-12-20 00:26:33 +00001741 return false;
1742}
1743
Benjamin Kramer634fc102010-02-15 22:42:31 +00001744/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1745/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001746/// to check everything. We expect the last argument to be a floating point
1747/// value.
1748bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1749 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001750 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001751 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001752 if (TheCall->getNumArgs() > NumArgs)
1753 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001754 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001755 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001756 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001757 (*(TheCall->arg_end()-1))->getLocEnd());
1758
Benjamin Kramer64aae502010-02-16 10:07:31 +00001759 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001760
Eli Friedman7e4faac2009-08-31 20:06:00 +00001761 if (OrigArg->isTypeDependent())
1762 return false;
1763
Chris Lattner68784ef2010-05-06 05:50:07 +00001764 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001765 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001766 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001767 diag::err_typecheck_call_invalid_unary_fp)
1768 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001769
Chris Lattner68784ef2010-05-06 05:50:07 +00001770 // If this is an implicit conversion from float -> double, remove it.
1771 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1772 Expr *CastArg = Cast->getSubExpr();
1773 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1774 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1775 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00001776 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00001777 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001778 }
1779 }
1780
Eli Friedman7e4faac2009-08-31 20:06:00 +00001781 return false;
1782}
1783
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001784/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1785// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001786ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001787 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001788 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001789 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001790 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1791 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001792
Nate Begemana0110022010-06-08 00:16:34 +00001793 // Determine which of the following types of shufflevector we're checking:
1794 // 1) unary, vector mask: (lhs, mask)
1795 // 2) binary, vector mask: (lhs, rhs, mask)
1796 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1797 QualType resType = TheCall->getArg(0)->getType();
1798 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001799
Douglas Gregorc25f7662009-05-19 22:10:17 +00001800 if (!TheCall->getArg(0)->isTypeDependent() &&
1801 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001802 QualType LHSType = TheCall->getArg(0)->getType();
1803 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001804
Craig Topperbaca3892013-07-29 06:47:04 +00001805 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1806 return ExprError(Diag(TheCall->getLocStart(),
1807 diag::err_shufflevector_non_vector)
1808 << SourceRange(TheCall->getArg(0)->getLocStart(),
1809 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001810
Nate Begemana0110022010-06-08 00:16:34 +00001811 numElements = LHSType->getAs<VectorType>()->getNumElements();
1812 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001813
Nate Begemana0110022010-06-08 00:16:34 +00001814 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1815 // with mask. If so, verify that RHS is an integer vector type with the
1816 // same number of elts as lhs.
1817 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001818 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001819 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001820 return ExprError(Diag(TheCall->getLocStart(),
1821 diag::err_shufflevector_incompatible_vector)
1822 << SourceRange(TheCall->getArg(1)->getLocStart(),
1823 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001824 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001825 return ExprError(Diag(TheCall->getLocStart(),
1826 diag::err_shufflevector_incompatible_vector)
1827 << SourceRange(TheCall->getArg(0)->getLocStart(),
1828 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001829 } else if (numElements != numResElements) {
1830 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001831 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001832 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001833 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001834 }
1835
1836 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001837 if (TheCall->getArg(i)->isTypeDependent() ||
1838 TheCall->getArg(i)->isValueDependent())
1839 continue;
1840
Nate Begemana0110022010-06-08 00:16:34 +00001841 llvm::APSInt Result(32);
1842 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1843 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001844 diag::err_shufflevector_nonconstant_argument)
1845 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001846
Craig Topper50ad5b72013-08-03 17:40:38 +00001847 // Allow -1 which will be translated to undef in the IR.
1848 if (Result.isSigned() && Result.isAllOnesValue())
1849 continue;
1850
Chris Lattner7ab824e2008-08-10 02:05:13 +00001851 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001852 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001853 diag::err_shufflevector_argument_too_large)
1854 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001855 }
1856
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001857 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001858
Chris Lattner7ab824e2008-08-10 02:05:13 +00001859 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001860 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00001861 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001862 }
1863
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001864 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
1865 TheCall->getCallee()->getLocStart(),
1866 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001867}
Chris Lattner43be2e62007-12-19 23:59:04 +00001868
Hal Finkelc4d7c822013-09-18 03:29:45 +00001869/// SemaConvertVectorExpr - Handle __builtin_convertvector
1870ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1871 SourceLocation BuiltinLoc,
1872 SourceLocation RParenLoc) {
1873 ExprValueKind VK = VK_RValue;
1874 ExprObjectKind OK = OK_Ordinary;
1875 QualType DstTy = TInfo->getType();
1876 QualType SrcTy = E->getType();
1877
1878 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1879 return ExprError(Diag(BuiltinLoc,
1880 diag::err_convertvector_non_vector)
1881 << E->getSourceRange());
1882 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1883 return ExprError(Diag(BuiltinLoc,
1884 diag::err_convertvector_non_vector_type));
1885
1886 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1887 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1888 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1889 if (SrcElts != DstElts)
1890 return ExprError(Diag(BuiltinLoc,
1891 diag::err_convertvector_incompatible_vector)
1892 << E->getSourceRange());
1893 }
1894
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001895 return new (Context)
1896 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00001897}
1898
Daniel Dunbarb7257262008-07-21 22:59:13 +00001899/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1900// This is declared to take (const void*, ...) and can take two
1901// optional constant int args.
1902bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001903 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001904
Chris Lattner3b054132008-11-19 05:08:23 +00001905 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001906 return Diag(TheCall->getLocEnd(),
1907 diag::err_typecheck_call_too_many_args_at_most)
1908 << 0 /*function call*/ << 3 << NumArgs
1909 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001910
1911 // Argument 0 is checked for us and the remaining arguments must be
1912 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00001913 for (unsigned i = 1; i != NumArgs; ++i)
1914 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001916
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001917 return false;
1918}
1919
Eric Christopher8d0c6212010-04-17 02:26:23 +00001920/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1921/// TheCall is a constant expression.
1922bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1923 llvm::APSInt &Result) {
1924 Expr *Arg = TheCall->getArg(ArgNum);
1925 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1926 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1927
1928 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1929
1930 if (!Arg->isIntegerConstantExpr(Result, Context))
1931 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001932 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001933
Chris Lattnerd545ad12009-09-23 06:06:36 +00001934 return false;
1935}
1936
Richard Sandiford28940af2014-04-16 08:47:51 +00001937/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
1938/// TheCall is a constant expression in the range [Low, High].
1939bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
1940 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001941 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001942
1943 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00001944 Expr *Arg = TheCall->getArg(ArgNum);
1945 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001946 return false;
1947
Eric Christopher8d0c6212010-04-17 02:26:23 +00001948 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00001949 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00001950 return true;
1951
Richard Sandiford28940af2014-04-16 08:47:51 +00001952 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00001953 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00001954 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001955
1956 return false;
1957}
1958
Eli Friedmanc97d0142009-05-03 06:04:26 +00001959/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001960/// This checks that val is a constant 1.
1961bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1962 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001963 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001964
Eric Christopher8d0c6212010-04-17 02:26:23 +00001965 // TODO: This is less than ideal. Overload this to take a value.
1966 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1967 return true;
1968
1969 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001970 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1971 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1972
1973 return false;
1974}
1975
Richard Smithd7293d72013-08-05 18:49:43 +00001976namespace {
1977enum StringLiteralCheckType {
1978 SLCT_NotALiteral,
1979 SLCT_UncheckedLiteral,
1980 SLCT_CheckedLiteral
1981};
1982}
1983
Richard Smith55ce3522012-06-25 20:30:08 +00001984// Determine if an expression is a string literal or constant string.
1985// If this function returns false on the arguments to a function expecting a
1986// format string, we will usually need to emit a warning.
1987// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00001988static StringLiteralCheckType
1989checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1990 bool HasVAListArg, unsigned format_idx,
1991 unsigned firstDataArg, Sema::FormatStringType Type,
1992 Sema::VariadicCallType CallType, bool InFunctionCall,
1993 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00001994 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001995 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00001996 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001997
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00001998 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00001999
Richard Smithd7293d72013-08-05 18:49:43 +00002000 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002001 // Technically -Wformat-nonliteral does not warn about this case.
2002 // The behavior of printf and friends in this case is implementation
2003 // dependent. Ideally if the format string cannot be null then
2004 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002005 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002006
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002007 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002008 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002009 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002010 // The expression is a literal if both sub-expressions were, and it was
2011 // completely checked only if both sub-expressions were checked.
2012 const AbstractConditionalOperator *C =
2013 cast<AbstractConditionalOperator>(E);
2014 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002015 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002016 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002017 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002018 if (Left == SLCT_NotALiteral)
2019 return SLCT_NotALiteral;
2020 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002021 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002022 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002023 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002024 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002025 }
2026
2027 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002028 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2029 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002030 }
2031
John McCallc07a0c72011-02-17 10:25:35 +00002032 case Stmt::OpaqueValueExprClass:
2033 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2034 E = src;
2035 goto tryAgain;
2036 }
Richard Smith55ce3522012-06-25 20:30:08 +00002037 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002038
Ted Kremeneka8890832011-02-24 23:03:04 +00002039 case Stmt::PredefinedExprClass:
2040 // While __func__, etc., are technically not string literals, they
2041 // cannot contain format specifiers and thus are not a security
2042 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002043 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002044
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002045 case Stmt::DeclRefExprClass: {
2046 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002047
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002048 // As an exception, do not flag errors for variables binding to
2049 // const string literals.
2050 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2051 bool isConstant = false;
2052 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002053
Richard Smithd7293d72013-08-05 18:49:43 +00002054 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2055 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002056 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002057 isConstant = T.isConstant(S.Context) &&
2058 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002059 } else if (T->isObjCObjectPointerType()) {
2060 // In ObjC, there is usually no "const ObjectPointer" type,
2061 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002062 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002063 }
Mike Stump11289f42009-09-09 15:08:12 +00002064
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002065 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002066 if (const Expr *Init = VD->getAnyInitializer()) {
2067 // Look through initializers like const char c[] = { "foo" }
2068 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2069 if (InitList->isStringLiteralInit())
2070 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2071 }
Richard Smithd7293d72013-08-05 18:49:43 +00002072 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002073 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002074 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002075 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002076 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002077 }
Mike Stump11289f42009-09-09 15:08:12 +00002078
Anders Carlssonb012ca92009-06-28 19:55:58 +00002079 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2080 // special check to see if the format string is a function parameter
2081 // of the function calling the printf function. If the function
2082 // has an attribute indicating it is a printf-like function, then we
2083 // should suppress warnings concerning non-literals being used in a call
2084 // to a vprintf function. For example:
2085 //
2086 // void
2087 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2088 // va_list ap;
2089 // va_start(ap, fmt);
2090 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2091 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002092 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002093 if (HasVAListArg) {
2094 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2095 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2096 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002097 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002098 // adjust for implicit parameter
2099 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2100 if (MD->isInstance())
2101 ++PVIndex;
2102 // We also check if the formats are compatible.
2103 // We can't pass a 'scanf' string to a 'printf' function.
2104 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002105 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002106 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002107 }
2108 }
2109 }
2110 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Richard Smith55ce3522012-06-25 20:30:08 +00002113 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002114 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002115
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002116 case Stmt::CallExprClass:
2117 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002118 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002119 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2120 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2121 unsigned ArgIndex = FA->getFormatIdx();
2122 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2123 if (MD->isInstance())
2124 --ArgIndex;
2125 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002126
Richard Smithd7293d72013-08-05 18:49:43 +00002127 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002128 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002129 Type, CallType, InFunctionCall,
2130 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002131 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2132 unsigned BuiltinID = FD->getBuiltinID();
2133 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2134 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2135 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002136 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002137 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002138 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002139 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002140 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002141 }
2142 }
Mike Stump11289f42009-09-09 15:08:12 +00002143
Richard Smith55ce3522012-06-25 20:30:08 +00002144 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002145 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002146 case Stmt::ObjCStringLiteralClass:
2147 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002148 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002150 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002151 StrE = ObjCFExpr->getString();
2152 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002153 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002154
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002155 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002156 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2157 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002158 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002159 }
Mike Stump11289f42009-09-09 15:08:12 +00002160
Richard Smith55ce3522012-06-25 20:30:08 +00002161 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002162 }
Mike Stump11289f42009-09-09 15:08:12 +00002163
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002165 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002166 }
2167}
2168
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002169Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002170 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002171 .Case("scanf", FST_Scanf)
2172 .Cases("printf", "printf0", FST_Printf)
2173 .Cases("NSString", "CFString", FST_NSString)
2174 .Case("strftime", FST_Strftime)
2175 .Case("strfmon", FST_Strfmon)
2176 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2177 .Default(FST_Unknown);
2178}
2179
Jordan Rose3e0ec582012-07-19 18:10:23 +00002180/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002181/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002182/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002183bool Sema::CheckFormatArguments(const FormatAttr *Format,
2184 ArrayRef<const Expr *> Args,
2185 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002186 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002187 SourceLocation Loc, SourceRange Range,
2188 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002189 FormatStringInfo FSI;
2190 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002191 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002192 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002193 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002194 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002195}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002196
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002197bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002198 bool HasVAListArg, unsigned format_idx,
2199 unsigned firstDataArg, FormatStringType Type,
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) {
Ted Kremenek02087932010-07-16 02:11:22 +00002203 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002204 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002205 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002206 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002209 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002210
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002211 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002212 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002213 // Dynamically generated format strings are difficult to
2214 // automatically vet at compile time. Requiring that format strings
2215 // are string literals: (1) permits the checking of format strings by
2216 // the compiler and thereby (2) can practically remove the source of
2217 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002218
Mike Stump11289f42009-09-09 15:08:12 +00002219 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002220 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002221 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002222 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002223 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002224 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2225 format_idx, firstDataArg, Type, CallType,
2226 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002227 if (CT != SLCT_NotALiteral)
2228 // Literal format string found, check done!
2229 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002230
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002231 // Strftime is particular as it always uses a single 'time' argument,
2232 // so it is safe to pass a non-literal string.
2233 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002234 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002235
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002236 // Do not emit diag when the string param is a macro expansion and the
2237 // format is either NSString or CFString. This is a hack to prevent
2238 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2239 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002240 if (Type == FST_NSString &&
2241 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002242 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002243
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002244 // If there are no arguments specified, warn with -Wformat-security, otherwise
2245 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002246 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002247 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002248 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002249 << OrigFormatExpr->getSourceRange();
2250 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002251 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002252 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002253 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002254 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002255}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002256
Ted Kremenekab278de2010-01-28 23:39:18 +00002257namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002258class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2259protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002260 Sema &S;
2261 const StringLiteral *FExpr;
2262 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002263 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002264 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002265 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002266 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002267 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002268 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002269 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002270 bool usesPositionalArgs;
2271 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002272 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002273 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002274 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002275public:
Ted Kremenek02087932010-07-16 02:11:22 +00002276 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002277 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002278 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002279 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002280 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002281 Sema::VariadicCallType callType,
2282 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002283 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002284 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2285 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002286 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002287 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002288 inFunctionCall(inFunctionCall), CallType(callType),
2289 CheckedVarArgs(CheckedVarArgs) {
2290 CoveredArgs.resize(numDataArgs);
2291 CoveredArgs.reset();
2292 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002293
Ted Kremenek019d2242010-01-29 01:50:07 +00002294 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002295
Ted Kremenek02087932010-07-16 02:11:22 +00002296 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002297 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002298
Jordan Rose92303592012-09-08 04:00:03 +00002299 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002300 const analyze_format_string::FormatSpecifier &FS,
2301 const analyze_format_string::ConversionSpecifier &CS,
2302 const char *startSpecifier, unsigned specifierLen,
2303 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002304
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002305 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002306 const analyze_format_string::FormatSpecifier &FS,
2307 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002308
2309 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002310 const analyze_format_string::ConversionSpecifier &CS,
2311 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002312
Craig Toppere14c0f82014-03-12 04:55:44 +00002313 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002314
Craig Toppere14c0f82014-03-12 04:55:44 +00002315 void HandleInvalidPosition(const char *startSpecifier,
2316 unsigned specifierLen,
2317 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002318
Craig Toppere14c0f82014-03-12 04:55:44 +00002319 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002320
Craig Toppere14c0f82014-03-12 04:55:44 +00002321 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002322
Richard Trieu03cf7b72011-10-28 00:41:25 +00002323 template <typename Range>
2324 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2325 const Expr *ArgumentExpr,
2326 PartialDiagnostic PDiag,
2327 SourceLocation StringLoc,
2328 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002329 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002330
Ted Kremenek02087932010-07-16 02:11:22 +00002331protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002332 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2333 const char *startSpec,
2334 unsigned specifierLen,
2335 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002336
2337 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2338 const char *startSpec,
2339 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002340
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002341 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002342 CharSourceRange getSpecifierRange(const char *startSpecifier,
2343 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002344 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002345
Ted Kremenek5739de72010-01-29 01:06:55 +00002346 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002347
2348 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2349 const analyze_format_string::ConversionSpecifier &CS,
2350 const char *startSpecifier, unsigned specifierLen,
2351 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002352
2353 template <typename Range>
2354 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2355 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002356 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002357};
2358}
2359
Ted Kremenek02087932010-07-16 02:11:22 +00002360SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002361 return OrigFormatExpr->getSourceRange();
2362}
2363
Ted Kremenek02087932010-07-16 02:11:22 +00002364CharSourceRange CheckFormatHandler::
2365getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002366 SourceLocation Start = getLocationOfByte(startSpecifier);
2367 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2368
2369 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002370 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002371
2372 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002373}
2374
Ted Kremenek02087932010-07-16 02:11:22 +00002375SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002376 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002377}
2378
Ted Kremenek02087932010-07-16 02:11:22 +00002379void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2380 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002381 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2382 getLocationOfByte(startSpecifier),
2383 /*IsStringLocation*/true,
2384 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002385}
2386
Jordan Rose92303592012-09-08 04:00:03 +00002387void CheckFormatHandler::HandleInvalidLengthModifier(
2388 const analyze_format_string::FormatSpecifier &FS,
2389 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002390 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002391 using namespace analyze_format_string;
2392
2393 const LengthModifier &LM = FS.getLengthModifier();
2394 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2395
2396 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002397 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002398 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002399 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002400 getLocationOfByte(LM.getStart()),
2401 /*IsStringLocation*/true,
2402 getSpecifierRange(startSpecifier, specifierLen));
2403
2404 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2405 << FixedLM->toString()
2406 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2407
2408 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002409 FixItHint Hint;
2410 if (DiagID == diag::warn_format_nonsensical_length)
2411 Hint = FixItHint::CreateRemoval(LMRange);
2412
2413 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),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002417 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002418 }
2419}
2420
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002421void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002422 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002423 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002424 using namespace analyze_format_string;
2425
2426 const LengthModifier &LM = FS.getLengthModifier();
2427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2428
2429 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002431 if (FixedLM) {
2432 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2433 << LM.toString() << 0,
2434 getLocationOfByte(LM.getStart()),
2435 /*IsStringLocation*/true,
2436 getSpecifierRange(startSpecifier, specifierLen));
2437
2438 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2439 << FixedLM->toString()
2440 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2441
2442 } else {
2443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2444 << LM.toString() << 0,
2445 getLocationOfByte(LM.getStart()),
2446 /*IsStringLocation*/true,
2447 getSpecifierRange(startSpecifier, specifierLen));
2448 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002449}
2450
2451void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2452 const analyze_format_string::ConversionSpecifier &CS,
2453 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002454 using namespace analyze_format_string;
2455
2456 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002457 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002458 if (FixedCS) {
2459 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2460 << CS.toString() << /*conversion specifier*/1,
2461 getLocationOfByte(CS.getStart()),
2462 /*IsStringLocation*/true,
2463 getSpecifierRange(startSpecifier, specifierLen));
2464
2465 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2466 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2467 << FixedCS->toString()
2468 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2469 } else {
2470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2471 << CS.toString() << /*conversion specifier*/1,
2472 getLocationOfByte(CS.getStart()),
2473 /*IsStringLocation*/true,
2474 getSpecifierRange(startSpecifier, specifierLen));
2475 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002476}
2477
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002478void CheckFormatHandler::HandlePosition(const char *startPos,
2479 unsigned posLen) {
2480 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2481 getLocationOfByte(startPos),
2482 /*IsStringLocation*/true,
2483 getSpecifierRange(startPos, posLen));
2484}
2485
Ted Kremenekd1668192010-02-27 01:41:03 +00002486void
Ted Kremenek02087932010-07-16 02:11:22 +00002487CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2488 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002489 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2490 << (unsigned) p,
2491 getLocationOfByte(startPos), /*IsStringLocation*/true,
2492 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002493}
2494
Ted Kremenek02087932010-07-16 02:11:22 +00002495void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002496 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002497 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2498 getLocationOfByte(startPos),
2499 /*IsStringLocation*/true,
2500 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002501}
2502
Ted Kremenek02087932010-07-16 02:11:22 +00002503void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002504 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002505 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002506 EmitFormatDiagnostic(
2507 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2508 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2509 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002510 }
Ted Kremenek02087932010-07-16 02:11:22 +00002511}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002512
Jordan Rose58bbe422012-07-19 18:10:08 +00002513// Note that this may return NULL if there was an error parsing or building
2514// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002515const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002516 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002517}
2518
2519void CheckFormatHandler::DoneProcessing() {
2520 // Does the number of data arguments exceed the number of
2521 // format conversions in the format string?
2522 if (!HasVAListArg) {
2523 // Find any arguments that weren't covered.
2524 CoveredArgs.flip();
2525 signed notCoveredArg = CoveredArgs.find_first();
2526 if (notCoveredArg >= 0) {
2527 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002528 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2529 SourceLocation Loc = E->getLocStart();
2530 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2531 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2532 Loc, /*IsStringLocation*/false,
2533 getFormatStringRange());
2534 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002535 }
Ted Kremenek02087932010-07-16 02:11:22 +00002536 }
2537 }
2538}
2539
Ted Kremenekce815422010-07-19 21:25:57 +00002540bool
2541CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2542 SourceLocation Loc,
2543 const char *startSpec,
2544 unsigned specifierLen,
2545 const char *csStart,
2546 unsigned csLen) {
2547
2548 bool keepGoing = true;
2549 if (argIndex < NumDataArgs) {
2550 // Consider the argument coverered, even though the specifier doesn't
2551 // make sense.
2552 CoveredArgs.set(argIndex);
2553 }
2554 else {
2555 // If argIndex exceeds the number of data arguments we
2556 // don't issue a warning because that is just a cascade of warnings (and
2557 // they may have intended '%%' anyway). We don't want to continue processing
2558 // the format string after this point, however, as we will like just get
2559 // gibberish when trying to match arguments.
2560 keepGoing = false;
2561 }
2562
Richard Trieu03cf7b72011-10-28 00:41:25 +00002563 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2564 << StringRef(csStart, csLen),
2565 Loc, /*IsStringLocation*/true,
2566 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002567
2568 return keepGoing;
2569}
2570
Richard Trieu03cf7b72011-10-28 00:41:25 +00002571void
2572CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2573 const char *startSpec,
2574 unsigned specifierLen) {
2575 EmitFormatDiagnostic(
2576 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2577 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2578}
2579
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002580bool
2581CheckFormatHandler::CheckNumArgs(
2582 const analyze_format_string::FormatSpecifier &FS,
2583 const analyze_format_string::ConversionSpecifier &CS,
2584 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2585
2586 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002587 PartialDiagnostic PDiag = FS.usesPositionalArg()
2588 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2589 << (argIndex+1) << NumDataArgs)
2590 : S.PDiag(diag::warn_printf_insufficient_data_args);
2591 EmitFormatDiagnostic(
2592 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2593 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002594 return false;
2595 }
2596 return true;
2597}
2598
Richard Trieu03cf7b72011-10-28 00:41:25 +00002599template<typename Range>
2600void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2601 SourceLocation Loc,
2602 bool IsStringLocation,
2603 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002604 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002605 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002606 Loc, IsStringLocation, StringRange, FixIt);
2607}
2608
2609/// \brief If the format string is not within the funcion call, emit a note
2610/// so that the function call and string are in diagnostic messages.
2611///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002612/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002613/// call and only one diagnostic message will be produced. Otherwise, an
2614/// extra note will be emitted pointing to location of the format string.
2615///
2616/// \param ArgumentExpr the expression that is passed as the format string
2617/// argument in the function call. Used for getting locations when two
2618/// diagnostics are emitted.
2619///
2620/// \param PDiag the callee should already have provided any strings for the
2621/// diagnostic message. This function only adds locations and fixits
2622/// to diagnostics.
2623///
2624/// \param Loc primary location for diagnostic. If two diagnostics are
2625/// required, one will be at Loc and a new SourceLocation will be created for
2626/// the other one.
2627///
2628/// \param IsStringLocation if true, Loc points to the format string should be
2629/// used for the note. Otherwise, Loc points to the argument list and will
2630/// be used with PDiag.
2631///
2632/// \param StringRange some or all of the string to highlight. This is
2633/// templated so it can accept either a CharSourceRange or a SourceRange.
2634///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002635/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002636template<typename Range>
2637void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2638 const Expr *ArgumentExpr,
2639 PartialDiagnostic PDiag,
2640 SourceLocation Loc,
2641 bool IsStringLocation,
2642 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002643 ArrayRef<FixItHint> FixIt) {
2644 if (InFunctionCall) {
2645 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2646 D << StringRange;
2647 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2648 I != E; ++I) {
2649 D << *I;
2650 }
2651 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002652 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2653 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002654
2655 const Sema::SemaDiagnosticBuilder &Note =
2656 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2657 diag::note_format_string_defined);
2658
2659 Note << StringRange;
2660 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2661 I != E; ++I) {
2662 Note << *I;
2663 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002664 }
2665}
2666
Ted Kremenek02087932010-07-16 02:11:22 +00002667//===--- CHECK: Printf format string checking ------------------------------===//
2668
2669namespace {
2670class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002671 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002672public:
2673 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2674 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002675 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002676 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002677 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002678 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002679 Sema::VariadicCallType CallType,
2680 llvm::SmallBitVector &CheckedVarArgs)
2681 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2682 numDataArgs, beg, hasVAListArg, Args,
2683 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2684 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002685 {}
2686
Craig Toppere14c0f82014-03-12 04:55:44 +00002687
Ted Kremenek02087932010-07-16 02:11:22 +00002688 bool HandleInvalidPrintfConversionSpecifier(
2689 const analyze_printf::PrintfSpecifier &FS,
2690 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002691 unsigned specifierLen) override;
2692
Ted Kremenek02087932010-07-16 02:11:22 +00002693 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2694 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002695 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002696 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2697 const char *StartSpecifier,
2698 unsigned SpecifierLen,
2699 const Expr *E);
2700
Ted Kremenek02087932010-07-16 02:11:22 +00002701 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2702 const char *startSpecifier, unsigned specifierLen);
2703 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2704 const analyze_printf::OptionalAmount &Amt,
2705 unsigned type,
2706 const char *startSpecifier, unsigned specifierLen);
2707 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2708 const analyze_printf::OptionalFlag &flag,
2709 const char *startSpecifier, unsigned specifierLen);
2710 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2711 const analyze_printf::OptionalFlag &ignoredFlag,
2712 const analyze_printf::OptionalFlag &flag,
2713 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002714 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002715 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002716
Ted Kremenek02087932010-07-16 02:11:22 +00002717};
2718}
2719
2720bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2721 const analyze_printf::PrintfSpecifier &FS,
2722 const char *startSpecifier,
2723 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002724 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002725 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002726
Ted Kremenekce815422010-07-19 21:25:57 +00002727 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2728 getLocationOfByte(CS.getStart()),
2729 startSpecifier, specifierLen,
2730 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002731}
2732
Ted Kremenek02087932010-07-16 02:11:22 +00002733bool CheckPrintfHandler::HandleAmount(
2734 const analyze_format_string::OptionalAmount &Amt,
2735 unsigned k, const char *startSpecifier,
2736 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002737
2738 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002739 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002740 unsigned argIndex = Amt.getArgIndex();
2741 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2743 << k,
2744 getLocationOfByte(Amt.getStart()),
2745 /*IsStringLocation*/true,
2746 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002747 // Don't do any more checking. We will just emit
2748 // spurious errors.
2749 return false;
2750 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002751
Ted Kremenek5739de72010-01-29 01:06:55 +00002752 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002753 // Although not in conformance with C99, we also allow the argument to be
2754 // an 'unsigned int' as that is a reasonably safe case. GCC also
2755 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002756 CoveredArgs.set(argIndex);
2757 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002758 if (!Arg)
2759 return false;
2760
Ted Kremenek5739de72010-01-29 01:06:55 +00002761 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002762
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002763 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2764 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002765
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002766 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002767 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002768 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002769 << T << Arg->getSourceRange(),
2770 getLocationOfByte(Amt.getStart()),
2771 /*IsStringLocation*/true,
2772 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002773 // Don't do any more checking. We will just emit
2774 // spurious errors.
2775 return false;
2776 }
2777 }
2778 }
2779 return true;
2780}
Ted Kremenek5739de72010-01-29 01:06:55 +00002781
Tom Careb49ec692010-06-17 19:00:27 +00002782void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002783 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002784 const analyze_printf::OptionalAmount &Amt,
2785 unsigned type,
2786 const char *startSpecifier,
2787 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002788 const analyze_printf::PrintfConversionSpecifier &CS =
2789 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002790
Richard Trieu03cf7b72011-10-28 00:41:25 +00002791 FixItHint fixit =
2792 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2793 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2794 Amt.getConstantLength()))
2795 : FixItHint();
2796
2797 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2798 << type << CS.toString(),
2799 getLocationOfByte(Amt.getStart()),
2800 /*IsStringLocation*/true,
2801 getSpecifierRange(startSpecifier, specifierLen),
2802 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002803}
2804
Ted Kremenek02087932010-07-16 02:11:22 +00002805void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002806 const analyze_printf::OptionalFlag &flag,
2807 const char *startSpecifier,
2808 unsigned specifierLen) {
2809 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002810 const analyze_printf::PrintfConversionSpecifier &CS =
2811 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002812 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2813 << flag.toString() << CS.toString(),
2814 getLocationOfByte(flag.getPosition()),
2815 /*IsStringLocation*/true,
2816 getSpecifierRange(startSpecifier, specifierLen),
2817 FixItHint::CreateRemoval(
2818 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002819}
2820
2821void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002822 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002823 const analyze_printf::OptionalFlag &ignoredFlag,
2824 const analyze_printf::OptionalFlag &flag,
2825 const char *startSpecifier,
2826 unsigned specifierLen) {
2827 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002828 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2829 << ignoredFlag.toString() << flag.toString(),
2830 getLocationOfByte(ignoredFlag.getPosition()),
2831 /*IsStringLocation*/true,
2832 getSpecifierRange(startSpecifier, specifierLen),
2833 FixItHint::CreateRemoval(
2834 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002835}
2836
Richard Smith55ce3522012-06-25 20:30:08 +00002837// Determines if the specified is a C++ class or struct containing
2838// a member with the specified name and kind (e.g. a CXXMethodDecl named
2839// "c_str()").
2840template<typename MemberKind>
2841static llvm::SmallPtrSet<MemberKind*, 1>
2842CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2843 const RecordType *RT = Ty->getAs<RecordType>();
2844 llvm::SmallPtrSet<MemberKind*, 1> Results;
2845
2846 if (!RT)
2847 return Results;
2848 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002849 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002850 return Results;
2851
Alp Tokerb6cc5922014-05-03 03:45:55 +00002852 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00002853 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002854 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002855
2856 // We just need to include all members of the right kind turned up by the
2857 // filter, at this point.
2858 if (S.LookupQualifiedName(R, RT->getDecl()))
2859 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2860 NamedDecl *decl = (*I)->getUnderlyingDecl();
2861 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2862 Results.insert(FK);
2863 }
2864 return Results;
2865}
2866
Richard Smith2868a732014-02-28 01:36:39 +00002867/// Check if we could call '.c_str()' on an object.
2868///
2869/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2870/// allow the call, or if it would be ambiguous).
2871bool Sema::hasCStrMethod(const Expr *E) {
2872 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2873 MethodSet Results =
2874 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2875 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2876 MI != ME; ++MI)
2877 if ((*MI)->getMinRequiredArguments() == 0)
2878 return true;
2879 return false;
2880}
2881
Richard Smith55ce3522012-06-25 20:30:08 +00002882// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002883// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002884// Returns true when a c_str() conversion method is found.
2885bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002886 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002887 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2888
2889 MethodSet Results =
2890 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2891
2892 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2893 MI != ME; ++MI) {
2894 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002895 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002896 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002897 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00002898 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00002899 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2900 << "c_str()"
2901 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2902 return true;
2903 }
2904 }
2905
2906 return false;
2907}
2908
Ted Kremenekab278de2010-01-28 23:39:18 +00002909bool
Ted Kremenek02087932010-07-16 02:11:22 +00002910CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002911 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002912 const char *startSpecifier,
2913 unsigned specifierLen) {
2914
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002915 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002916 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002917 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002918
Ted Kremenek6cd69422010-07-19 22:01:06 +00002919 if (FS.consumesDataArgument()) {
2920 if (atFirstArg) {
2921 atFirstArg = false;
2922 usesPositionalArgs = FS.usesPositionalArg();
2923 }
2924 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002925 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2926 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002927 return false;
2928 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002929 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002930
Ted Kremenekd1668192010-02-27 01:41:03 +00002931 // First check if the field width, precision, and conversion specifier
2932 // have matching data arguments.
2933 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2934 startSpecifier, specifierLen)) {
2935 return false;
2936 }
2937
2938 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2939 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002940 return false;
2941 }
2942
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002943 if (!CS.consumesDataArgument()) {
2944 // FIXME: Technically specifying a precision or field width here
2945 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002946 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002947 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002948
Ted Kremenek4a49d982010-02-26 19:18:41 +00002949 // Consume the argument.
2950 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002951 if (argIndex < NumDataArgs) {
2952 // The check to see if the argIndex is valid will come later.
2953 // We set the bit here because we may exit early from this
2954 // function if we encounter some other error.
2955 CoveredArgs.set(argIndex);
2956 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00002957
2958 // Check for using an Objective-C specific conversion specifier
2959 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002960 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00002961 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2962 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00002963 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002964
Tom Careb49ec692010-06-17 19:00:27 +00002965 // Check for invalid use of field width
2966 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00002967 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00002968 startSpecifier, specifierLen);
2969 }
2970
2971 // Check for invalid use of precision
2972 if (!FS.hasValidPrecision()) {
2973 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2974 startSpecifier, specifierLen);
2975 }
2976
2977 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00002978 if (!FS.hasValidThousandsGroupingPrefix())
2979 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002980 if (!FS.hasValidLeadingZeros())
2981 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2982 if (!FS.hasValidPlusPrefix())
2983 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00002984 if (!FS.hasValidSpacePrefix())
2985 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002986 if (!FS.hasValidAlternativeForm())
2987 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2988 if (!FS.hasValidLeftJustified())
2989 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2990
2991 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00002992 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2993 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2994 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00002995 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2996 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2997 startSpecifier, specifierLen);
2998
2999 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003000 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003001 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3002 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003003 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003004 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003005 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003006 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3007 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003008
Jordan Rose92303592012-09-08 04:00:03 +00003009 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3010 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3011
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003012 // The remaining checks depend on the data arguments.
3013 if (HasVAListArg)
3014 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003015
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003016 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003017 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003018
Jordan Rose58bbe422012-07-19 18:10:08 +00003019 const Expr *Arg = getDataArg(argIndex);
3020 if (!Arg)
3021 return true;
3022
3023 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003024}
3025
Jordan Roseaee34382012-09-05 22:56:26 +00003026static bool requiresParensToAddCast(const Expr *E) {
3027 // FIXME: We should have a general way to reason about operator
3028 // precedence and whether parens are actually needed here.
3029 // Take care of a few common cases where they aren't.
3030 const Expr *Inside = E->IgnoreImpCasts();
3031 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3032 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3033
3034 switch (Inside->getStmtClass()) {
3035 case Stmt::ArraySubscriptExprClass:
3036 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003037 case Stmt::CharacterLiteralClass:
3038 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003039 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003040 case Stmt::FloatingLiteralClass:
3041 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003042 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003043 case Stmt::ObjCArrayLiteralClass:
3044 case Stmt::ObjCBoolLiteralExprClass:
3045 case Stmt::ObjCBoxedExprClass:
3046 case Stmt::ObjCDictionaryLiteralClass:
3047 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003048 case Stmt::ObjCIvarRefExprClass:
3049 case Stmt::ObjCMessageExprClass:
3050 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003051 case Stmt::ObjCStringLiteralClass:
3052 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003053 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003054 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003055 case Stmt::UnaryOperatorClass:
3056 return false;
3057 default:
3058 return true;
3059 }
3060}
3061
Richard Smith55ce3522012-06-25 20:30:08 +00003062bool
3063CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3064 const char *StartSpecifier,
3065 unsigned SpecifierLen,
3066 const Expr *E) {
3067 using namespace analyze_format_string;
3068 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003069 // Now type check the data expression that matches the
3070 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003071 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3072 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003073 if (!AT.isValid())
3074 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003075
Jordan Rose598ec092012-12-05 18:44:40 +00003076 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003077 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3078 ExprTy = TET->getUnderlyingExpr()->getType();
3079 }
3080
Jordan Rose598ec092012-12-05 18:44:40 +00003081 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003082 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003083
Jordan Rose22b74712012-09-05 22:56:19 +00003084 // Look through argument promotions for our error message's reported type.
3085 // This includes the integral and floating promotions, but excludes array
3086 // and function pointer decay; seeing that an argument intended to be a
3087 // string has type 'char [6]' is probably more confusing than 'char *'.
3088 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3089 if (ICE->getCastKind() == CK_IntegralCast ||
3090 ICE->getCastKind() == CK_FloatingCast) {
3091 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003092 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003093
3094 // Check if we didn't match because of an implicit cast from a 'char'
3095 // or 'short' to an 'int'. This is done because printf is a varargs
3096 // function.
3097 if (ICE->getType() == S.Context.IntTy ||
3098 ICE->getType() == S.Context.UnsignedIntTy) {
3099 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003100 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003101 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003102 }
Jordan Rose98709982012-06-04 22:48:57 +00003103 }
Jordan Rose598ec092012-12-05 18:44:40 +00003104 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3105 // Special case for 'a', which has type 'int' in C.
3106 // Note, however, that we do /not/ want to treat multibyte constants like
3107 // 'MooV' as characters! This form is deprecated but still exists.
3108 if (ExprTy == S.Context.IntTy)
3109 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3110 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003111 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003112
Jordan Rosebc53ed12014-05-31 04:12:14 +00003113 // Look through enums to their underlying type.
3114 bool IsEnum = false;
3115 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3116 ExprTy = EnumTy->getDecl()->getIntegerType();
3117 IsEnum = true;
3118 }
3119
Jordan Rose0e5badd2012-12-05 18:44:49 +00003120 // %C in an Objective-C context prints a unichar, not a wchar_t.
3121 // If the argument is an integer of some kind, believe the %C and suggest
3122 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003123 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003124 if (ObjCContext &&
3125 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3126 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3127 !ExprTy->isCharType()) {
3128 // 'unichar' is defined as a typedef of unsigned short, but we should
3129 // prefer using the typedef if it is visible.
3130 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003131
3132 // While we are here, check if the value is an IntegerLiteral that happens
3133 // to be within the valid range.
3134 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3135 const llvm::APInt &V = IL->getValue();
3136 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3137 return true;
3138 }
3139
Jordan Rose0e5badd2012-12-05 18:44:49 +00003140 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3141 Sema::LookupOrdinaryName);
3142 if (S.LookupName(Result, S.getCurScope())) {
3143 NamedDecl *ND = Result.getFoundDecl();
3144 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3145 if (TD->getUnderlyingType() == IntendedTy)
3146 IntendedTy = S.Context.getTypedefType(TD);
3147 }
3148 }
3149 }
3150
3151 // Special-case some of Darwin's platform-independence types by suggesting
3152 // casts to primitive types that are known to be large enough.
3153 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003154 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003155 // Use a 'while' to peel off layers of typedefs.
3156 QualType TyTy = IntendedTy;
3157 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003158 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003159 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003160 .Case("NSInteger", S.Context.LongTy)
3161 .Case("NSUInteger", S.Context.UnsignedLongTy)
3162 .Case("SInt32", S.Context.IntTy)
3163 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003164 .Default(QualType());
3165
3166 if (!CastTy.isNull()) {
3167 ShouldNotPrintDirectly = true;
3168 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003169 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003170 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003171 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003172 }
3173 }
3174
Jordan Rose22b74712012-09-05 22:56:19 +00003175 // We may be able to offer a FixItHint if it is a supported type.
3176 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003177 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003178 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003179
Jordan Rose22b74712012-09-05 22:56:19 +00003180 if (success) {
3181 // Get the fix string from the fixed format specifier
3182 SmallString<16> buf;
3183 llvm::raw_svector_ostream os(buf);
3184 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003185
Jordan Roseaee34382012-09-05 22:56:26 +00003186 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3187
Jordan Rose0e5badd2012-12-05 18:44:49 +00003188 if (IntendedTy == ExprTy) {
3189 // In this case, the specifier is wrong and should be changed to match
3190 // the argument.
3191 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003192 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3193 << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003194 << E->getSourceRange(),
3195 E->getLocStart(),
3196 /*IsStringLocation*/false,
3197 SpecRange,
3198 FixItHint::CreateReplacement(SpecRange, os.str()));
3199
3200 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003201 // The canonical type for formatting this value is different from the
3202 // actual type of the expression. (This occurs, for example, with Darwin's
3203 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3204 // should be printed as 'long' for 64-bit compatibility.)
3205 // Rather than emitting a normal format/argument mismatch, we want to
3206 // add a cast to the recommended type (and correct the format string
3207 // if necessary).
3208 SmallString<16> CastBuf;
3209 llvm::raw_svector_ostream CastFix(CastBuf);
3210 CastFix << "(";
3211 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3212 CastFix << ")";
3213
3214 SmallVector<FixItHint,4> Hints;
3215 if (!AT.matchesType(S.Context, IntendedTy))
3216 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3217
3218 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3219 // If there's already a cast present, just replace it.
3220 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3221 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3222
3223 } else if (!requiresParensToAddCast(E)) {
3224 // If the expression has high enough precedence,
3225 // just write the C-style cast.
3226 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3227 CastFix.str()));
3228 } else {
3229 // Otherwise, add parens around the expression as well as the cast.
3230 CastFix << "(";
3231 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3232 CastFix.str()));
3233
Alp Tokerb6cc5922014-05-03 03:45:55 +00003234 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003235 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3236 }
3237
Jordan Rose0e5badd2012-12-05 18:44:49 +00003238 if (ShouldNotPrintDirectly) {
3239 // The expression has a type that should not be printed directly.
3240 // We extract the name from the typedef because we don't want to show
3241 // the underlying type in the diagnostic.
3242 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003243
Jordan Rose0e5badd2012-12-05 18:44:49 +00003244 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003245 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003246 << E->getSourceRange(),
3247 E->getLocStart(), /*IsStringLocation=*/false,
3248 SpecRange, Hints);
3249 } else {
3250 // In this case, the expression could be printed using a different
3251 // specifier, but we've decided that the specifier is probably correct
3252 // and we should cast instead. Just use the normal warning message.
3253 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003254 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3255 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003256 << E->getSourceRange(),
3257 E->getLocStart(), /*IsStringLocation*/false,
3258 SpecRange, Hints);
3259 }
Jordan Roseaee34382012-09-05 22:56:26 +00003260 }
Jordan Rose22b74712012-09-05 22:56:19 +00003261 } else {
3262 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3263 SpecifierLen);
3264 // Since the warning for passing non-POD types to variadic functions
3265 // was deferred until now, we emit a warning for non-POD
3266 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003267 switch (S.isValidVarArgType(ExprTy)) {
3268 case Sema::VAK_Valid:
3269 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003270 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003271 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3272 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Richard Smithd7293d72013-08-05 18:49:43 +00003273 << CSR
3274 << E->getSourceRange(),
3275 E->getLocStart(), /*IsStringLocation*/false, CSR);
3276 break;
3277
3278 case Sema::VAK_Undefined:
3279 EmitFormatDiagnostic(
3280 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003281 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003282 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003283 << CallType
3284 << AT.getRepresentativeTypeName(S.Context)
3285 << CSR
3286 << E->getSourceRange(),
3287 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003288 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003289 break;
3290
3291 case Sema::VAK_Invalid:
3292 if (ExprTy->isObjCObjectType())
3293 EmitFormatDiagnostic(
3294 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3295 << S.getLangOpts().CPlusPlus11
3296 << ExprTy
3297 << CallType
3298 << AT.getRepresentativeTypeName(S.Context)
3299 << CSR
3300 << E->getSourceRange(),
3301 E->getLocStart(), /*IsStringLocation*/false, CSR);
3302 else
3303 // FIXME: If this is an initializer list, suggest removing the braces
3304 // or inserting a cast to the target type.
3305 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3306 << isa<InitListExpr>(E) << ExprTy << CallType
3307 << AT.getRepresentativeTypeName(S.Context)
3308 << E->getSourceRange();
3309 break;
3310 }
3311
3312 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3313 "format string specifier index out of range");
3314 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003315 }
3316
Ted Kremenekab278de2010-01-28 23:39:18 +00003317 return true;
3318}
3319
Ted Kremenek02087932010-07-16 02:11:22 +00003320//===--- CHECK: Scanf format string checking ------------------------------===//
3321
3322namespace {
3323class CheckScanfHandler : public CheckFormatHandler {
3324public:
3325 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3326 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003327 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003328 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003329 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003330 Sema::VariadicCallType CallType,
3331 llvm::SmallBitVector &CheckedVarArgs)
3332 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3333 numDataArgs, beg, hasVAListArg,
3334 Args, formatIdx, inFunctionCall, CallType,
3335 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003336 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003337
3338 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3339 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003340 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003341
3342 bool HandleInvalidScanfConversionSpecifier(
3343 const analyze_scanf::ScanfSpecifier &FS,
3344 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003345 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003346
Craig Toppere14c0f82014-03-12 04:55:44 +00003347 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003348};
Ted Kremenek019d2242010-01-29 01:50:07 +00003349}
Ted Kremenekab278de2010-01-28 23:39:18 +00003350
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003351void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3352 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003353 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3354 getLocationOfByte(end), /*IsStringLocation*/true,
3355 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003356}
3357
Ted Kremenekce815422010-07-19 21:25:57 +00003358bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3359 const analyze_scanf::ScanfSpecifier &FS,
3360 const char *startSpecifier,
3361 unsigned specifierLen) {
3362
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003363 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003364 FS.getConversionSpecifier();
3365
3366 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3367 getLocationOfByte(CS.getStart()),
3368 startSpecifier, specifierLen,
3369 CS.getStart(), CS.getLength());
3370}
3371
Ted Kremenek02087932010-07-16 02:11:22 +00003372bool CheckScanfHandler::HandleScanfSpecifier(
3373 const analyze_scanf::ScanfSpecifier &FS,
3374 const char *startSpecifier,
3375 unsigned specifierLen) {
3376
3377 using namespace analyze_scanf;
3378 using namespace analyze_format_string;
3379
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003380 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003381
Ted Kremenek6cd69422010-07-19 22:01:06 +00003382 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3383 // be used to decide if we are using positional arguments consistently.
3384 if (FS.consumesDataArgument()) {
3385 if (atFirstArg) {
3386 atFirstArg = false;
3387 usesPositionalArgs = FS.usesPositionalArg();
3388 }
3389 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003390 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3391 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003392 return false;
3393 }
Ted Kremenek02087932010-07-16 02:11:22 +00003394 }
3395
3396 // Check if the field with is non-zero.
3397 const OptionalAmount &Amt = FS.getFieldWidth();
3398 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3399 if (Amt.getConstantAmount() == 0) {
3400 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3401 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003402 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3403 getLocationOfByte(Amt.getStart()),
3404 /*IsStringLocation*/true, R,
3405 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003406 }
3407 }
3408
3409 if (!FS.consumesDataArgument()) {
3410 // FIXME: Technically specifying a precision or field width here
3411 // makes no sense. Worth issuing a warning at some point.
3412 return true;
3413 }
3414
3415 // Consume the argument.
3416 unsigned argIndex = FS.getArgIndex();
3417 if (argIndex < NumDataArgs) {
3418 // The check to see if the argIndex is valid will come later.
3419 // We set the bit here because we may exit early from this
3420 // function if we encounter some other error.
3421 CoveredArgs.set(argIndex);
3422 }
3423
Ted Kremenek4407ea42010-07-20 20:04:47 +00003424 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003425 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003426 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3427 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003428 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003429 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003430 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003431 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3432 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003433
Jordan Rose92303592012-09-08 04:00:03 +00003434 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3435 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3436
Ted Kremenek02087932010-07-16 02:11:22 +00003437 // The remaining checks depend on the data arguments.
3438 if (HasVAListArg)
3439 return true;
3440
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003441 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003442 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003443
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003444 // Check that the argument type matches the format specifier.
3445 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003446 if (!Ex)
3447 return true;
3448
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003449 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3450 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003451 ScanfSpecifier fixedFS = FS;
Jordan Rose177b0a32014-03-20 03:32:39 +00003452 bool success = fixedFS.fixType(Ex->getType(),
3453 Ex->IgnoreImpCasts()->getType(),
3454 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003455
3456 if (success) {
3457 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003458 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003459 llvm::raw_svector_ostream os(buf);
3460 fixedFS.toString(os);
3461
3462 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003463 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3464 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003465 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003466 Ex->getLocStart(),
3467 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003468 getSpecifierRange(startSpecifier, specifierLen),
3469 FixItHint::CreateReplacement(
3470 getSpecifierRange(startSpecifier, specifierLen),
3471 os.str()));
3472 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003473 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003474 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3475 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003476 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003477 Ex->getLocStart(),
3478 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003479 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003480 }
3481 }
3482
Ted Kremenek02087932010-07-16 02:11:22 +00003483 return true;
3484}
3485
3486void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003487 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003488 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003489 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003490 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003491 bool inFunctionCall, VariadicCallType CallType,
3492 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003493
Ted Kremenekab278de2010-01-28 23:39:18 +00003494 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003495 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003496 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003497 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003498 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3499 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003500 return;
3501 }
Ted Kremenek02087932010-07-16 02:11:22 +00003502
Ted Kremenekab278de2010-01-28 23:39:18 +00003503 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003504 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003505 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003506 // Account for cases where the string literal is truncated in a declaration.
3507 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3508 assert(T && "String literal not of constant array type!");
3509 size_t TypeSize = T->getSize().getZExtValue();
3510 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003511 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003512
3513 // Emit a warning if the string literal is truncated and does not contain an
3514 // embedded null character.
3515 if (TypeSize <= StrRef.size() &&
3516 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3517 CheckFormatHandler::EmitFormatDiagnostic(
3518 *this, inFunctionCall, Args[format_idx],
3519 PDiag(diag::warn_printf_format_string_not_null_terminated),
3520 FExpr->getLocStart(),
3521 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3522 return;
3523 }
3524
Ted Kremenekab278de2010-01-28 23:39:18 +00003525 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003526 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003527 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003528 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003529 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3530 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003531 return;
3532 }
Ted Kremenek02087932010-07-16 02:11:22 +00003533
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003534 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003535 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003536 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003537 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003538 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003539
Hans Wennborg23926bd2011-12-15 10:25:47 +00003540 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003541 getLangOpts(),
3542 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003543 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003544 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003545 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003546 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003547 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003548
Hans Wennborg23926bd2011-12-15 10:25:47 +00003549 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003550 getLangOpts(),
3551 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003552 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003553 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003554}
3555
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003556//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3557
3558// Returns the related absolute value function that is larger, of 0 if one
3559// does not exist.
3560static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3561 switch (AbsFunction) {
3562 default:
3563 return 0;
3564
3565 case Builtin::BI__builtin_abs:
3566 return Builtin::BI__builtin_labs;
3567 case Builtin::BI__builtin_labs:
3568 return Builtin::BI__builtin_llabs;
3569 case Builtin::BI__builtin_llabs:
3570 return 0;
3571
3572 case Builtin::BI__builtin_fabsf:
3573 return Builtin::BI__builtin_fabs;
3574 case Builtin::BI__builtin_fabs:
3575 return Builtin::BI__builtin_fabsl;
3576 case Builtin::BI__builtin_fabsl:
3577 return 0;
3578
3579 case Builtin::BI__builtin_cabsf:
3580 return Builtin::BI__builtin_cabs;
3581 case Builtin::BI__builtin_cabs:
3582 return Builtin::BI__builtin_cabsl;
3583 case Builtin::BI__builtin_cabsl:
3584 return 0;
3585
3586 case Builtin::BIabs:
3587 return Builtin::BIlabs;
3588 case Builtin::BIlabs:
3589 return Builtin::BIllabs;
3590 case Builtin::BIllabs:
3591 return 0;
3592
3593 case Builtin::BIfabsf:
3594 return Builtin::BIfabs;
3595 case Builtin::BIfabs:
3596 return Builtin::BIfabsl;
3597 case Builtin::BIfabsl:
3598 return 0;
3599
3600 case Builtin::BIcabsf:
3601 return Builtin::BIcabs;
3602 case Builtin::BIcabs:
3603 return Builtin::BIcabsl;
3604 case Builtin::BIcabsl:
3605 return 0;
3606 }
3607}
3608
3609// Returns the argument type of the absolute value function.
3610static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3611 unsigned AbsType) {
3612 if (AbsType == 0)
3613 return QualType();
3614
3615 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3616 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3617 if (Error != ASTContext::GE_None)
3618 return QualType();
3619
3620 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3621 if (!FT)
3622 return QualType();
3623
3624 if (FT->getNumParams() != 1)
3625 return QualType();
3626
3627 return FT->getParamType(0);
3628}
3629
3630// Returns the best absolute value function, or zero, based on type and
3631// current absolute value function.
3632static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3633 unsigned AbsFunctionKind) {
3634 unsigned BestKind = 0;
3635 uint64_t ArgSize = Context.getTypeSize(ArgType);
3636 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3637 Kind = getLargerAbsoluteValueFunction(Kind)) {
3638 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3639 if (Context.getTypeSize(ParamType) >= ArgSize) {
3640 if (BestKind == 0)
3641 BestKind = Kind;
3642 else if (Context.hasSameType(ParamType, ArgType)) {
3643 BestKind = Kind;
3644 break;
3645 }
3646 }
3647 }
3648 return BestKind;
3649}
3650
3651enum AbsoluteValueKind {
3652 AVK_Integer,
3653 AVK_Floating,
3654 AVK_Complex
3655};
3656
3657static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3658 if (T->isIntegralOrEnumerationType())
3659 return AVK_Integer;
3660 if (T->isRealFloatingType())
3661 return AVK_Floating;
3662 if (T->isAnyComplexType())
3663 return AVK_Complex;
3664
3665 llvm_unreachable("Type not integer, floating, or complex");
3666}
3667
3668// Changes the absolute value function to a different type. Preserves whether
3669// the function is a builtin.
3670static unsigned changeAbsFunction(unsigned AbsKind,
3671 AbsoluteValueKind ValueKind) {
3672 switch (ValueKind) {
3673 case AVK_Integer:
3674 switch (AbsKind) {
3675 default:
3676 return 0;
3677 case Builtin::BI__builtin_fabsf:
3678 case Builtin::BI__builtin_fabs:
3679 case Builtin::BI__builtin_fabsl:
3680 case Builtin::BI__builtin_cabsf:
3681 case Builtin::BI__builtin_cabs:
3682 case Builtin::BI__builtin_cabsl:
3683 return Builtin::BI__builtin_abs;
3684 case Builtin::BIfabsf:
3685 case Builtin::BIfabs:
3686 case Builtin::BIfabsl:
3687 case Builtin::BIcabsf:
3688 case Builtin::BIcabs:
3689 case Builtin::BIcabsl:
3690 return Builtin::BIabs;
3691 }
3692 case AVK_Floating:
3693 switch (AbsKind) {
3694 default:
3695 return 0;
3696 case Builtin::BI__builtin_abs:
3697 case Builtin::BI__builtin_labs:
3698 case Builtin::BI__builtin_llabs:
3699 case Builtin::BI__builtin_cabsf:
3700 case Builtin::BI__builtin_cabs:
3701 case Builtin::BI__builtin_cabsl:
3702 return Builtin::BI__builtin_fabsf;
3703 case Builtin::BIabs:
3704 case Builtin::BIlabs:
3705 case Builtin::BIllabs:
3706 case Builtin::BIcabsf:
3707 case Builtin::BIcabs:
3708 case Builtin::BIcabsl:
3709 return Builtin::BIfabsf;
3710 }
3711 case AVK_Complex:
3712 switch (AbsKind) {
3713 default:
3714 return 0;
3715 case Builtin::BI__builtin_abs:
3716 case Builtin::BI__builtin_labs:
3717 case Builtin::BI__builtin_llabs:
3718 case Builtin::BI__builtin_fabsf:
3719 case Builtin::BI__builtin_fabs:
3720 case Builtin::BI__builtin_fabsl:
3721 return Builtin::BI__builtin_cabsf;
3722 case Builtin::BIabs:
3723 case Builtin::BIlabs:
3724 case Builtin::BIllabs:
3725 case Builtin::BIfabsf:
3726 case Builtin::BIfabs:
3727 case Builtin::BIfabsl:
3728 return Builtin::BIcabsf;
3729 }
3730 }
3731 llvm_unreachable("Unable to convert function");
3732}
3733
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003734static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003735 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3736 if (!FnInfo)
3737 return 0;
3738
3739 switch (FDecl->getBuiltinID()) {
3740 default:
3741 return 0;
3742 case Builtin::BI__builtin_abs:
3743 case Builtin::BI__builtin_fabs:
3744 case Builtin::BI__builtin_fabsf:
3745 case Builtin::BI__builtin_fabsl:
3746 case Builtin::BI__builtin_labs:
3747 case Builtin::BI__builtin_llabs:
3748 case Builtin::BI__builtin_cabs:
3749 case Builtin::BI__builtin_cabsf:
3750 case Builtin::BI__builtin_cabsl:
3751 case Builtin::BIabs:
3752 case Builtin::BIlabs:
3753 case Builtin::BIllabs:
3754 case Builtin::BIfabs:
3755 case Builtin::BIfabsf:
3756 case Builtin::BIfabsl:
3757 case Builtin::BIcabs:
3758 case Builtin::BIcabsf:
3759 case Builtin::BIcabsl:
3760 return FDecl->getBuiltinID();
3761 }
3762 llvm_unreachable("Unknown Builtin type");
3763}
3764
3765// If the replacement is valid, emit a note with replacement function.
3766// Additionally, suggest including the proper header if not already included.
3767static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00003768 unsigned AbsKind, QualType ArgType) {
3769 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003770 const char *HeaderName = nullptr;
3771 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003772 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
3773 FunctionName = "std::abs";
3774 if (ArgType->isIntegralOrEnumerationType()) {
3775 HeaderName = "cstdlib";
3776 } else if (ArgType->isRealFloatingType()) {
3777 HeaderName = "cmath";
3778 } else {
3779 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003780 }
Richard Trieubeffb832014-04-15 23:47:53 +00003781
3782 // Lookup all std::abs
3783 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00003784 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00003785 R.suppressDiagnostics();
3786 S.LookupQualifiedName(R, Std);
3787
3788 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00003789 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00003790 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
3791 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
3792 } else {
3793 FDecl = dyn_cast<FunctionDecl>(I);
3794 }
3795 if (!FDecl)
3796 continue;
3797
3798 // Found std::abs(), check that they are the right ones.
3799 if (FDecl->getNumParams() != 1)
3800 continue;
3801
3802 // Check that the parameter type can handle the argument.
3803 QualType ParamType = FDecl->getParamDecl(0)->getType();
3804 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
3805 S.Context.getTypeSize(ArgType) <=
3806 S.Context.getTypeSize(ParamType)) {
3807 // Found a function, don't need the header hint.
3808 EmitHeaderHint = false;
3809 break;
3810 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003811 }
Richard Trieubeffb832014-04-15 23:47:53 +00003812 }
3813 } else {
3814 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
3815 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
3816
3817 if (HeaderName) {
3818 DeclarationName DN(&S.Context.Idents.get(FunctionName));
3819 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
3820 R.suppressDiagnostics();
3821 S.LookupName(R, S.getCurScope());
3822
3823 if (R.isSingleResult()) {
3824 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3825 if (FD && FD->getBuiltinID() == AbsKind) {
3826 EmitHeaderHint = false;
3827 } else {
3828 return;
3829 }
3830 } else if (!R.empty()) {
3831 return;
3832 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003833 }
3834 }
3835
3836 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00003837 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003838
Richard Trieubeffb832014-04-15 23:47:53 +00003839 if (!HeaderName)
3840 return;
3841
3842 if (!EmitHeaderHint)
3843 return;
3844
3845 S.Diag(Loc, diag::note_please_include_header) << HeaderName << FunctionName;
3846}
3847
3848static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
3849 if (!FDecl)
3850 return false;
3851
3852 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
3853 return false;
3854
3855 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
3856
3857 while (ND && ND->isInlineNamespace()) {
3858 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003859 }
Richard Trieubeffb832014-04-15 23:47:53 +00003860
3861 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
3862 return false;
3863
3864 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
3865 return false;
3866
3867 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003868}
3869
3870// Warn when using the wrong abs() function.
3871void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3872 const FunctionDecl *FDecl,
3873 IdentifierInfo *FnInfo) {
3874 if (Call->getNumArgs() != 1)
3875 return;
3876
3877 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00003878 bool IsStdAbs = IsFunctionStdAbs(FDecl);
3879 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003880 return;
3881
3882 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3883 QualType ParamType = Call->getArg(0)->getType();
3884
3885 // Unsigned types can not be negative. Suggest to drop the absolute value
3886 // function.
3887 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00003888 const char *FunctionName =
3889 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003890 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3891 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00003892 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003893 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3894 return;
3895 }
3896
Richard Trieubeffb832014-04-15 23:47:53 +00003897 // std::abs has overloads which prevent most of the absolute value problems
3898 // from occurring.
3899 if (IsStdAbs)
3900 return;
3901
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003902 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3903 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3904
3905 // The argument and parameter are the same kind. Check if they are the right
3906 // size.
3907 if (ArgValueKind == ParamValueKind) {
3908 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3909 return;
3910
3911 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3912 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3913 << FDecl << ArgType << ParamType;
3914
3915 if (NewAbsKind == 0)
3916 return;
3917
3918 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003919 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003920 return;
3921 }
3922
3923 // ArgValueKind != ParamValueKind
3924 // The wrong type of absolute value function was used. Attempt to find the
3925 // proper one.
3926 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3927 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3928 if (NewAbsKind == 0)
3929 return;
3930
3931 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3932 << FDecl << ParamValueKind << ArgValueKind;
3933
3934 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00003935 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003936 return;
3937}
3938
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003939//===--- CHECK: Standard memory functions ---------------------------------===//
3940
Nico Weber0e6daef2013-12-26 23:38:39 +00003941/// \brief Takes the expression passed to the size_t parameter of functions
3942/// such as memcmp, strncat, etc and warns if it's a comparison.
3943///
3944/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3945static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3946 IdentifierInfo *FnName,
3947 SourceLocation FnLoc,
3948 SourceLocation RParenLoc) {
3949 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3950 if (!Size)
3951 return false;
3952
3953 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3954 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3955 return false;
3956
Nico Weber0e6daef2013-12-26 23:38:39 +00003957 SourceRange SizeRange = Size->getSourceRange();
3958 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3959 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00003960 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00003961 << FnName << FixItHint::CreateInsertion(
3962 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00003963 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00003964 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00003965 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00003966 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
3967 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00003968
3969 return true;
3970}
3971
Douglas Gregora74926b2011-05-03 20:05:22 +00003972/// \brief Determine whether the given type is a dynamic class type (e.g.,
3973/// whether it has a vtable).
3974static bool isDynamicClassType(QualType T) {
3975 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3976 if (CXXRecordDecl *Definition = Record->getDefinition())
3977 if (Definition->isDynamicClass())
3978 return true;
3979
3980 return false;
3981}
3982
Chandler Carruth889ed862011-06-21 23:04:20 +00003983/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003984/// otherwise returns NULL.
3985static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003986 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003987 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3988 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3989 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003990
Craig Topperc3ec1492014-05-26 06:22:03 +00003991 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003992}
3993
Chandler Carruth889ed862011-06-21 23:04:20 +00003994/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003995static QualType getSizeOfArgType(const Expr* E) {
3996 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3997 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3998 if (SizeOf->getKind() == clang::UETT_SizeOf)
3999 return SizeOf->getTypeOfArgument();
4000
4001 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004002}
4003
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004004/// \brief Check for dangerous or invalid arguments to memset().
4005///
Chandler Carruthac687262011-06-03 06:23:57 +00004006/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004007/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4008/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004009///
4010/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004011void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004012 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004013 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004014 assert(BId != 0);
4015
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004016 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004017 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004018 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004019 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004020 return;
4021
Anna Zaks22122702012-01-17 00:37:07 +00004022 unsigned LastArg = (BId == Builtin::BImemset ||
4023 BId == Builtin::BIstrndup ? 1 : 2);
4024 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004025 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004026
Nico Weber0e6daef2013-12-26 23:38:39 +00004027 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4028 Call->getLocStart(), Call->getRParenLoc()))
4029 return;
4030
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004031 // We have special checking when the length is a sizeof expression.
4032 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4033 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4034 llvm::FoldingSetNodeID SizeOfArgID;
4035
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004036 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4037 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004038 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004039
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004040 QualType DestTy = Dest->getType();
4041 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4042 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004043
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004044 // Never warn about void type pointers. This can be used to suppress
4045 // false positives.
4046 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004047 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004048
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004049 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4050 // actually comparing the expressions for equality. Because computing the
4051 // expression IDs can be expensive, we only do this if the diagnostic is
4052 // enabled.
4053 if (SizeOfArg &&
4054 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4055 SizeOfArg->getExprLoc())) {
4056 // We only compute IDs for expressions if the warning is enabled, and
4057 // cache the sizeof arg's ID.
4058 if (SizeOfArgID == llvm::FoldingSetNodeID())
4059 SizeOfArg->Profile(SizeOfArgID, Context, true);
4060 llvm::FoldingSetNodeID DestID;
4061 Dest->Profile(DestID, Context, true);
4062 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004063 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4064 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004065 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004066 StringRef ReadableName = FnName->getName();
4067
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004068 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004069 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004070 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004071 if (!PointeeTy->isIncompleteType() &&
4072 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004073 ActionIdx = 2; // If the pointee's size is sizeof(char),
4074 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004075
4076 // If the function is defined as a builtin macro, do not show macro
4077 // expansion.
4078 SourceLocation SL = SizeOfArg->getExprLoc();
4079 SourceRange DSR = Dest->getSourceRange();
4080 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004081 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004082
4083 if (SM.isMacroArgExpansion(SL)) {
4084 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4085 SL = SM.getSpellingLoc(SL);
4086 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4087 SM.getSpellingLoc(DSR.getEnd()));
4088 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4089 SM.getSpellingLoc(SSR.getEnd()));
4090 }
4091
Anna Zaksd08d9152012-05-30 23:14:52 +00004092 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004093 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004094 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004095 << PointeeTy
4096 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004097 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004098 << SSR);
4099 DiagRuntimeBehavior(SL, SizeOfArg,
4100 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4101 << ActionIdx
4102 << SSR);
4103
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004104 break;
4105 }
4106 }
4107
4108 // Also check for cases where the sizeof argument is the exact same
4109 // type as the memory argument, and where it points to a user-defined
4110 // record type.
4111 if (SizeOfArgTy != QualType()) {
4112 if (PointeeTy->isRecordType() &&
4113 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4114 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4115 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4116 << FnName << SizeOfArgTy << ArgIdx
4117 << PointeeTy << Dest->getSourceRange()
4118 << LenExpr->getSourceRange());
4119 break;
4120 }
Nico Weberc5e73862011-06-14 16:14:58 +00004121 }
4122
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004123 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004124 if (isDynamicClassType(PointeeTy)) {
4125
4126 unsigned OperationType = 0;
4127 // "overwritten" if we're warning about the destination for any call
4128 // but memcmp; otherwise a verb appropriate to the call.
4129 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4130 if (BId == Builtin::BImemcpy)
4131 OperationType = 1;
4132 else if(BId == Builtin::BImemmove)
4133 OperationType = 2;
4134 else if (BId == Builtin::BImemcmp)
4135 OperationType = 3;
4136 }
4137
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004138 DiagRuntimeBehavior(
4139 Dest->getExprLoc(), Dest,
4140 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004141 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004142 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004143 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004144 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004145 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4146 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004147 DiagRuntimeBehavior(
4148 Dest->getExprLoc(), Dest,
4149 PDiag(diag::warn_arc_object_memaccess)
4150 << ArgIdx << FnName << PointeeTy
4151 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004152 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004153 continue;
John McCall31168b02011-06-15 23:02:42 +00004154
4155 DiagRuntimeBehavior(
4156 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004157 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004158 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4159 break;
4160 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004161 }
4162}
4163
Ted Kremenek6865f772011-08-18 20:55:45 +00004164// A little helper routine: ignore addition and subtraction of integer literals.
4165// This intentionally does not ignore all integer constant expressions because
4166// we don't want to remove sizeof().
4167static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4168 Ex = Ex->IgnoreParenCasts();
4169
4170 for (;;) {
4171 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4172 if (!BO || !BO->isAdditiveOp())
4173 break;
4174
4175 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4176 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4177
4178 if (isa<IntegerLiteral>(RHS))
4179 Ex = LHS;
4180 else if (isa<IntegerLiteral>(LHS))
4181 Ex = RHS;
4182 else
4183 break;
4184 }
4185
4186 return Ex;
4187}
4188
Anna Zaks13b08572012-08-08 21:42:23 +00004189static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4190 ASTContext &Context) {
4191 // Only handle constant-sized or VLAs, but not flexible members.
4192 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4193 // Only issue the FIXIT for arrays of size > 1.
4194 if (CAT->getSize().getSExtValue() <= 1)
4195 return false;
4196 } else if (!Ty->isVariableArrayType()) {
4197 return false;
4198 }
4199 return true;
4200}
4201
Ted Kremenek6865f772011-08-18 20:55:45 +00004202// Warn if the user has made the 'size' argument to strlcpy or strlcat
4203// be the size of the source, instead of the destination.
4204void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4205 IdentifierInfo *FnName) {
4206
4207 // Don't crash if the user has the wrong number of arguments
4208 if (Call->getNumArgs() != 3)
4209 return;
4210
4211 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4212 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004213 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004214
4215 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4216 Call->getLocStart(), Call->getRParenLoc()))
4217 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004218
4219 // Look for 'strlcpy(dst, x, sizeof(x))'
4220 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4221 CompareWithSrc = Ex;
4222 else {
4223 // Look for 'strlcpy(dst, x, strlen(x))'
4224 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004225 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4226 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004227 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4228 }
4229 }
4230
4231 if (!CompareWithSrc)
4232 return;
4233
4234 // Determine if the argument to sizeof/strlen is equal to the source
4235 // argument. In principle there's all kinds of things you could do
4236 // here, for instance creating an == expression and evaluating it with
4237 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4238 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4239 if (!SrcArgDRE)
4240 return;
4241
4242 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4243 if (!CompareWithSrcDRE ||
4244 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4245 return;
4246
4247 const Expr *OriginalSizeArg = Call->getArg(2);
4248 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4249 << OriginalSizeArg->getSourceRange() << FnName;
4250
4251 // Output a FIXIT hint if the destination is an array (rather than a
4252 // pointer to an array). This could be enhanced to handle some
4253 // pointers if we know the actual size, like if DstArg is 'array+2'
4254 // we could say 'sizeof(array)-2'.
4255 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004256 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004257 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004258
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004259 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004260 llvm::raw_svector_ostream OS(sizeString);
4261 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004262 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004263 OS << ")";
4264
4265 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4266 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4267 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004268}
4269
Anna Zaks314cd092012-02-01 19:08:57 +00004270/// Check if two expressions refer to the same declaration.
4271static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4272 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4273 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4274 return D1->getDecl() == D2->getDecl();
4275 return false;
4276}
4277
4278static const Expr *getStrlenExprArg(const Expr *E) {
4279 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4280 const FunctionDecl *FD = CE->getDirectCallee();
4281 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004282 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004283 return CE->getArg(0)->IgnoreParenCasts();
4284 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004285 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004286}
4287
4288// Warn on anti-patterns as the 'size' argument to strncat.
4289// The correct size argument should look like following:
4290// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4291void Sema::CheckStrncatArguments(const CallExpr *CE,
4292 IdentifierInfo *FnName) {
4293 // Don't crash if the user has the wrong number of arguments.
4294 if (CE->getNumArgs() < 3)
4295 return;
4296 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4297 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4298 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4299
Nico Weber0e6daef2013-12-26 23:38:39 +00004300 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4301 CE->getRParenLoc()))
4302 return;
4303
Anna Zaks314cd092012-02-01 19:08:57 +00004304 // Identify common expressions, which are wrongly used as the size argument
4305 // to strncat and may lead to buffer overflows.
4306 unsigned PatternType = 0;
4307 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4308 // - sizeof(dst)
4309 if (referToTheSameDecl(SizeOfArg, DstArg))
4310 PatternType = 1;
4311 // - sizeof(src)
4312 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4313 PatternType = 2;
4314 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4315 if (BE->getOpcode() == BO_Sub) {
4316 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4317 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4318 // - sizeof(dst) - strlen(dst)
4319 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4320 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4321 PatternType = 1;
4322 // - sizeof(src) - (anything)
4323 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4324 PatternType = 2;
4325 }
4326 }
4327
4328 if (PatternType == 0)
4329 return;
4330
Anna Zaks5069aa32012-02-03 01:27:37 +00004331 // Generate the diagnostic.
4332 SourceLocation SL = LenArg->getLocStart();
4333 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004334 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004335
4336 // If the function is defined as a builtin macro, do not show macro expansion.
4337 if (SM.isMacroArgExpansion(SL)) {
4338 SL = SM.getSpellingLoc(SL);
4339 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4340 SM.getSpellingLoc(SR.getEnd()));
4341 }
4342
Anna Zaks13b08572012-08-08 21:42:23 +00004343 // Check if the destination is an array (rather than a pointer to an array).
4344 QualType DstTy = DstArg->getType();
4345 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4346 Context);
4347 if (!isKnownSizeArray) {
4348 if (PatternType == 1)
4349 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4350 else
4351 Diag(SL, diag::warn_strncat_src_size) << SR;
4352 return;
4353 }
4354
Anna Zaks314cd092012-02-01 19:08:57 +00004355 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004356 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004357 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004358 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004359
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004360 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004361 llvm::raw_svector_ostream OS(sizeString);
4362 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004363 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004364 OS << ") - ";
4365 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004366 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004367 OS << ") - 1";
4368
Anna Zaks5069aa32012-02-03 01:27:37 +00004369 Diag(SL, diag::note_strncat_wrong_size)
4370 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004371}
4372
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004373//===--- CHECK: Return Address of Stack Variable --------------------------===//
4374
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004375static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4376 Decl *ParentDecl);
4377static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4378 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004379
4380/// CheckReturnStackAddr - Check if a return statement returns the address
4381/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004382static void
4383CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4384 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004385
Craig Topperc3ec1492014-05-26 06:22:03 +00004386 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004387 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004388
4389 // Perform checking for returned stack addresses, local blocks,
4390 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004391 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004392 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004393 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00004394 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004395 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004396 }
4397
Craig Topperc3ec1492014-05-26 06:22:03 +00004398 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004399 return; // Nothing suspicious was found.
4400
4401 SourceLocation diagLoc;
4402 SourceRange diagRange;
4403 if (refVars.empty()) {
4404 diagLoc = stackE->getLocStart();
4405 diagRange = stackE->getSourceRange();
4406 } else {
4407 // We followed through a reference variable. 'stackE' contains the
4408 // problematic expression but we will warn at the return statement pointing
4409 // at the reference variable. We will later display the "trail" of
4410 // reference variables using notes.
4411 diagLoc = refVars[0]->getLocStart();
4412 diagRange = refVars[0]->getSourceRange();
4413 }
4414
4415 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004416 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004417 : diag::warn_ret_stack_addr)
4418 << DR->getDecl()->getDeclName() << diagRange;
4419 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004420 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004421 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004422 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004423 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004424 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4425 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004426 << diagRange;
4427 }
4428
4429 // Display the "trail" of reference variables that we followed until we
4430 // found the problematic expression using notes.
4431 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4432 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4433 // If this var binds to another reference var, show the range of the next
4434 // var, otherwise the var binds to the problematic expression, in which case
4435 // show the range of the expression.
4436 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4437 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004438 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4439 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004440 }
4441}
4442
4443/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4444/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004445/// to a location on the stack, a local block, an address of a label, or a
4446/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004447/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004448/// encounter a subexpression that (1) clearly does not lead to one of the
4449/// above problematic expressions (2) is something we cannot determine leads to
4450/// a problematic expression based on such local checking.
4451///
4452/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4453/// the expression that they point to. Such variables are added to the
4454/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004455///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004456/// EvalAddr processes expressions that are pointers that are used as
4457/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004458/// At the base case of the recursion is a check for the above problematic
4459/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004460///
4461/// This implementation handles:
4462///
4463/// * pointer-to-pointer casts
4464/// * implicit conversions from array references to pointers
4465/// * taking the address of fields
4466/// * arbitrary interplay between "&" and "*" operators
4467/// * pointer arithmetic from an address of a stack variable
4468/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004469static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4470 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004471 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00004472 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004473
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004474 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004475 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004476 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004477 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004478 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004479
Peter Collingbourne91147592011-04-15 00:35:48 +00004480 E = E->IgnoreParens();
4481
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004482 // Our "symbolic interpreter" is just a dispatch off the currently
4483 // viewed AST node. We then recursively traverse the AST by calling
4484 // EvalAddr and EvalVal appropriately.
4485 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004486 case Stmt::DeclRefExprClass: {
4487 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4488
Richard Smith40f08eb2014-01-30 22:05:38 +00004489 // If we leave the immediate function, the lifetime isn't about to end.
4490 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004491 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004492
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004493 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4494 // If this is a reference variable, follow through to the expression that
4495 // it points to.
4496 if (V->hasLocalStorage() &&
4497 V->getType()->isReferenceType() && V->hasInit()) {
4498 // Add the reference variable to the "trail".
4499 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004500 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004501 }
4502
Craig Topperc3ec1492014-05-26 06:22:03 +00004503 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004504 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004505
Chris Lattner934edb22007-12-28 05:31:15 +00004506 case Stmt::UnaryOperatorClass: {
4507 // The only unary operator that make sense to handle here
4508 // is AddrOf. All others don't make sense as pointers.
4509 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004510
John McCalle3027922010-08-25 11:45:40 +00004511 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004512 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004513 else
Craig Topperc3ec1492014-05-26 06:22:03 +00004514 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004515 }
Mike Stump11289f42009-09-09 15:08:12 +00004516
Chris Lattner934edb22007-12-28 05:31:15 +00004517 case Stmt::BinaryOperatorClass: {
4518 // Handle pointer arithmetic. All other binary operators are not valid
4519 // in this context.
4520 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004521 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004522
John McCalle3027922010-08-25 11:45:40 +00004523 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00004524 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004525
Chris Lattner934edb22007-12-28 05:31:15 +00004526 Expr *Base = B->getLHS();
4527
4528 // Determine which argument is the real pointer base. It could be
4529 // the RHS argument instead of the LHS.
4530 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004531
Chris Lattner934edb22007-12-28 05:31:15 +00004532 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004533 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004534 }
Steve Naroff2752a172008-09-10 19:17:48 +00004535
Chris Lattner934edb22007-12-28 05:31:15 +00004536 // For conditional operators we need to see if either the LHS or RHS are
4537 // valid DeclRefExpr*s. If one of them is valid, we return it.
4538 case Stmt::ConditionalOperatorClass: {
4539 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004540
Chris Lattner934edb22007-12-28 05:31:15 +00004541 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004542 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4543 if (Expr *LHSExpr = C->getLHS()) {
4544 // In C++, we can have a throw-expression, which has 'void' type.
4545 if (!LHSExpr->getType()->isVoidType())
4546 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004547 return LHS;
4548 }
Chris Lattner934edb22007-12-28 05:31:15 +00004549
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004550 // In C++, we can have a throw-expression, which has 'void' type.
4551 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004552 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004553
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004554 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004555 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004556
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004557 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004558 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004559 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00004560 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004561
4562 case Stmt::AddrLabelExprClass:
4563 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004564
John McCall28fc7092011-11-10 05:35:25 +00004565 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004566 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4567 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004568
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004569 // For casts, we need to handle conversions from arrays to
4570 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004571 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004572 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004573 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004574 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004575 case Stmt::CXXStaticCastExprClass:
4576 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004577 case Stmt::CXXConstCastExprClass:
4578 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004579 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4580 switch (cast<CastExpr>(E)->getCastKind()) {
4581 case CK_BitCast:
4582 case CK_LValueToRValue:
4583 case CK_NoOp:
4584 case CK_BaseToDerived:
4585 case CK_DerivedToBase:
4586 case CK_UncheckedDerivedToBase:
4587 case CK_Dynamic:
4588 case CK_CPointerToObjCPointerCast:
4589 case CK_BlockPointerToObjCPointerCast:
4590 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004591 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004592
4593 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004594 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004595
4596 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004597 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00004598 }
Chris Lattner934edb22007-12-28 05:31:15 +00004599 }
Mike Stump11289f42009-09-09 15:08:12 +00004600
Douglas Gregorfe314812011-06-21 17:03:29 +00004601 case Stmt::MaterializeTemporaryExprClass:
4602 if (Expr *Result = EvalAddr(
4603 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004604 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004605 return Result;
4606
4607 return E;
4608
Chris Lattner934edb22007-12-28 05:31:15 +00004609 // Everything else: we simply don't reason about them.
4610 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00004611 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00004612 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004613}
Mike Stump11289f42009-09-09 15:08:12 +00004614
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004615
4616/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4617/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004618static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4619 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004620do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004621 // We should only be called for evaluating non-pointer expressions, or
4622 // expressions with a pointer type that are not used as references but instead
4623 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004624
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004625 // Our "symbolic interpreter" is just a dispatch off the currently
4626 // viewed AST node. We then recursively traverse the AST by calling
4627 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004628
4629 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004630 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004631 case Stmt::ImplicitCastExprClass: {
4632 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004633 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004634 E = IE->getSubExpr();
4635 continue;
4636 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004637 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00004638 }
4639
John McCall28fc7092011-11-10 05:35:25 +00004640 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004641 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004642
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004643 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004644 // When we hit a DeclRefExpr we are looking at code that refers to a
4645 // variable's name. If it's not a reference variable we check if it has
4646 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004647 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004648
Richard Smith40f08eb2014-01-30 22:05:38 +00004649 // If we leave the immediate function, the lifetime isn't about to end.
4650 if (DR->refersToEnclosingLocal())
Craig Topperc3ec1492014-05-26 06:22:03 +00004651 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00004652
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004653 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4654 // Check if it refers to itself, e.g. "int& i = i;".
4655 if (V == ParentDecl)
4656 return DR;
4657
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004658 if (V->hasLocalStorage()) {
4659 if (!V->getType()->isReferenceType())
4660 return DR;
4661
4662 // Reference variable, follow through to the expression that
4663 // it points to.
4664 if (V->hasInit()) {
4665 // Add the reference variable to the "trail".
4666 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004667 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004668 }
4669 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004670 }
Mike Stump11289f42009-09-09 15:08:12 +00004671
Craig Topperc3ec1492014-05-26 06:22:03 +00004672 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004673 }
Mike Stump11289f42009-09-09 15:08:12 +00004674
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004675 case Stmt::UnaryOperatorClass: {
4676 // The only unary operator that make sense to handle here
4677 // is Deref. All others don't resolve to a "name." This includes
4678 // handling all sorts of rvalues passed to a unary operator.
4679 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004680
John McCalle3027922010-08-25 11:45:40 +00004681 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004682 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004683
Craig Topperc3ec1492014-05-26 06:22:03 +00004684 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004685 }
Mike Stump11289f42009-09-09 15:08:12 +00004686
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004687 case Stmt::ArraySubscriptExprClass: {
4688 // Array subscripts are potential references to data on the stack. We
4689 // retrieve the DeclRefExpr* for the array variable if it indeed
4690 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004691 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004692 }
Mike Stump11289f42009-09-09 15:08:12 +00004693
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004694 case Stmt::ConditionalOperatorClass: {
4695 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004696 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004697 ConditionalOperator *C = cast<ConditionalOperator>(E);
4698
Anders Carlsson801c5c72007-11-30 19:04:31 +00004699 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004700 if (Expr *LHSExpr = C->getLHS()) {
4701 // In C++, we can have a throw-expression, which has 'void' type.
4702 if (!LHSExpr->getType()->isVoidType())
4703 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4704 return LHS;
4705 }
4706
4707 // In C++, we can have a throw-expression, which has 'void' type.
4708 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004709 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004710
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004711 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004712 }
Mike Stump11289f42009-09-09 15:08:12 +00004713
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004714 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004715 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004716 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004717
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004718 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004719 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00004720 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004721
4722 // Check whether the member type is itself a reference, in which case
4723 // we're not going to refer to the member, but to what the member refers to.
4724 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004726
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004727 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004728 }
Mike Stump11289f42009-09-09 15:08:12 +00004729
Douglas Gregorfe314812011-06-21 17:03:29 +00004730 case Stmt::MaterializeTemporaryExprClass:
4731 if (Expr *Result = EvalVal(
4732 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004733 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004734 return Result;
4735
4736 return E;
4737
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004738 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004739 // Check that we don't return or take the address of a reference to a
4740 // temporary. This is only useful in C++.
4741 if (!E->isTypeDependent() && E->isRValue())
4742 return E;
4743
4744 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00004745 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004746 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004747} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004748}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004749
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004750void
4751Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4752 SourceLocation ReturnLoc,
4753 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004754 const AttrVec *Attrs,
4755 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004756 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4757
4758 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004759 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4760 CheckNonNullExpr(*this, RetValExp))
4761 Diag(ReturnLoc, diag::warn_null_ret)
4762 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004763
4764 // C++11 [basic.stc.dynamic.allocation]p4:
4765 // If an allocation function declared with a non-throwing
4766 // exception-specification fails to allocate storage, it shall return
4767 // a null pointer. Any other allocation function that fails to allocate
4768 // storage shall indicate failure only by throwing an exception [...]
4769 if (FD) {
4770 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4771 if (Op == OO_New || Op == OO_Array_New) {
4772 const FunctionProtoType *Proto
4773 = FD->getType()->castAs<FunctionProtoType>();
4774 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4775 CheckNonNullExpr(*this, RetValExp))
4776 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4777 << FD << getLangOpts().CPlusPlus11;
4778 }
4779 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004780}
4781
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004782//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4783
4784/// Check for comparisons of floating point operands using != and ==.
4785/// Issue a warning if these are no self-comparisons, as they are not likely
4786/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004787void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004788 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4789 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004790
4791 // Special case: check for x == x (which is OK).
4792 // Do not emit warnings for such cases.
4793 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4794 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4795 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004796 return;
Mike Stump11289f42009-09-09 15:08:12 +00004797
4798
Ted Kremenekeda40e22007-11-29 00:59:04 +00004799 // Special case: check for comparisons against literals that can be exactly
4800 // represented by APFloat. In such cases, do not emit a warning. This
4801 // is a heuristic: often comparison against such literals are used to
4802 // detect if a value in a variable has not changed. This clearly can
4803 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004804 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4805 if (FLL->isExact())
4806 return;
4807 } else
4808 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4809 if (FLR->isExact())
4810 return;
Mike Stump11289f42009-09-09 15:08:12 +00004811
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004812 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004813 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004814 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004815 return;
Mike Stump11289f42009-09-09 15:08:12 +00004816
David Blaikie1f4ff152012-07-16 20:47:22 +00004817 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004818 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004819 return;
Mike Stump11289f42009-09-09 15:08:12 +00004820
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004821 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004822 Diag(Loc, diag::warn_floatingpoint_eq)
4823 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004824}
John McCallca01b222010-01-04 23:21:16 +00004825
John McCall70aa5392010-01-06 05:24:50 +00004826//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4827//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004828
John McCall70aa5392010-01-06 05:24:50 +00004829namespace {
John McCallca01b222010-01-04 23:21:16 +00004830
John McCall70aa5392010-01-06 05:24:50 +00004831/// Structure recording the 'active' range of an integer-valued
4832/// expression.
4833struct IntRange {
4834 /// The number of bits active in the int.
4835 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004836
John McCall70aa5392010-01-06 05:24:50 +00004837 /// True if the int is known not to have negative values.
4838 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004839
John McCall70aa5392010-01-06 05:24:50 +00004840 IntRange(unsigned Width, bool NonNegative)
4841 : Width(Width), NonNegative(NonNegative)
4842 {}
John McCallca01b222010-01-04 23:21:16 +00004843
John McCall817d4af2010-11-10 23:38:19 +00004844 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004845 static IntRange forBoolType() {
4846 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004847 }
4848
John McCall817d4af2010-11-10 23:38:19 +00004849 /// Returns the range of an opaque value of the given integral type.
4850 static IntRange forValueOfType(ASTContext &C, QualType T) {
4851 return forValueOfCanonicalType(C,
4852 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004853 }
4854
John McCall817d4af2010-11-10 23:38:19 +00004855 /// Returns the range of an opaque value of a canonical integral type.
4856 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004857 assert(T->isCanonicalUnqualified());
4858
4859 if (const VectorType *VT = dyn_cast<VectorType>(T))
4860 T = VT->getElementType().getTypePtr();
4861 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4862 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004863
David Majnemer6a426652013-06-07 22:07:20 +00004864 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004865 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004866 EnumDecl *Enum = ET->getDecl();
4867 if (!Enum->isCompleteDefinition())
4868 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004869
David Majnemer6a426652013-06-07 22:07:20 +00004870 unsigned NumPositive = Enum->getNumPositiveBits();
4871 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004872
David Majnemer6a426652013-06-07 22:07:20 +00004873 if (NumNegative == 0)
4874 return IntRange(NumPositive, true/*NonNegative*/);
4875 else
4876 return IntRange(std::max(NumPositive + 1, NumNegative),
4877 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004878 }
John McCall70aa5392010-01-06 05:24:50 +00004879
4880 const BuiltinType *BT = cast<BuiltinType>(T);
4881 assert(BT->isInteger());
4882
4883 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4884 }
4885
John McCall817d4af2010-11-10 23:38:19 +00004886 /// Returns the "target" range of a canonical integral type, i.e.
4887 /// the range of values expressible in the type.
4888 ///
4889 /// This matches forValueOfCanonicalType except that enums have the
4890 /// full range of their type, not the range of their enumerators.
4891 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4892 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();
4898 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004899 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004900
4901 const BuiltinType *BT = cast<BuiltinType>(T);
4902 assert(BT->isInteger());
4903
4904 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4905 }
4906
4907 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004908 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004909 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004910 L.NonNegative && R.NonNegative);
4911 }
4912
John McCall817d4af2010-11-10 23:38:19 +00004913 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004914 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004915 return IntRange(std::min(L.Width, R.Width),
4916 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004917 }
4918};
4919
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004920static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4921 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004922 if (value.isSigned() && value.isNegative())
4923 return IntRange(value.getMinSignedBits(), false);
4924
4925 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004926 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004927
4928 // isNonNegative() just checks the sign bit without considering
4929 // signedness.
4930 return IntRange(value.getActiveBits(), true);
4931}
4932
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004933static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4934 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004935 if (result.isInt())
4936 return GetValueRange(C, result.getInt(), MaxWidth);
4937
4938 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004939 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4940 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4941 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4942 R = IntRange::join(R, El);
4943 }
John McCall70aa5392010-01-06 05:24:50 +00004944 return R;
4945 }
4946
4947 if (result.isComplexInt()) {
4948 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4949 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4950 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004951 }
4952
4953 // This can happen with lossless casts to intptr_t of "based" lvalues.
4954 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004955 // FIXME: The only reason we need to pass the type in here is to get
4956 // the sign right on this one case. It would be nice if APValue
4957 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004958 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004959 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004960}
John McCall70aa5392010-01-06 05:24:50 +00004961
Eli Friedmane6d33952013-07-08 20:20:06 +00004962static QualType GetExprType(Expr *E) {
4963 QualType Ty = E->getType();
4964 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4965 Ty = AtomicRHS->getValueType();
4966 return Ty;
4967}
4968
John McCall70aa5392010-01-06 05:24:50 +00004969/// Pseudo-evaluate the given integer expression, estimating the
4970/// range of values it might take.
4971///
4972/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004973static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004974 E = E->IgnoreParens();
4975
4976 // Try a full evaluation first.
4977 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004978 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004979 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004980
4981 // I think we only want to look through implicit casts here; if the
4982 // user has an explicit widening cast, we should treat the value as
4983 // being of the new, wider type.
4984 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004985 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004986 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4987
Eli Friedmane6d33952013-07-08 20:20:06 +00004988 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004989
John McCalle3027922010-08-25 11:45:40 +00004990 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004991
John McCall70aa5392010-01-06 05:24:50 +00004992 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004993 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004994 return OutputTypeRange;
4995
4996 IntRange SubRange
4997 = GetExprRange(C, CE->getSubExpr(),
4998 std::min(MaxWidth, OutputTypeRange.Width));
4999
5000 // Bail out if the subexpr's range is as wide as the cast type.
5001 if (SubRange.Width >= OutputTypeRange.Width)
5002 return OutputTypeRange;
5003
5004 // Otherwise, we take the smaller width, and we're non-negative if
5005 // either the output type or the subexpr is.
5006 return IntRange(SubRange.Width,
5007 SubRange.NonNegative || OutputTypeRange.NonNegative);
5008 }
5009
5010 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5011 // If we can fold the condition, just take that operand.
5012 bool CondResult;
5013 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5014 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5015 : CO->getFalseExpr(),
5016 MaxWidth);
5017
5018 // Otherwise, conservatively merge.
5019 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5020 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5021 return IntRange::join(L, R);
5022 }
5023
5024 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5025 switch (BO->getOpcode()) {
5026
5027 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005028 case BO_LAnd:
5029 case BO_LOr:
5030 case BO_LT:
5031 case BO_GT:
5032 case BO_LE:
5033 case BO_GE:
5034 case BO_EQ:
5035 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005036 return IntRange::forBoolType();
5037
John McCallc3688382011-07-13 06:35:24 +00005038 // The type of the assignments is the type of the LHS, so the RHS
5039 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005040 case BO_MulAssign:
5041 case BO_DivAssign:
5042 case BO_RemAssign:
5043 case BO_AddAssign:
5044 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005045 case BO_XorAssign:
5046 case BO_OrAssign:
5047 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005048 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005049
John McCallc3688382011-07-13 06:35:24 +00005050 // Simple assignments just pass through the RHS, which will have
5051 // been coerced to the LHS type.
5052 case BO_Assign:
5053 // TODO: bitfields?
5054 return GetExprRange(C, BO->getRHS(), MaxWidth);
5055
John McCall70aa5392010-01-06 05:24:50 +00005056 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005057 case BO_PtrMemD:
5058 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005059 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005060
John McCall2ce81ad2010-01-06 22:07:33 +00005061 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005062 case BO_And:
5063 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005064 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5065 GetExprRange(C, BO->getRHS(), MaxWidth));
5066
John McCall70aa5392010-01-06 05:24:50 +00005067 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005068 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005069 // ...except that we want to treat '1 << (blah)' as logically
5070 // positive. It's an important idiom.
5071 if (IntegerLiteral *I
5072 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5073 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005074 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005075 return IntRange(R.Width, /*NonNegative*/ true);
5076 }
5077 }
5078 // fallthrough
5079
John McCalle3027922010-08-25 11:45:40 +00005080 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005081 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005082
John McCall2ce81ad2010-01-06 22:07:33 +00005083 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005084 case BO_Shr:
5085 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005086 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5087
5088 // If the shift amount is a positive constant, drop the width by
5089 // that much.
5090 llvm::APSInt shift;
5091 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5092 shift.isNonNegative()) {
5093 unsigned zext = shift.getZExtValue();
5094 if (zext >= L.Width)
5095 L.Width = (L.NonNegative ? 0 : 1);
5096 else
5097 L.Width -= zext;
5098 }
5099
5100 return L;
5101 }
5102
5103 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005104 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005105 return GetExprRange(C, BO->getRHS(), MaxWidth);
5106
John McCall2ce81ad2010-01-06 22:07:33 +00005107 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005108 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005109 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005110 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005111 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005112
John McCall51431812011-07-14 22:39:48 +00005113 // The width of a division result is mostly determined by the size
5114 // of the LHS.
5115 case BO_Div: {
5116 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005117 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005118 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5119
5120 // If the divisor is constant, use that.
5121 llvm::APSInt divisor;
5122 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5123 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5124 if (log2 >= L.Width)
5125 L.Width = (L.NonNegative ? 0 : 1);
5126 else
5127 L.Width = std::min(L.Width - log2, MaxWidth);
5128 return L;
5129 }
5130
5131 // Otherwise, just use the LHS's width.
5132 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5133 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5134 }
5135
5136 // The result of a remainder can't be larger than the result of
5137 // either side.
5138 case BO_Rem: {
5139 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005140 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005141 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5142 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5143
5144 IntRange meet = IntRange::meet(L, R);
5145 meet.Width = std::min(meet.Width, MaxWidth);
5146 return meet;
5147 }
5148
5149 // The default behavior is okay for these.
5150 case BO_Mul:
5151 case BO_Add:
5152 case BO_Xor:
5153 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005154 break;
5155 }
5156
John McCall51431812011-07-14 22:39:48 +00005157 // The default case is to treat the operation as if it were closed
5158 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005159 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5160 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5161 return IntRange::join(L, R);
5162 }
5163
5164 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5165 switch (UO->getOpcode()) {
5166 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005167 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005168 return IntRange::forBoolType();
5169
5170 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005171 case UO_Deref:
5172 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005173 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005174
5175 default:
5176 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5177 }
5178 }
5179
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005180 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5181 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5182
John McCalld25db7e2013-05-06 21:39:12 +00005183 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005184 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005185 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005186
Eli Friedmane6d33952013-07-08 20:20:06 +00005187 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005188}
John McCall263a48b2010-01-04 23:31:57 +00005189
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005190static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005191 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005192}
5193
John McCall263a48b2010-01-04 23:31:57 +00005194/// Checks whether the given value, which currently has the given
5195/// source semantics, has the same value when coerced through the
5196/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005197static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5198 const llvm::fltSemantics &Src,
5199 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005200 llvm::APFloat truncated = value;
5201
5202 bool ignored;
5203 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5204 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5205
5206 return truncated.bitwiseIsEqual(value);
5207}
5208
5209/// Checks whether the given value, which currently has the given
5210/// source semantics, has the same value when coerced through the
5211/// target semantics.
5212///
5213/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005214static bool IsSameFloatAfterCast(const APValue &value,
5215 const llvm::fltSemantics &Src,
5216 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005217 if (value.isFloat())
5218 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5219
5220 if (value.isVector()) {
5221 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5222 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5223 return false;
5224 return true;
5225 }
5226
5227 assert(value.isComplexFloat());
5228 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5229 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5230}
5231
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005232static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005233
Ted Kremenek6274be42010-09-23 21:43:44 +00005234static bool IsZero(Sema &S, Expr *E) {
5235 // Suppress cases where we are comparing against an enum constant.
5236 if (const DeclRefExpr *DR =
5237 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5238 if (isa<EnumConstantDecl>(DR->getDecl()))
5239 return false;
5240
5241 // Suppress cases where the '0' value is expanded from a macro.
5242 if (E->getLocStart().isMacroID())
5243 return false;
5244
John McCallcc7e5bf2010-05-06 08:58:33 +00005245 llvm::APSInt Value;
5246 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5247}
5248
John McCall2551c1b2010-10-06 00:25:24 +00005249static bool HasEnumType(Expr *E) {
5250 // Strip off implicit integral promotions.
5251 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005252 if (ICE->getCastKind() != CK_IntegralCast &&
5253 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005254 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005255 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005256 }
5257
5258 return E->getType()->isEnumeralType();
5259}
5260
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005261static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005262 // Disable warning in template instantiations.
5263 if (!S.ActiveTemplateInstantiations.empty())
5264 return;
5265
John McCalle3027922010-08-25 11:45:40 +00005266 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005267 if (E->isValueDependent())
5268 return;
5269
John McCalle3027922010-08-25 11:45:40 +00005270 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005271 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005272 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005273 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005274 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005275 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005276 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005277 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005278 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005279 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005280 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005281 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005282 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005283 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005284 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005285 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5286 }
5287}
5288
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005289static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005290 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005291 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005292 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005293 // Disable warning in template instantiations.
5294 if (!S.ActiveTemplateInstantiations.empty())
5295 return;
5296
Richard Trieu0f097742014-04-04 04:13:47 +00005297 // TODO: Investigate using GetExprRange() to get tighter bounds
5298 // on the bit ranges.
5299 QualType OtherT = Other->getType();
5300 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5301 unsigned OtherWidth = OtherRange.Width;
5302
5303 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5304
Richard Trieu560910c2012-11-14 22:50:24 +00005305 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005306 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005307 return;
5308
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005309 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005310 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005311
Richard Trieu0f097742014-04-04 04:13:47 +00005312 // Used for diagnostic printout.
5313 enum {
5314 LiteralConstant = 0,
5315 CXXBoolLiteralTrue,
5316 CXXBoolLiteralFalse
5317 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005318
Richard Trieu0f097742014-04-04 04:13:47 +00005319 if (!OtherIsBooleanType) {
5320 QualType ConstantT = Constant->getType();
5321 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005322
Richard Trieu0f097742014-04-04 04:13:47 +00005323 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5324 return;
5325 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5326 "comparison with non-integer type");
5327
5328 bool ConstantSigned = ConstantT->isSignedIntegerType();
5329 bool CommonSigned = CommonT->isSignedIntegerType();
5330
5331 bool EqualityOnly = false;
5332
5333 if (CommonSigned) {
5334 // The common type is signed, therefore no signed to unsigned conversion.
5335 if (!OtherRange.NonNegative) {
5336 // Check that the constant is representable in type OtherT.
5337 if (ConstantSigned) {
5338 if (OtherWidth >= Value.getMinSignedBits())
5339 return;
5340 } else { // !ConstantSigned
5341 if (OtherWidth >= Value.getActiveBits() + 1)
5342 return;
5343 }
5344 } else { // !OtherSigned
5345 // Check that the constant is representable in type OtherT.
5346 // Negative values are out of range.
5347 if (ConstantSigned) {
5348 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5349 return;
5350 } else { // !ConstantSigned
5351 if (OtherWidth >= Value.getActiveBits())
5352 return;
5353 }
Richard Trieu560910c2012-11-14 22:50:24 +00005354 }
Richard Trieu0f097742014-04-04 04:13:47 +00005355 } else { // !CommonSigned
5356 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005357 if (OtherWidth >= Value.getActiveBits())
5358 return;
Richard Trieu0f097742014-04-04 04:13:47 +00005359 } else if (!OtherRange.NonNegative && !ConstantSigned) {
5360 // Check to see if the constant is representable in OtherT.
5361 if (OtherWidth > Value.getActiveBits())
5362 return;
5363 // Check to see if the constant is equivalent to a negative value
5364 // cast to CommonT.
5365 if (S.Context.getIntWidth(ConstantT) ==
5366 S.Context.getIntWidth(CommonT) &&
5367 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
5368 return;
5369 // The constant value rests between values that OtherT can represent
5370 // after conversion. Relational comparison still works, but equality
5371 // comparisons will be tautological.
5372 EqualityOnly = true;
5373 } else { // OtherSigned && ConstantSigned
5374 assert(0 && "Two signed types converted to unsigned types.");
Richard Trieu560910c2012-11-14 22:50:24 +00005375 }
5376 }
Richard Trieu0f097742014-04-04 04:13:47 +00005377
5378 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5379
5380 if (op == BO_EQ || op == BO_NE) {
5381 IsTrue = op == BO_NE;
5382 } else if (EqualityOnly) {
5383 return;
5384 } else if (RhsConstant) {
5385 if (op == BO_GT || op == BO_GE)
5386 IsTrue = !PositiveConstant;
5387 else // op == BO_LT || op == BO_LE
5388 IsTrue = PositiveConstant;
5389 } else {
5390 if (op == BO_LT || op == BO_LE)
5391 IsTrue = !PositiveConstant;
5392 else // op == BO_GT || op == BO_GE
5393 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005394 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005395 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00005396 // Other isKnownToHaveBooleanValue
5397 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
5398 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
5399 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
5400
5401 static const struct LinkedConditions {
5402 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
5403 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
5404 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
5405 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
5406 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
5407 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
5408
5409 } TruthTable = {
5410 // Constant on LHS. | Constant on RHS. |
5411 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
5412 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
5413 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
5414 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
5415 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
5416 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
5417 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
5418 };
5419
5420 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
5421
5422 enum ConstantValue ConstVal = Zero;
5423 if (Value.isUnsigned() || Value.isNonNegative()) {
5424 if (Value == 0) {
5425 LiteralOrBoolConstant =
5426 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
5427 ConstVal = Zero;
5428 } else if (Value == 1) {
5429 LiteralOrBoolConstant =
5430 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
5431 ConstVal = One;
5432 } else {
5433 LiteralOrBoolConstant = LiteralConstant;
5434 ConstVal = GT_One;
5435 }
5436 } else {
5437 ConstVal = LT_Zero;
5438 }
5439
5440 CompareBoolWithConstantResult CmpRes;
5441
5442 switch (op) {
5443 case BO_LT:
5444 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
5445 break;
5446 case BO_GT:
5447 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
5448 break;
5449 case BO_LE:
5450 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
5451 break;
5452 case BO_GE:
5453 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
5454 break;
5455 case BO_EQ:
5456 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
5457 break;
5458 case BO_NE:
5459 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
5460 break;
5461 default:
5462 CmpRes = Unkwn;
5463 break;
5464 }
5465
5466 if (CmpRes == AFals) {
5467 IsTrue = false;
5468 } else if (CmpRes == ATrue) {
5469 IsTrue = true;
5470 } else {
5471 return;
5472 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005473 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005474
5475 // If this is a comparison to an enum constant, include that
5476 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00005477 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005478 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5479 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5480
5481 SmallString<64> PrettySourceValue;
5482 llvm::raw_svector_ostream OS(PrettySourceValue);
5483 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005484 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005485 else
5486 OS << Value;
5487
Richard Trieu0f097742014-04-04 04:13:47 +00005488 S.DiagRuntimeBehavior(
5489 E->getOperatorLoc(), E,
5490 S.PDiag(diag::warn_out_of_range_compare)
5491 << OS.str() << LiteralOrBoolConstant
5492 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
5493 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005494}
5495
John McCallcc7e5bf2010-05-06 08:58:33 +00005496/// Analyze the operands of the given comparison. Implements the
5497/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005498static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005499 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5500 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005501}
John McCall263a48b2010-01-04 23:31:57 +00005502
John McCallca01b222010-01-04 23:21:16 +00005503/// \brief Implements -Wsign-compare.
5504///
Richard Trieu82402a02011-09-15 21:56:47 +00005505/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005506static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005507 // The type the comparison is being performed in.
5508 QualType T = E->getLHS()->getType();
5509 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5510 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005511 if (E->isValueDependent())
5512 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005513
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005514 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5515 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005516
5517 bool IsComparisonConstant = false;
5518
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005519 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005520 // of 'true' or 'false'.
5521 if (T->isIntegralType(S.Context)) {
5522 llvm::APSInt RHSValue;
5523 bool IsRHSIntegralLiteral =
5524 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5525 llvm::APSInt LHSValue;
5526 bool IsLHSIntegralLiteral =
5527 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5528 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5529 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5530 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5531 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5532 else
5533 IsComparisonConstant =
5534 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005535 } else if (!T->hasUnsignedIntegerRepresentation())
5536 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005537
John McCallcc7e5bf2010-05-06 08:58:33 +00005538 // We don't do anything special if this isn't an unsigned integral
5539 // comparison: we're only interested in integral comparisons, and
5540 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005541 //
5542 // We also don't care about value-dependent expressions or expressions
5543 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005544 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005545 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005546
John McCallcc7e5bf2010-05-06 08:58:33 +00005547 // Check to see if one of the (unmodified) operands is of different
5548 // signedness.
5549 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005550 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5551 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005552 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005553 signedOperand = LHS;
5554 unsignedOperand = RHS;
5555 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5556 signedOperand = RHS;
5557 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005558 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005559 CheckTrivialUnsignedComparison(S, E);
5560 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005561 }
5562
John McCallcc7e5bf2010-05-06 08:58:33 +00005563 // Otherwise, calculate the effective range of the signed operand.
5564 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005565
John McCallcc7e5bf2010-05-06 08:58:33 +00005566 // Go ahead and analyze implicit conversions in the operands. Note
5567 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005568 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5569 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005570
John McCallcc7e5bf2010-05-06 08:58:33 +00005571 // If the signed range is non-negative, -Wsign-compare won't fire,
5572 // but we should still check for comparisons which are always true
5573 // or false.
5574 if (signedRange.NonNegative)
5575 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005576
5577 // For (in)equality comparisons, if the unsigned operand is a
5578 // constant which cannot collide with a overflowed signed operand,
5579 // then reinterpreting the signed operand as unsigned will not
5580 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005581 if (E->isEqualityOp()) {
5582 unsigned comparisonWidth = S.Context.getIntWidth(T);
5583 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005584
John McCallcc7e5bf2010-05-06 08:58:33 +00005585 // We should never be unable to prove that the unsigned operand is
5586 // non-negative.
5587 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5588
5589 if (unsignedRange.Width < comparisonWidth)
5590 return;
5591 }
5592
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005593 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5594 S.PDiag(diag::warn_mixed_sign_comparison)
5595 << LHS->getType() << RHS->getType()
5596 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005597}
5598
John McCall1f425642010-11-11 03:21:53 +00005599/// Analyzes an attempt to assign the given value to a bitfield.
5600///
5601/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005602static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5603 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005604 assert(Bitfield->isBitField());
5605 if (Bitfield->isInvalidDecl())
5606 return false;
5607
John McCalldeebbcf2010-11-11 05:33:51 +00005608 // White-list bool bitfields.
5609 if (Bitfield->getType()->isBooleanType())
5610 return false;
5611
Douglas Gregor789adec2011-02-04 13:09:01 +00005612 // Ignore value- or type-dependent expressions.
5613 if (Bitfield->getBitWidth()->isValueDependent() ||
5614 Bitfield->getBitWidth()->isTypeDependent() ||
5615 Init->isValueDependent() ||
5616 Init->isTypeDependent())
5617 return false;
5618
John McCall1f425642010-11-11 03:21:53 +00005619 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5620
Richard Smith5fab0c92011-12-28 19:48:30 +00005621 llvm::APSInt Value;
5622 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005623 return false;
5624
John McCall1f425642010-11-11 03:21:53 +00005625 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005626 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005627
5628 if (OriginalWidth <= FieldWidth)
5629 return false;
5630
Eli Friedmanc267a322012-01-26 23:11:39 +00005631 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005632 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005633 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005634
Eli Friedmanc267a322012-01-26 23:11:39 +00005635 // Check whether the stored value is equal to the original value.
5636 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005637 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005638 return false;
5639
Eli Friedmanc267a322012-01-26 23:11:39 +00005640 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005641 // therefore don't strictly fit into a signed bitfield of width 1.
5642 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005643 return false;
5644
John McCall1f425642010-11-11 03:21:53 +00005645 std::string PrettyValue = Value.toString(10);
5646 std::string PrettyTrunc = TruncatedValue.toString(10);
5647
5648 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5649 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5650 << Init->getSourceRange();
5651
5652 return true;
5653}
5654
John McCalld2a53122010-11-09 23:24:47 +00005655/// Analyze the given simple or compound assignment for warning-worthy
5656/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005657static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005658 // Just recurse on the LHS.
5659 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5660
5661 // We want to recurse on the RHS as normal unless we're assigning to
5662 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005663 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005664 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005665 E->getOperatorLoc())) {
5666 // Recurse, ignoring any implicit conversions on the RHS.
5667 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5668 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005669 }
5670 }
5671
5672 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5673}
5674
John McCall263a48b2010-01-04 23:31:57 +00005675/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005676static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005677 SourceLocation CContext, unsigned diag,
5678 bool pruneControlFlow = false) {
5679 if (pruneControlFlow) {
5680 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5681 S.PDiag(diag)
5682 << SourceType << T << E->getSourceRange()
5683 << SourceRange(CContext));
5684 return;
5685 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005686 S.Diag(E->getExprLoc(), diag)
5687 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5688}
5689
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005690/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005691static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005692 SourceLocation CContext, unsigned diag,
5693 bool pruneControlFlow = false) {
5694 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005695}
5696
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005697/// Diagnose an implicit cast from a literal expression. Does not warn when the
5698/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005699void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5700 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005701 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005702 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005703 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005704 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5705 T->hasUnsignedIntegerRepresentation());
5706 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005707 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005708 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005709 return;
5710
Eli Friedman07185912013-08-29 23:44:43 +00005711 // FIXME: Force the precision of the source value down so we don't print
5712 // digits which are usually useless (we don't really care here if we
5713 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5714 // would automatically print the shortest representation, but it's a bit
5715 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005716 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005717 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5718 precision = (precision * 59 + 195) / 196;
5719 Value.toString(PrettySourceValue, precision);
5720
David Blaikie9b88cc02012-05-15 17:18:27 +00005721 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005722 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5723 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5724 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005725 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005726
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005727 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005728 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5729 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005730}
5731
John McCall18a2c2c2010-11-09 22:22:12 +00005732std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5733 if (!Range.Width) return "0";
5734
5735 llvm::APSInt ValueInRange = Value;
5736 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005737 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005738 return ValueInRange.toString(10);
5739}
5740
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005741static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5742 if (!isa<ImplicitCastExpr>(Ex))
5743 return false;
5744
5745 Expr *InnerE = Ex->IgnoreParenImpCasts();
5746 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5747 const Type *Source =
5748 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5749 if (Target->isDependentType())
5750 return false;
5751
5752 const BuiltinType *FloatCandidateBT =
5753 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5754 const Type *BoolCandidateType = ToBool ? Target : Source;
5755
5756 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5757 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5758}
5759
5760void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5761 SourceLocation CC) {
5762 unsigned NumArgs = TheCall->getNumArgs();
5763 for (unsigned i = 0; i < NumArgs; ++i) {
5764 Expr *CurrA = TheCall->getArg(i);
5765 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5766 continue;
5767
5768 bool IsSwapped = ((i > 0) &&
5769 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5770 IsSwapped |= ((i < (NumArgs - 1)) &&
5771 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5772 if (IsSwapped) {
5773 // Warn on this floating-point to bool conversion.
5774 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5775 CurrA->getType(), CC,
5776 diag::warn_impcast_floating_point_to_bool);
5777 }
5778 }
5779}
5780
John McCallcc7e5bf2010-05-06 08:58:33 +00005781void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00005782 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005783 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005784
John McCallcc7e5bf2010-05-06 08:58:33 +00005785 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5786 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5787 if (Source == Target) return;
5788 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005789
Chandler Carruthc22845a2011-07-26 05:40:03 +00005790 // If the conversion context location is invalid don't complain. We also
5791 // don't want to emit a warning if the issue occurs from the expansion of
5792 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5793 // delay this check as long as possible. Once we detect we are in that
5794 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005795 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005796 return;
5797
Richard Trieu021baa32011-09-23 20:10:00 +00005798 // Diagnose implicit casts to bool.
5799 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5800 if (isa<StringLiteral>(E))
5801 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005802 // and expressions, for instance, assert(0 && "error here"), are
5803 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005804 return DiagnoseImpCast(S, E, T, CC,
5805 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005806 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5807 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5808 // This covers the literal expressions that evaluate to Objective-C
5809 // objects.
5810 return DiagnoseImpCast(S, E, T, CC,
5811 diag::warn_impcast_objective_c_literal_to_bool);
5812 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005813 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5814 // Warn on pointer to bool conversion that is always true.
5815 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5816 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005817 }
Richard Trieu021baa32011-09-23 20:10:00 +00005818 }
John McCall263a48b2010-01-04 23:31:57 +00005819
5820 // Strip vector types.
5821 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005822 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005823 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005824 return;
John McCallacf0ee52010-10-08 02:01:28 +00005825 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005826 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005827
5828 // If the vector cast is cast between two vectors of the same size, it is
5829 // a bitcast, not a conversion.
5830 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5831 return;
John McCall263a48b2010-01-04 23:31:57 +00005832
5833 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5834 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5835 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00005836 if (auto VecTy = dyn_cast<VectorType>(Target))
5837 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00005838
5839 // Strip complex types.
5840 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005841 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005842 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005843 return;
5844
John McCallacf0ee52010-10-08 02:01:28 +00005845 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005846 }
John McCall263a48b2010-01-04 23:31:57 +00005847
5848 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5849 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5850 }
5851
5852 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5853 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5854
5855 // If the source is floating point...
5856 if (SourceBT && SourceBT->isFloatingPoint()) {
5857 // ...and the target is floating point...
5858 if (TargetBT && TargetBT->isFloatingPoint()) {
5859 // ...then warn if we're dropping FP rank.
5860
5861 // Builtin FP kinds are ordered by increasing FP rank.
5862 if (SourceBT->getKind() > TargetBT->getKind()) {
5863 // Don't warn about float constants that are precisely
5864 // representable in the target type.
5865 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005866 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005867 // Value might be a float, a float vector, or a float complex.
5868 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005869 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5870 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005871 return;
5872 }
5873
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005874 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005875 return;
5876
John McCallacf0ee52010-10-08 02:01:28 +00005877 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005878 }
5879 return;
5880 }
5881
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005882 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005883 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005884 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005885 return;
5886
Chandler Carruth22c7a792011-02-17 11:05:49 +00005887 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005888 // We also want to warn on, e.g., "int i = -1.234"
5889 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5890 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5891 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5892
Chandler Carruth016ef402011-04-10 08:36:24 +00005893 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5894 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005895 } else {
5896 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5897 }
5898 }
John McCall263a48b2010-01-04 23:31:57 +00005899
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005900 // If the target is bool, warn if expr is a function or method call.
5901 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5902 isa<CallExpr>(E)) {
5903 // Check last argument of function call to see if it is an
5904 // implicit cast from a type matching the type the result
5905 // is being cast to.
5906 CallExpr *CEx = cast<CallExpr>(E);
5907 unsigned NumArgs = CEx->getNumArgs();
5908 if (NumArgs > 0) {
5909 Expr *LastA = CEx->getArg(NumArgs - 1);
5910 Expr *InnerE = LastA->IgnoreParenImpCasts();
5911 const Type *InnerType =
5912 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5913 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5914 // Warn on this floating-point to bool conversion
5915 DiagnoseImpCast(S, E, T, CC,
5916 diag::warn_impcast_floating_point_to_bool);
5917 }
5918 }
5919 }
John McCall263a48b2010-01-04 23:31:57 +00005920 return;
5921 }
5922
Richard Trieubeaf3452011-05-29 19:59:02 +00005923 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005924 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005925 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005926 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005927 SourceLocation Loc = E->getSourceRange().getBegin();
5928 if (Loc.isMacroID())
5929 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005930 if (!Loc.isMacroID() || CC.isMacroID())
5931 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5932 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005933 << FixItHint::CreateReplacement(Loc,
5934 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005935 }
5936
David Blaikie9366d2b2012-06-19 21:19:06 +00005937 if (!Source->isIntegerType() || !Target->isIntegerType())
5938 return;
5939
David Blaikie7555b6a2012-05-15 16:56:36 +00005940 // TODO: remove this early return once the false positives for constant->bool
5941 // in templates, macros, etc, are reduced or removed.
5942 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5943 return;
5944
John McCallcc7e5bf2010-05-06 08:58:33 +00005945 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005946 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005947
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005948 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005949 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005950 // TODO: this should happen for bitfield stores, too.
5951 llvm::APSInt Value(32);
5952 if (E->isIntegerConstantExpr(Value, S.Context)) {
5953 if (S.SourceMgr.isInSystemMacro(CC))
5954 return;
5955
John McCall18a2c2c2010-11-09 22:22:12 +00005956 std::string PrettySourceValue = Value.toString(10);
5957 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005958
Ted Kremenek33ba9952011-10-22 02:37:33 +00005959 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5960 S.PDiag(diag::warn_impcast_integer_precision_constant)
5961 << PrettySourceValue << PrettyTargetValue
5962 << E->getType() << T << E->getSourceRange()
5963 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005964 return;
5965 }
5966
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005967 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5968 if (S.SourceMgr.isInSystemMacro(CC))
5969 return;
5970
David Blaikie9455da02012-04-12 22:40:54 +00005971 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005972 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5973 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005974 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005975 }
5976
5977 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5978 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5979 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005980
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005981 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005982 return;
5983
John McCallcc7e5bf2010-05-06 08:58:33 +00005984 unsigned DiagID = diag::warn_impcast_integer_sign;
5985
5986 // Traditionally, gcc has warned about this under -Wsign-compare.
5987 // We also want to warn about it in -Wconversion.
5988 // So if -Wconversion is off, use a completely identical diagnostic
5989 // in the sign-compare group.
5990 // The conditional-checking code will
5991 if (ICContext) {
5992 DiagID = diag::warn_impcast_integer_sign_conditional;
5993 *ICContext = true;
5994 }
5995
John McCallacf0ee52010-10-08 02:01:28 +00005996 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005997 }
5998
Douglas Gregora78f1932011-02-22 02:45:07 +00005999 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006000 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6001 // type, to give us better diagnostics.
6002 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006003 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006004 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6005 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6006 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6007 SourceType = S.Context.getTypeDeclType(Enum);
6008 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6009 }
6010 }
6011
Douglas Gregora78f1932011-02-22 02:45:07 +00006012 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6013 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006014 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6015 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006016 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006017 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006018 return;
6019
Douglas Gregor364f7db2011-03-12 00:14:31 +00006020 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006021 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006022 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006023
John McCall263a48b2010-01-04 23:31:57 +00006024 return;
6025}
6026
David Blaikie18e9ac72012-05-15 21:57:38 +00006027void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6028 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006029
6030void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006031 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006032 E = E->IgnoreParenImpCasts();
6033
6034 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006035 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006036
John McCallacf0ee52010-10-08 02:01:28 +00006037 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006038 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006039 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006040 return;
6041}
6042
David Blaikie18e9ac72012-05-15 21:57:38 +00006043void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6044 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00006045 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006046
6047 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006048 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6049 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006050
6051 // If -Wconversion would have warned about either of the candidates
6052 // for a signedness conversion to the context type...
6053 if (!Suspicious) return;
6054
6055 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006056 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
6057 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006058 return;
6059
John McCallcc7e5bf2010-05-06 08:58:33 +00006060 // ...then check whether it would have warned about either of the
6061 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006062 if (E->getType() == T) return;
6063
6064 Suspicious = false;
6065 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6066 E->getType(), CC, &Suspicious);
6067 if (!Suspicious)
6068 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006069 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006070}
6071
6072/// AnalyzeImplicitConversions - Find and report any interesting
6073/// implicit conversions in the given expression. There are a couple
6074/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006075void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006076 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006077 Expr *E = OrigE->IgnoreParenImpCasts();
6078
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006079 if (E->isTypeDependent() || E->isValueDependent())
6080 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006081
John McCallcc7e5bf2010-05-06 08:58:33 +00006082 // For conditional operators, we analyze the arguments as if they
6083 // were being fed directly into the output.
6084 if (isa<ConditionalOperator>(E)) {
6085 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006086 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006087 return;
6088 }
6089
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006090 // Check implicit argument conversions for function calls.
6091 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6092 CheckImplicitArgumentConversions(S, Call, CC);
6093
John McCallcc7e5bf2010-05-06 08:58:33 +00006094 // Go ahead and check any implicit conversions we might have skipped.
6095 // The non-canonical typecheck is just an optimization;
6096 // CheckImplicitConversion will filter out dead implicit conversions.
6097 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006098 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006099
6100 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006101
6102 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006103 if (POE->getResultExpr())
6104 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006105 }
6106
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006107 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6108 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6109
John McCallcc7e5bf2010-05-06 08:58:33 +00006110 // Skip past explicit casts.
6111 if (isa<ExplicitCastExpr>(E)) {
6112 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006113 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006114 }
6115
John McCalld2a53122010-11-09 23:24:47 +00006116 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6117 // Do a somewhat different check with comparison operators.
6118 if (BO->isComparisonOp())
6119 return AnalyzeComparison(S, BO);
6120
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006121 // And with simple assignments.
6122 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006123 return AnalyzeAssignment(S, BO);
6124 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006125
6126 // These break the otherwise-useful invariant below. Fortunately,
6127 // we don't really need to recurse into them, because any internal
6128 // expressions should have been analyzed already when they were
6129 // built into statements.
6130 if (isa<StmtExpr>(E)) return;
6131
6132 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006133 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006134
6135 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006136 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006137 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006138 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006139 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006140 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006141 if (!ChildExpr)
6142 continue;
6143
Richard Trieu955231d2014-01-25 01:10:35 +00006144 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006145 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006146 // Ignore checking string literals that are in logical and operators.
6147 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006148 continue;
6149 AnalyzeImplicitConversions(S, ChildExpr, CC);
6150 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006151}
6152
6153} // end anonymous namespace
6154
Richard Trieu3bb8b562014-02-26 02:36:06 +00006155enum {
6156 AddressOf,
6157 FunctionPointer,
6158 ArrayPointer
6159};
6160
6161/// \brief Diagnose pointers that are always non-null.
6162/// \param E the expression containing the pointer
6163/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6164/// compared to a null pointer
6165/// \param IsEqual True when the comparison is equal to a null pointer
6166/// \param Range Extra SourceRange to highlight in the diagnostic
6167void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6168 Expr::NullPointerConstantKind NullKind,
6169 bool IsEqual, SourceRange Range) {
6170
6171 // Don't warn inside macros.
6172 if (E->getExprLoc().isMacroID())
6173 return;
6174 E = E->IgnoreImpCasts();
6175
6176 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6177
6178 bool IsAddressOf = false;
6179
6180 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6181 if (UO->getOpcode() != UO_AddrOf)
6182 return;
6183 IsAddressOf = true;
6184 E = UO->getSubExpr();
6185 }
6186
6187 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006188 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006189 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6190 D = R->getDecl();
6191 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6192 D = M->getMemberDecl();
6193 }
6194
6195 // Weak Decls can be null.
6196 if (!D || D->isWeak())
6197 return;
6198
6199 QualType T = D->getType();
6200 const bool IsArray = T->isArrayType();
6201 const bool IsFunction = T->isFunctionType();
6202
6203 if (IsAddressOf) {
6204 // Address of function is used to silence the function warning.
6205 if (IsFunction)
6206 return;
6207 // Address of reference can be null.
6208 if (T->isReferenceType())
6209 return;
6210 }
6211
6212 // Found nothing.
6213 if (!IsAddressOf && !IsFunction && !IsArray)
6214 return;
6215
6216 // Pretty print the expression for the diagnostic.
6217 std::string Str;
6218 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00006219 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00006220
6221 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6222 : diag::warn_impcast_pointer_to_bool;
6223 unsigned DiagType;
6224 if (IsAddressOf)
6225 DiagType = AddressOf;
6226 else if (IsFunction)
6227 DiagType = FunctionPointer;
6228 else if (IsArray)
6229 DiagType = ArrayPointer;
6230 else
6231 llvm_unreachable("Could not determine diagnostic.");
6232 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6233 << Range << IsEqual;
6234
6235 if (!IsFunction)
6236 return;
6237
6238 // Suggest '&' to silence the function warning.
6239 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6240 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6241
6242 // Check to see if '()' fixit should be emitted.
6243 QualType ReturnType;
6244 UnresolvedSet<4> NonTemplateOverloads;
6245 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6246 if (ReturnType.isNull())
6247 return;
6248
6249 if (IsCompare) {
6250 // There are two cases here. If there is null constant, the only suggest
6251 // for a pointer return type. If the null is 0, then suggest if the return
6252 // type is a pointer or an integer type.
6253 if (!ReturnType->isPointerType()) {
6254 if (NullKind == Expr::NPCK_ZeroExpression ||
6255 NullKind == Expr::NPCK_ZeroLiteral) {
6256 if (!ReturnType->isIntegerType())
6257 return;
6258 } else {
6259 return;
6260 }
6261 }
6262 } else { // !IsCompare
6263 // For function to bool, only suggest if the function pointer has bool
6264 // return type.
6265 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6266 return;
6267 }
6268 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00006269 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00006270}
6271
6272
John McCallcc7e5bf2010-05-06 08:58:33 +00006273/// Diagnoses "dangerous" implicit conversions within the given
6274/// expression (which is a full expression). Implements -Wconversion
6275/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006276///
6277/// \param CC the "context" location of the implicit conversion, i.e.
6278/// the most location of the syntactic entity requiring the implicit
6279/// conversion
6280void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006281 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006282 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006283 return;
6284
6285 // Don't diagnose for value- or type-dependent expressions.
6286 if (E->isTypeDependent() || E->isValueDependent())
6287 return;
6288
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006289 // Check for array bounds violations in cases where the check isn't triggered
6290 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6291 // ArraySubscriptExpr is on the RHS of a variable initialization.
6292 CheckArrayAccess(E);
6293
John McCallacf0ee52010-10-08 02:01:28 +00006294 // This is not the right CC for (e.g.) a variable initialization.
6295 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006296}
6297
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006298/// Diagnose when expression is an integer constant expression and its evaluation
6299/// results in integer overflow
6300void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006301 if (isa<BinaryOperator>(E->IgnoreParens()))
6302 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006303}
6304
Richard Smithc406cb72013-01-17 01:17:56 +00006305namespace {
6306/// \brief Visitor for expressions which looks for unsequenced operations on the
6307/// same object.
6308class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006309 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6310
Richard Smithc406cb72013-01-17 01:17:56 +00006311 /// \brief A tree of sequenced regions within an expression. Two regions are
6312 /// unsequenced if one is an ancestor or a descendent of the other. When we
6313 /// finish processing an expression with sequencing, such as a comma
6314 /// expression, we fold its tree nodes into its parent, since they are
6315 /// unsequenced with respect to nodes we will visit later.
6316 class SequenceTree {
6317 struct Value {
6318 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6319 unsigned Parent : 31;
6320 bool Merged : 1;
6321 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006322 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006323
6324 public:
6325 /// \brief A region within an expression which may be sequenced with respect
6326 /// to some other region.
6327 class Seq {
6328 explicit Seq(unsigned N) : Index(N) {}
6329 unsigned Index;
6330 friend class SequenceTree;
6331 public:
6332 Seq() : Index(0) {}
6333 };
6334
6335 SequenceTree() { Values.push_back(Value(0)); }
6336 Seq root() const { return Seq(0); }
6337
6338 /// \brief Create a new sequence of operations, which is an unsequenced
6339 /// subset of \p Parent. This sequence of operations is sequenced with
6340 /// respect to other children of \p Parent.
6341 Seq allocate(Seq Parent) {
6342 Values.push_back(Value(Parent.Index));
6343 return Seq(Values.size() - 1);
6344 }
6345
6346 /// \brief Merge a sequence of operations into its parent.
6347 void merge(Seq S) {
6348 Values[S.Index].Merged = true;
6349 }
6350
6351 /// \brief Determine whether two operations are unsequenced. This operation
6352 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6353 /// should have been merged into its parent as appropriate.
6354 bool isUnsequenced(Seq Cur, Seq Old) {
6355 unsigned C = representative(Cur.Index);
6356 unsigned Target = representative(Old.Index);
6357 while (C >= Target) {
6358 if (C == Target)
6359 return true;
6360 C = Values[C].Parent;
6361 }
6362 return false;
6363 }
6364
6365 private:
6366 /// \brief Pick a representative for a sequence.
6367 unsigned representative(unsigned K) {
6368 if (Values[K].Merged)
6369 // Perform path compression as we go.
6370 return Values[K].Parent = representative(Values[K].Parent);
6371 return K;
6372 }
6373 };
6374
6375 /// An object for which we can track unsequenced uses.
6376 typedef NamedDecl *Object;
6377
6378 /// Different flavors of object usage which we track. We only track the
6379 /// least-sequenced usage of each kind.
6380 enum UsageKind {
6381 /// A read of an object. Multiple unsequenced reads are OK.
6382 UK_Use,
6383 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006384 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006385 UK_ModAsValue,
6386 /// A modification of an object which is not sequenced before the value
6387 /// computation of the expression, such as n++.
6388 UK_ModAsSideEffect,
6389
6390 UK_Count = UK_ModAsSideEffect + 1
6391 };
6392
6393 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00006394 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00006395 Expr *Use;
6396 SequenceTree::Seq Seq;
6397 };
6398
6399 struct UsageInfo {
6400 UsageInfo() : Diagnosed(false) {}
6401 Usage Uses[UK_Count];
6402 /// Have we issued a diagnostic for this variable already?
6403 bool Diagnosed;
6404 };
6405 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6406
6407 Sema &SemaRef;
6408 /// Sequenced regions within the expression.
6409 SequenceTree Tree;
6410 /// Declaration modifications and references which we have seen.
6411 UsageInfoMap UsageMap;
6412 /// The region we are currently within.
6413 SequenceTree::Seq Region;
6414 /// Filled in with declarations which were modified as a side-effect
6415 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006416 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006417 /// Expressions to check later. We defer checking these to reduce
6418 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006419 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006420
6421 /// RAII object wrapping the visitation of a sequenced subexpression of an
6422 /// expression. At the end of this process, the side-effects of the evaluation
6423 /// become sequenced with respect to the value computation of the result, so
6424 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6425 /// UK_ModAsValue.
6426 struct SequencedSubexpression {
6427 SequencedSubexpression(SequenceChecker &Self)
6428 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6429 Self.ModAsSideEffect = &ModAsSideEffect;
6430 }
6431 ~SequencedSubexpression() {
6432 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6433 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6434 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6435 Self.addUsage(U, ModAsSideEffect[I].first,
6436 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6437 }
6438 Self.ModAsSideEffect = OldModAsSideEffect;
6439 }
6440
6441 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006442 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6443 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006444 };
6445
Richard Smith40238f02013-06-20 22:21:56 +00006446 /// RAII object wrapping the visitation of a subexpression which we might
6447 /// choose to evaluate as a constant. If any subexpression is evaluated and
6448 /// found to be non-constant, this allows us to suppress the evaluation of
6449 /// the outer expression.
6450 class EvaluationTracker {
6451 public:
6452 EvaluationTracker(SequenceChecker &Self)
6453 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6454 Self.EvalTracker = this;
6455 }
6456 ~EvaluationTracker() {
6457 Self.EvalTracker = Prev;
6458 if (Prev)
6459 Prev->EvalOK &= EvalOK;
6460 }
6461
6462 bool evaluate(const Expr *E, bool &Result) {
6463 if (!EvalOK || E->isValueDependent())
6464 return false;
6465 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6466 return EvalOK;
6467 }
6468
6469 private:
6470 SequenceChecker &Self;
6471 EvaluationTracker *Prev;
6472 bool EvalOK;
6473 } *EvalTracker;
6474
Richard Smithc406cb72013-01-17 01:17:56 +00006475 /// \brief Find the object which is produced by the specified expression,
6476 /// if any.
6477 Object getObject(Expr *E, bool Mod) const {
6478 E = E->IgnoreParenCasts();
6479 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6480 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6481 return getObject(UO->getSubExpr(), Mod);
6482 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6483 if (BO->getOpcode() == BO_Comma)
6484 return getObject(BO->getRHS(), Mod);
6485 if (Mod && BO->isAssignmentOp())
6486 return getObject(BO->getLHS(), Mod);
6487 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6488 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6489 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6490 return ME->getMemberDecl();
6491 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6492 // FIXME: If this is a reference, map through to its value.
6493 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00006494 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00006495 }
6496
6497 /// \brief Note that an object was modified or used by an expression.
6498 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6499 Usage &U = UI.Uses[UK];
6500 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6501 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6502 ModAsSideEffect->push_back(std::make_pair(O, U));
6503 U.Use = Ref;
6504 U.Seq = Region;
6505 }
6506 }
6507 /// \brief Check whether a modification or use conflicts with a prior usage.
6508 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6509 bool IsModMod) {
6510 if (UI.Diagnosed)
6511 return;
6512
6513 const Usage &U = UI.Uses[OtherKind];
6514 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6515 return;
6516
6517 Expr *Mod = U.Use;
6518 Expr *ModOrUse = Ref;
6519 if (OtherKind == UK_Use)
6520 std::swap(Mod, ModOrUse);
6521
6522 SemaRef.Diag(Mod->getExprLoc(),
6523 IsModMod ? diag::warn_unsequenced_mod_mod
6524 : diag::warn_unsequenced_mod_use)
6525 << O << SourceRange(ModOrUse->getExprLoc());
6526 UI.Diagnosed = true;
6527 }
6528
6529 void notePreUse(Object O, Expr *Use) {
6530 UsageInfo &U = UsageMap[O];
6531 // Uses conflict with other modifications.
6532 checkUsage(O, U, Use, UK_ModAsValue, false);
6533 }
6534 void notePostUse(Object O, Expr *Use) {
6535 UsageInfo &U = UsageMap[O];
6536 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6537 addUsage(U, O, Use, UK_Use);
6538 }
6539
6540 void notePreMod(Object O, Expr *Mod) {
6541 UsageInfo &U = UsageMap[O];
6542 // Modifications conflict with other modifications and with uses.
6543 checkUsage(O, U, Mod, UK_ModAsValue, true);
6544 checkUsage(O, U, Mod, UK_Use, false);
6545 }
6546 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6547 UsageInfo &U = UsageMap[O];
6548 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6549 addUsage(U, O, Use, UK);
6550 }
6551
6552public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006553 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00006554 : Base(S.Context), SemaRef(S), Region(Tree.root()),
6555 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006556 Visit(E);
6557 }
6558
6559 void VisitStmt(Stmt *S) {
6560 // Skip all statements which aren't expressions for now.
6561 }
6562
6563 void VisitExpr(Expr *E) {
6564 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006565 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006566 }
6567
6568 void VisitCastExpr(CastExpr *E) {
6569 Object O = Object();
6570 if (E->getCastKind() == CK_LValueToRValue)
6571 O = getObject(E->getSubExpr(), false);
6572
6573 if (O)
6574 notePreUse(O, E);
6575 VisitExpr(E);
6576 if (O)
6577 notePostUse(O, E);
6578 }
6579
6580 void VisitBinComma(BinaryOperator *BO) {
6581 // C++11 [expr.comma]p1:
6582 // Every value computation and side effect associated with the left
6583 // expression is sequenced before every value computation and side
6584 // effect associated with the right expression.
6585 SequenceTree::Seq LHS = Tree.allocate(Region);
6586 SequenceTree::Seq RHS = Tree.allocate(Region);
6587 SequenceTree::Seq OldRegion = Region;
6588
6589 {
6590 SequencedSubexpression SeqLHS(*this);
6591 Region = LHS;
6592 Visit(BO->getLHS());
6593 }
6594
6595 Region = RHS;
6596 Visit(BO->getRHS());
6597
6598 Region = OldRegion;
6599
6600 // Forget that LHS and RHS are sequenced. They are both unsequenced
6601 // with respect to other stuff.
6602 Tree.merge(LHS);
6603 Tree.merge(RHS);
6604 }
6605
6606 void VisitBinAssign(BinaryOperator *BO) {
6607 // The modification is sequenced after the value computation of the LHS
6608 // and RHS, so check it before inspecting the operands and update the
6609 // map afterwards.
6610 Object O = getObject(BO->getLHS(), true);
6611 if (!O)
6612 return VisitExpr(BO);
6613
6614 notePreMod(O, BO);
6615
6616 // C++11 [expr.ass]p7:
6617 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6618 // only once.
6619 //
6620 // Therefore, for a compound assignment operator, O is considered used
6621 // everywhere except within the evaluation of E1 itself.
6622 if (isa<CompoundAssignOperator>(BO))
6623 notePreUse(O, BO);
6624
6625 Visit(BO->getLHS());
6626
6627 if (isa<CompoundAssignOperator>(BO))
6628 notePostUse(O, BO);
6629
6630 Visit(BO->getRHS());
6631
Richard Smith83e37bee2013-06-26 23:16:51 +00006632 // C++11 [expr.ass]p1:
6633 // the assignment is sequenced [...] before the value computation of the
6634 // assignment expression.
6635 // C11 6.5.16/3 has no such rule.
6636 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6637 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006638 }
6639 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6640 VisitBinAssign(CAO);
6641 }
6642
6643 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6644 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6645 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6646 Object O = getObject(UO->getSubExpr(), true);
6647 if (!O)
6648 return VisitExpr(UO);
6649
6650 notePreMod(O, UO);
6651 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006652 // C++11 [expr.pre.incr]p1:
6653 // the expression ++x is equivalent to x+=1
6654 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6655 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006656 }
6657
6658 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6659 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6660 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6661 Object O = getObject(UO->getSubExpr(), true);
6662 if (!O)
6663 return VisitExpr(UO);
6664
6665 notePreMod(O, UO);
6666 Visit(UO->getSubExpr());
6667 notePostMod(O, UO, UK_ModAsSideEffect);
6668 }
6669
6670 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6671 void VisitBinLOr(BinaryOperator *BO) {
6672 // The side-effects of the LHS of an '&&' are sequenced before the
6673 // value computation of the RHS, and hence before the value computation
6674 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6675 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006676 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006677 {
6678 SequencedSubexpression Sequenced(*this);
6679 Visit(BO->getLHS());
6680 }
6681
6682 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006683 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006684 if (!Result)
6685 Visit(BO->getRHS());
6686 } else {
6687 // Check for unsequenced operations in the RHS, treating it as an
6688 // entirely separate evaluation.
6689 //
6690 // FIXME: If there are operations in the RHS which are unsequenced
6691 // with respect to operations outside the RHS, and those operations
6692 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006693 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006694 }
Richard Smithc406cb72013-01-17 01:17:56 +00006695 }
6696 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006697 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006698 {
6699 SequencedSubexpression Sequenced(*this);
6700 Visit(BO->getLHS());
6701 }
6702
6703 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006704 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006705 if (Result)
6706 Visit(BO->getRHS());
6707 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006708 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006709 }
Richard Smithc406cb72013-01-17 01:17:56 +00006710 }
6711
6712 // Only visit the condition, unless we can be sure which subexpression will
6713 // be chosen.
6714 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006715 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006716 {
6717 SequencedSubexpression Sequenced(*this);
6718 Visit(CO->getCond());
6719 }
Richard Smithc406cb72013-01-17 01:17:56 +00006720
6721 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006722 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006723 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006724 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006725 WorkList.push_back(CO->getTrueExpr());
6726 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006727 }
Richard Smithc406cb72013-01-17 01:17:56 +00006728 }
6729
Richard Smithe3dbfe02013-06-30 10:40:20 +00006730 void VisitCallExpr(CallExpr *CE) {
6731 // C++11 [intro.execution]p15:
6732 // When calling a function [...], every value computation and side effect
6733 // associated with any argument expression, or with the postfix expression
6734 // designating the called function, is sequenced before execution of every
6735 // expression or statement in the body of the function [and thus before
6736 // the value computation of its result].
6737 SequencedSubexpression Sequenced(*this);
6738 Base::VisitCallExpr(CE);
6739
6740 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6741 }
6742
Richard Smithc406cb72013-01-17 01:17:56 +00006743 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006744 // This is a call, so all subexpressions are sequenced before the result.
6745 SequencedSubexpression Sequenced(*this);
6746
Richard Smithc406cb72013-01-17 01:17:56 +00006747 if (!CCE->isListInitialization())
6748 return VisitExpr(CCE);
6749
6750 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006751 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006752 SequenceTree::Seq Parent = Region;
6753 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6754 E = CCE->arg_end();
6755 I != E; ++I) {
6756 Region = Tree.allocate(Parent);
6757 Elts.push_back(Region);
6758 Visit(*I);
6759 }
6760
6761 // Forget that the initializers are sequenced.
6762 Region = Parent;
6763 for (unsigned I = 0; I < Elts.size(); ++I)
6764 Tree.merge(Elts[I]);
6765 }
6766
6767 void VisitInitListExpr(InitListExpr *ILE) {
6768 if (!SemaRef.getLangOpts().CPlusPlus11)
6769 return VisitExpr(ILE);
6770
6771 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006772 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006773 SequenceTree::Seq Parent = Region;
6774 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6775 Expr *E = ILE->getInit(I);
6776 if (!E) continue;
6777 Region = Tree.allocate(Parent);
6778 Elts.push_back(Region);
6779 Visit(E);
6780 }
6781
6782 // Forget that the initializers are sequenced.
6783 Region = Parent;
6784 for (unsigned I = 0; I < Elts.size(); ++I)
6785 Tree.merge(Elts[I]);
6786 }
6787};
6788}
6789
6790void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006791 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006792 WorkList.push_back(E);
6793 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006794 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006795 SequenceChecker(*this, Item, WorkList);
6796 }
Richard Smithc406cb72013-01-17 01:17:56 +00006797}
6798
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006799void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6800 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006801 CheckImplicitConversions(E, CheckLoc);
6802 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006803 if (!IsConstexpr && !E->isValueDependent())
6804 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006805}
6806
John McCall1f425642010-11-11 03:21:53 +00006807void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6808 FieldDecl *BitField,
6809 Expr *Init) {
6810 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6811}
6812
Mike Stump0c2ec772010-01-21 03:59:47 +00006813/// CheckParmsForFunctionDef - Check that the parameters of the given
6814/// function are appropriate for the definition of a function. This
6815/// takes care of any checks that cannot be performed on the
6816/// declaration itself, e.g., that the types of each of the function
6817/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006818bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6819 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006820 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006821 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006822 for (; P != PEnd; ++P) {
6823 ParmVarDecl *Param = *P;
6824
Mike Stump0c2ec772010-01-21 03:59:47 +00006825 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6826 // function declarator that is part of a function definition of
6827 // that function shall not have incomplete type.
6828 //
6829 // This is also C++ [dcl.fct]p6.
6830 if (!Param->isInvalidDecl() &&
6831 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006832 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006833 Param->setInvalidDecl();
6834 HasInvalidParm = true;
6835 }
6836
6837 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6838 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006839 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00006840 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006841 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006842 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006843 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006844
6845 // C99 6.7.5.3p12:
6846 // If the function declarator is not part of a definition of that
6847 // function, parameters may have incomplete type and may use the [*]
6848 // notation in their sequences of declarator specifiers to specify
6849 // variable length array types.
6850 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006851 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006852 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006853 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006854 // information is added for it.
6855 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006856 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006857 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006858 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006859 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006860
6861 // MSVC destroys objects passed by value in the callee. Therefore a
6862 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006863 // object's destructor. However, we don't perform any direct access check
6864 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006865 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6866 .getCXXABI()
6867 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006868 if (!Param->isInvalidDecl()) {
6869 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6870 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6871 if (!ClassDecl->isInvalidDecl() &&
6872 !ClassDecl->hasIrrelevantDestructor() &&
6873 !ClassDecl->isDependentContext()) {
6874 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6875 MarkFunctionReferenced(Param->getLocation(), Destructor);
6876 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6877 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006878 }
6879 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006880 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006881 }
6882
6883 return HasInvalidParm;
6884}
John McCall2b5c1b22010-08-12 21:44:57 +00006885
6886/// CheckCastAlign - Implements -Wcast-align, which warns when a
6887/// pointer cast increases the alignment requirements.
6888void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6889 // This is actually a lot of work to potentially be doing on every
6890 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006891 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6892 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006893 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006894 return;
6895
6896 // Ignore dependent types.
6897 if (T->isDependentType() || Op->getType()->isDependentType())
6898 return;
6899
6900 // Require that the destination be a pointer type.
6901 const PointerType *DestPtr = T->getAs<PointerType>();
6902 if (!DestPtr) return;
6903
6904 // If the destination has alignment 1, we're done.
6905 QualType DestPointee = DestPtr->getPointeeType();
6906 if (DestPointee->isIncompleteType()) return;
6907 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6908 if (DestAlign.isOne()) return;
6909
6910 // Require that the source be a pointer type.
6911 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6912 if (!SrcPtr) return;
6913 QualType SrcPointee = SrcPtr->getPointeeType();
6914
6915 // Whitelist casts from cv void*. We already implicitly
6916 // whitelisted casts to cv void*, since they have alignment 1.
6917 // Also whitelist casts involving incomplete types, which implicitly
6918 // includes 'void'.
6919 if (SrcPointee->isIncompleteType()) return;
6920
6921 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6922 if (SrcAlign >= DestAlign) return;
6923
6924 Diag(TRange.getBegin(), diag::warn_cast_align)
6925 << Op->getType() << T
6926 << static_cast<unsigned>(SrcAlign.getQuantity())
6927 << static_cast<unsigned>(DestAlign.getQuantity())
6928 << TRange << Op->getSourceRange();
6929}
6930
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006931static const Type* getElementType(const Expr *BaseExpr) {
6932 const Type* EltType = BaseExpr->getType().getTypePtr();
6933 if (EltType->isAnyPointerType())
6934 return EltType->getPointeeType().getTypePtr();
6935 else if (EltType->isArrayType())
6936 return EltType->getBaseElementTypeUnsafe();
6937 return EltType;
6938}
6939
Chandler Carruth28389f02011-08-05 09:10:50 +00006940/// \brief Check whether this array fits the idiom of a size-one tail padded
6941/// array member of a struct.
6942///
6943/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6944/// commonly used to emulate flexible arrays in C89 code.
6945static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6946 const NamedDecl *ND) {
6947 if (Size != 1 || !ND) return false;
6948
6949 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6950 if (!FD) return false;
6951
6952 // Don't consider sizes resulting from macro expansions or template argument
6953 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006954
6955 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006956 while (TInfo) {
6957 TypeLoc TL = TInfo->getTypeLoc();
6958 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006959 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6960 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006961 TInfo = TDL->getTypeSourceInfo();
6962 continue;
6963 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006964 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6965 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006966 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6967 return false;
6968 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006969 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006970 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006971
6972 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006973 if (!RD) return false;
6974 if (RD->isUnion()) return false;
6975 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6976 if (!CRD->isStandardLayout()) return false;
6977 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006978
Benjamin Kramer8c543672011-08-06 03:04:42 +00006979 // See if this is the last field decl in the record.
6980 const Decl *D = FD;
6981 while ((D = D->getNextDeclInContext()))
6982 if (isa<FieldDecl>(D))
6983 return false;
6984 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006985}
6986
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006987void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006988 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006989 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006990 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006991 if (IndexExpr->isValueDependent())
6992 return;
6993
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006994 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006995 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006996 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006997 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006998 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006999 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007000
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007001 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007002 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007003 return;
Richard Smith13f67182011-12-16 19:31:14 +00007004 if (IndexNegated)
7005 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007006
Craig Topperc3ec1492014-05-26 06:22:03 +00007007 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007008 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7009 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007010 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007011 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007012
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007013 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007014 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007015 if (!size.isStrictlyPositive())
7016 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007017
7018 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007019 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007020 // Make sure we're comparing apples to apples when comparing index to size
7021 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7022 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007023 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007024 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007025 if (ptrarith_typesize != array_typesize) {
7026 // There's a cast to a different size type involved
7027 uint64_t ratio = array_typesize / ptrarith_typesize;
7028 // TODO: Be smarter about handling cases where array_typesize is not a
7029 // multiple of ptrarith_typesize
7030 if (ptrarith_typesize * ratio == array_typesize)
7031 size *= llvm::APInt(size.getBitWidth(), ratio);
7032 }
7033 }
7034
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007035 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007036 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007037 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007038 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007039
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007040 // For array subscripting the index must be less than size, but for pointer
7041 // arithmetic also allow the index (offset) to be equal to size since
7042 // computing the next address after the end of the array is legal and
7043 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007044 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007045 return;
7046
7047 // Also don't warn for arrays of size 1 which are members of some
7048 // structure. These are often used to approximate flexible arrays in C89
7049 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007050 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007051 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007052
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007053 // Suppress the warning if the subscript expression (as identified by the
7054 // ']' location) and the index expression are both from macro expansions
7055 // within a system header.
7056 if (ASE) {
7057 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7058 ASE->getRBracketLoc());
7059 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7060 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7061 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007062 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007063 return;
7064 }
7065 }
7066
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007067 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007068 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007069 DiagID = diag::warn_array_index_exceeds_bounds;
7070
7071 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7072 PDiag(DiagID) << index.toString(10, true)
7073 << size.toString(10, true)
7074 << (unsigned)size.getLimitedValue(~0U)
7075 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007076 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007077 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007078 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007079 DiagID = diag::warn_ptr_arith_precedes_bounds;
7080 if (index.isNegative()) index = -index;
7081 }
7082
7083 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7084 PDiag(DiagID) << index.toString(10, true)
7085 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007086 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007087
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007088 if (!ND) {
7089 // Try harder to find a NamedDecl to point at in the note.
7090 while (const ArraySubscriptExpr *ASE =
7091 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7092 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7093 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7094 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7095 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7096 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7097 }
7098
Chandler Carruth1af88f12011-02-17 21:10:52 +00007099 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007100 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7101 PDiag(diag::note_array_index_out_of_bounds)
7102 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007103}
7104
Ted Kremenekdf26df72011-03-01 18:41:00 +00007105void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007106 int AllowOnePastEnd = 0;
7107 while (expr) {
7108 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007109 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007110 case Stmt::ArraySubscriptExprClass: {
7111 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007112 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007113 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007114 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007115 }
7116 case Stmt::UnaryOperatorClass: {
7117 // Only unwrap the * and & unary operators
7118 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7119 expr = UO->getSubExpr();
7120 switch (UO->getOpcode()) {
7121 case UO_AddrOf:
7122 AllowOnePastEnd++;
7123 break;
7124 case UO_Deref:
7125 AllowOnePastEnd--;
7126 break;
7127 default:
7128 return;
7129 }
7130 break;
7131 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007132 case Stmt::ConditionalOperatorClass: {
7133 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7134 if (const Expr *lhs = cond->getLHS())
7135 CheckArrayAccess(lhs);
7136 if (const Expr *rhs = cond->getRHS())
7137 CheckArrayAccess(rhs);
7138 return;
7139 }
7140 default:
7141 return;
7142 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007143 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007144}
John McCall31168b02011-06-15 23:02:42 +00007145
7146//===--- CHECK: Objective-C retain cycles ----------------------------------//
7147
7148namespace {
7149 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007150 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007151 VarDecl *Variable;
7152 SourceRange Range;
7153 SourceLocation Loc;
7154 bool Indirect;
7155
7156 void setLocsFrom(Expr *e) {
7157 Loc = e->getExprLoc();
7158 Range = e->getSourceRange();
7159 }
7160 };
7161}
7162
7163/// Consider whether capturing the given variable can possibly lead to
7164/// a retain cycle.
7165static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007166 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007167 // lifetime. In MRR, it's captured strongly if the variable is
7168 // __block and has an appropriate type.
7169 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7170 return false;
7171
7172 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007173 if (ref)
7174 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007175 return true;
7176}
7177
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007178static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007179 while (true) {
7180 e = e->IgnoreParens();
7181 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7182 switch (cast->getCastKind()) {
7183 case CK_BitCast:
7184 case CK_LValueBitCast:
7185 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007186 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007187 e = cast->getSubExpr();
7188 continue;
7189
John McCall31168b02011-06-15 23:02:42 +00007190 default:
7191 return false;
7192 }
7193 }
7194
7195 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7196 ObjCIvarDecl *ivar = ref->getDecl();
7197 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7198 return false;
7199
7200 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007201 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007202 return false;
7203
7204 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7205 owner.Indirect = true;
7206 return true;
7207 }
7208
7209 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7210 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7211 if (!var) return false;
7212 return considerVariable(var, ref, owner);
7213 }
7214
John McCall31168b02011-06-15 23:02:42 +00007215 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7216 if (member->isArrow()) return false;
7217
7218 // Don't count this as an indirect ownership.
7219 e = member->getBase();
7220 continue;
7221 }
7222
John McCallfe96e0b2011-11-06 09:01:30 +00007223 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7224 // Only pay attention to pseudo-objects on property references.
7225 ObjCPropertyRefExpr *pre
7226 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7227 ->IgnoreParens());
7228 if (!pre) return false;
7229 if (pre->isImplicitProperty()) return false;
7230 ObjCPropertyDecl *property = pre->getExplicitProperty();
7231 if (!property->isRetaining() &&
7232 !(property->getPropertyIvarDecl() &&
7233 property->getPropertyIvarDecl()->getType()
7234 .getObjCLifetime() == Qualifiers::OCL_Strong))
7235 return false;
7236
7237 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007238 if (pre->isSuperReceiver()) {
7239 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7240 if (!owner.Variable)
7241 return false;
7242 owner.Loc = pre->getLocation();
7243 owner.Range = pre->getSourceRange();
7244 return true;
7245 }
John McCallfe96e0b2011-11-06 09:01:30 +00007246 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7247 ->getSourceExpr());
7248 continue;
7249 }
7250
John McCall31168b02011-06-15 23:02:42 +00007251 // Array ivars?
7252
7253 return false;
7254 }
7255}
7256
7257namespace {
7258 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7259 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7260 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Craig Topperc3ec1492014-05-26 06:22:03 +00007261 Variable(variable), Capturer(nullptr) {}
John McCall31168b02011-06-15 23:02:42 +00007262
7263 VarDecl *Variable;
7264 Expr *Capturer;
7265
7266 void VisitDeclRefExpr(DeclRefExpr *ref) {
7267 if (ref->getDecl() == Variable && !Capturer)
7268 Capturer = ref;
7269 }
7270
John McCall31168b02011-06-15 23:02:42 +00007271 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7272 if (Capturer) return;
7273 Visit(ref->getBase());
7274 if (Capturer && ref->isFreeIvar())
7275 Capturer = ref;
7276 }
7277
7278 void VisitBlockExpr(BlockExpr *block) {
7279 // Look inside nested blocks
7280 if (block->getBlockDecl()->capturesVariable(Variable))
7281 Visit(block->getBlockDecl()->getBody());
7282 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007283
7284 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7285 if (Capturer) return;
7286 if (OVE->getSourceExpr())
7287 Visit(OVE->getSourceExpr());
7288 }
John McCall31168b02011-06-15 23:02:42 +00007289 };
7290}
7291
7292/// Check whether the given argument is a block which captures a
7293/// variable.
7294static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7295 assert(owner.Variable && owner.Loc.isValid());
7296
7297 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007298
7299 // Look through [^{...} copy] and Block_copy(^{...}).
7300 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7301 Selector Cmd = ME->getSelector();
7302 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7303 e = ME->getInstanceReceiver();
7304 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00007305 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00007306 e = e->IgnoreParenCasts();
7307 }
7308 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7309 if (CE->getNumArgs() == 1) {
7310 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007311 if (Fn) {
7312 const IdentifierInfo *FnI = Fn->getIdentifier();
7313 if (FnI && FnI->isStr("_Block_copy")) {
7314 e = CE->getArg(0)->IgnoreParenCasts();
7315 }
7316 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007317 }
7318 }
7319
John McCall31168b02011-06-15 23:02:42 +00007320 BlockExpr *block = dyn_cast<BlockExpr>(e);
7321 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00007322 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00007323
7324 FindCaptureVisitor visitor(S.Context, owner.Variable);
7325 visitor.Visit(block->getBlockDecl()->getBody());
7326 return visitor.Capturer;
7327}
7328
7329static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7330 RetainCycleOwner &owner) {
7331 assert(capturer);
7332 assert(owner.Variable && owner.Loc.isValid());
7333
7334 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7335 << owner.Variable << capturer->getSourceRange();
7336 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7337 << owner.Indirect << owner.Range;
7338}
7339
7340/// Check for a keyword selector that starts with the word 'add' or
7341/// 'set'.
7342static bool isSetterLikeSelector(Selector sel) {
7343 if (sel.isUnarySelector()) return false;
7344
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007345 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007346 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007347 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007348 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007349 else if (str.startswith("add")) {
7350 // Specially whitelist 'addOperationWithBlock:'.
7351 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7352 return false;
7353 str = str.substr(3);
7354 }
John McCall31168b02011-06-15 23:02:42 +00007355 else
7356 return false;
7357
7358 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007359 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007360}
7361
7362/// Check a message send to see if it's likely to cause a retain cycle.
7363void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7364 // Only check instance methods whose selector looks like a setter.
7365 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7366 return;
7367
7368 // Try to find a variable that the receiver is strongly owned by.
7369 RetainCycleOwner owner;
7370 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007371 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007372 return;
7373 } else {
7374 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7375 owner.Variable = getCurMethodDecl()->getSelfDecl();
7376 owner.Loc = msg->getSuperLoc();
7377 owner.Range = msg->getSuperLoc();
7378 }
7379
7380 // Check whether the receiver is captured by any of the arguments.
7381 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7382 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7383 return diagnoseRetainCycle(*this, capturer, owner);
7384}
7385
7386/// Check a property assign to see if it's likely to cause a retain cycle.
7387void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7388 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007389 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007390 return;
7391
7392 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7393 diagnoseRetainCycle(*this, capturer, owner);
7394}
7395
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007396void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7397 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00007398 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007399 return;
7400
7401 // Because we don't have an expression for the variable, we have to set the
7402 // location explicitly here.
7403 Owner.Loc = Var->getLocation();
7404 Owner.Range = Var->getSourceRange();
7405
7406 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7407 diagnoseRetainCycle(*this, Capturer, Owner);
7408}
7409
Ted Kremenek9304da92012-12-21 08:04:28 +00007410static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7411 Expr *RHS, bool isProperty) {
7412 // Check if RHS is an Objective-C object literal, which also can get
7413 // immediately zapped in a weak reference. Note that we explicitly
7414 // allow ObjCStringLiterals, since those are designed to never really die.
7415 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007416
Ted Kremenek64873352012-12-21 22:46:35 +00007417 // This enum needs to match with the 'select' in
7418 // warn_objc_arc_literal_assign (off-by-1).
7419 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7420 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7421 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007422
7423 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007424 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007425 << (isProperty ? 0 : 1)
7426 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007427
7428 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007429}
7430
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007431static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7432 Qualifiers::ObjCLifetime LT,
7433 Expr *RHS, bool isProperty) {
7434 // Strip off any implicit cast added to get to the one ARC-specific.
7435 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7436 if (cast->getCastKind() == CK_ARCConsumeObject) {
7437 S.Diag(Loc, diag::warn_arc_retained_assign)
7438 << (LT == Qualifiers::OCL_ExplicitNone)
7439 << (isProperty ? 0 : 1)
7440 << RHS->getSourceRange();
7441 return true;
7442 }
7443 RHS = cast->getSubExpr();
7444 }
7445
7446 if (LT == Qualifiers::OCL_Weak &&
7447 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7448 return true;
7449
7450 return false;
7451}
7452
Ted Kremenekb36234d2012-12-21 08:04:20 +00007453bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7454 QualType LHS, Expr *RHS) {
7455 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7456
7457 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7458 return false;
7459
7460 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7461 return true;
7462
7463 return false;
7464}
7465
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007466void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7467 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007468 QualType LHSType;
7469 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007470 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007471 ObjCPropertyRefExpr *PRE
7472 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7473 if (PRE && !PRE->isImplicitProperty()) {
7474 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7475 if (PD)
7476 LHSType = PD->getType();
7477 }
7478
7479 if (LHSType.isNull())
7480 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007481
7482 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7483
7484 if (LT == Qualifiers::OCL_Weak) {
7485 DiagnosticsEngine::Level Level =
7486 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7487 if (Level != DiagnosticsEngine::Ignored)
7488 getCurFunction()->markSafeWeakUse(LHS);
7489 }
7490
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007491 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7492 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007493
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007494 // FIXME. Check for other life times.
7495 if (LT != Qualifiers::OCL_None)
7496 return;
7497
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007498 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007499 if (PRE->isImplicitProperty())
7500 return;
7501 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7502 if (!PD)
7503 return;
7504
Bill Wendling44426052012-12-20 19:22:21 +00007505 unsigned Attributes = PD->getPropertyAttributes();
7506 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007507 // when 'assign' attribute was not explicitly specified
7508 // by user, ignore it and rely on property type itself
7509 // for lifetime info.
7510 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7511 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7512 LHSType->isObjCRetainableType())
7513 return;
7514
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007515 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007516 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007517 Diag(Loc, diag::warn_arc_retained_property_assign)
7518 << RHS->getSourceRange();
7519 return;
7520 }
7521 RHS = cast->getSubExpr();
7522 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007523 }
Bill Wendling44426052012-12-20 19:22:21 +00007524 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007525 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7526 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007527 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007528 }
7529}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007530
7531//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7532
7533namespace {
7534bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7535 SourceLocation StmtLoc,
7536 const NullStmt *Body) {
7537 // Do not warn if the body is a macro that expands to nothing, e.g:
7538 //
7539 // #define CALL(x)
7540 // if (condition)
7541 // CALL(0);
7542 //
7543 if (Body->hasLeadingEmptyMacro())
7544 return false;
7545
7546 // Get line numbers of statement and body.
7547 bool StmtLineInvalid;
7548 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7549 &StmtLineInvalid);
7550 if (StmtLineInvalid)
7551 return false;
7552
7553 bool BodyLineInvalid;
7554 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7555 &BodyLineInvalid);
7556 if (BodyLineInvalid)
7557 return false;
7558
7559 // Warn if null statement and body are on the same line.
7560 if (StmtLine != BodyLine)
7561 return false;
7562
7563 return true;
7564}
7565} // Unnamed namespace
7566
7567void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7568 const Stmt *Body,
7569 unsigned DiagID) {
7570 // Since this is a syntactic check, don't emit diagnostic for template
7571 // instantiations, this just adds noise.
7572 if (CurrentInstantiationScope)
7573 return;
7574
7575 // The body should be a null statement.
7576 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7577 if (!NBody)
7578 return;
7579
7580 // Do the usual checks.
7581 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7582 return;
7583
7584 Diag(NBody->getSemiLoc(), DiagID);
7585 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7586}
7587
7588void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7589 const Stmt *PossibleBody) {
7590 assert(!CurrentInstantiationScope); // Ensured by caller
7591
7592 SourceLocation StmtLoc;
7593 const Stmt *Body;
7594 unsigned DiagID;
7595 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7596 StmtLoc = FS->getRParenLoc();
7597 Body = FS->getBody();
7598 DiagID = diag::warn_empty_for_body;
7599 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7600 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7601 Body = WS->getBody();
7602 DiagID = diag::warn_empty_while_body;
7603 } else
7604 return; // Neither `for' nor `while'.
7605
7606 // The body should be a null statement.
7607 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7608 if (!NBody)
7609 return;
7610
7611 // Skip expensive checks if diagnostic is disabled.
7612 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7613 DiagnosticsEngine::Ignored)
7614 return;
7615
7616 // Do the usual checks.
7617 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7618 return;
7619
7620 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7621 // noise level low, emit diagnostics only if for/while is followed by a
7622 // CompoundStmt, e.g.:
7623 // for (int i = 0; i < n; i++);
7624 // {
7625 // a(i);
7626 // }
7627 // or if for/while is followed by a statement with more indentation
7628 // than for/while itself:
7629 // for (int i = 0; i < n; i++);
7630 // a(i);
7631 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7632 if (!ProbableTypo) {
7633 bool BodyColInvalid;
7634 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7635 PossibleBody->getLocStart(),
7636 &BodyColInvalid);
7637 if (BodyColInvalid)
7638 return;
7639
7640 bool StmtColInvalid;
7641 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7642 S->getLocStart(),
7643 &StmtColInvalid);
7644 if (StmtColInvalid)
7645 return;
7646
7647 if (BodyCol > StmtCol)
7648 ProbableTypo = true;
7649 }
7650
7651 if (ProbableTypo) {
7652 Diag(NBody->getSemiLoc(), DiagID);
7653 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7654 }
7655}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007656
7657//===--- Layout compatibility ----------------------------------------------//
7658
7659namespace {
7660
7661bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7662
7663/// \brief Check if two enumeration types are layout-compatible.
7664bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7665 // C++11 [dcl.enum] p8:
7666 // Two enumeration types are layout-compatible if they have the same
7667 // underlying type.
7668 return ED1->isComplete() && ED2->isComplete() &&
7669 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7670}
7671
7672/// \brief Check if two fields are layout-compatible.
7673bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7674 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7675 return false;
7676
7677 if (Field1->isBitField() != Field2->isBitField())
7678 return false;
7679
7680 if (Field1->isBitField()) {
7681 // Make sure that the bit-fields are the same length.
7682 unsigned Bits1 = Field1->getBitWidthValue(C);
7683 unsigned Bits2 = Field2->getBitWidthValue(C);
7684
7685 if (Bits1 != Bits2)
7686 return false;
7687 }
7688
7689 return true;
7690}
7691
7692/// \brief Check if two standard-layout structs are layout-compatible.
7693/// (C++11 [class.mem] p17)
7694bool isLayoutCompatibleStruct(ASTContext &C,
7695 RecordDecl *RD1,
7696 RecordDecl *RD2) {
7697 // If both records are C++ classes, check that base classes match.
7698 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7699 // If one of records is a CXXRecordDecl we are in C++ mode,
7700 // thus the other one is a CXXRecordDecl, too.
7701 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7702 // Check number of base classes.
7703 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7704 return false;
7705
7706 // Check the base classes.
7707 for (CXXRecordDecl::base_class_const_iterator
7708 Base1 = D1CXX->bases_begin(),
7709 BaseEnd1 = D1CXX->bases_end(),
7710 Base2 = D2CXX->bases_begin();
7711 Base1 != BaseEnd1;
7712 ++Base1, ++Base2) {
7713 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7714 return false;
7715 }
7716 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7717 // If only RD2 is a C++ class, it should have zero base classes.
7718 if (D2CXX->getNumBases() > 0)
7719 return false;
7720 }
7721
7722 // Check the fields.
7723 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7724 Field2End = RD2->field_end(),
7725 Field1 = RD1->field_begin(),
7726 Field1End = RD1->field_end();
7727 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7728 if (!isLayoutCompatible(C, *Field1, *Field2))
7729 return false;
7730 }
7731 if (Field1 != Field1End || Field2 != Field2End)
7732 return false;
7733
7734 return true;
7735}
7736
7737/// \brief Check if two standard-layout unions are layout-compatible.
7738/// (C++11 [class.mem] p18)
7739bool isLayoutCompatibleUnion(ASTContext &C,
7740 RecordDecl *RD1,
7741 RecordDecl *RD2) {
7742 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007743 for (auto *Field2 : RD2->fields())
7744 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007745
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007746 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007747 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7748 I = UnmatchedFields.begin(),
7749 E = UnmatchedFields.end();
7750
7751 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007752 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007753 bool Result = UnmatchedFields.erase(*I);
7754 (void) Result;
7755 assert(Result);
7756 break;
7757 }
7758 }
7759 if (I == E)
7760 return false;
7761 }
7762
7763 return UnmatchedFields.empty();
7764}
7765
7766bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7767 if (RD1->isUnion() != RD2->isUnion())
7768 return false;
7769
7770 if (RD1->isUnion())
7771 return isLayoutCompatibleUnion(C, RD1, RD2);
7772 else
7773 return isLayoutCompatibleStruct(C, RD1, RD2);
7774}
7775
7776/// \brief Check if two types are layout-compatible in C++11 sense.
7777bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7778 if (T1.isNull() || T2.isNull())
7779 return false;
7780
7781 // C++11 [basic.types] p11:
7782 // If two types T1 and T2 are the same type, then T1 and T2 are
7783 // layout-compatible types.
7784 if (C.hasSameType(T1, T2))
7785 return true;
7786
7787 T1 = T1.getCanonicalType().getUnqualifiedType();
7788 T2 = T2.getCanonicalType().getUnqualifiedType();
7789
7790 const Type::TypeClass TC1 = T1->getTypeClass();
7791 const Type::TypeClass TC2 = T2->getTypeClass();
7792
7793 if (TC1 != TC2)
7794 return false;
7795
7796 if (TC1 == Type::Enum) {
7797 return isLayoutCompatible(C,
7798 cast<EnumType>(T1)->getDecl(),
7799 cast<EnumType>(T2)->getDecl());
7800 } else if (TC1 == Type::Record) {
7801 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7802 return false;
7803
7804 return isLayoutCompatible(C,
7805 cast<RecordType>(T1)->getDecl(),
7806 cast<RecordType>(T2)->getDecl());
7807 }
7808
7809 return false;
7810}
7811}
7812
7813//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7814
7815namespace {
7816/// \brief Given a type tag expression find the type tag itself.
7817///
7818/// \param TypeExpr Type tag expression, as it appears in user's code.
7819///
7820/// \param VD Declaration of an identifier that appears in a type tag.
7821///
7822/// \param MagicValue Type tag magic value.
7823bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7824 const ValueDecl **VD, uint64_t *MagicValue) {
7825 while(true) {
7826 if (!TypeExpr)
7827 return false;
7828
7829 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7830
7831 switch (TypeExpr->getStmtClass()) {
7832 case Stmt::UnaryOperatorClass: {
7833 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7834 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7835 TypeExpr = UO->getSubExpr();
7836 continue;
7837 }
7838 return false;
7839 }
7840
7841 case Stmt::DeclRefExprClass: {
7842 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7843 *VD = DRE->getDecl();
7844 return true;
7845 }
7846
7847 case Stmt::IntegerLiteralClass: {
7848 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7849 llvm::APInt MagicValueAPInt = IL->getValue();
7850 if (MagicValueAPInt.getActiveBits() <= 64) {
7851 *MagicValue = MagicValueAPInt.getZExtValue();
7852 return true;
7853 } else
7854 return false;
7855 }
7856
7857 case Stmt::BinaryConditionalOperatorClass:
7858 case Stmt::ConditionalOperatorClass: {
7859 const AbstractConditionalOperator *ACO =
7860 cast<AbstractConditionalOperator>(TypeExpr);
7861 bool Result;
7862 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7863 if (Result)
7864 TypeExpr = ACO->getTrueExpr();
7865 else
7866 TypeExpr = ACO->getFalseExpr();
7867 continue;
7868 }
7869 return false;
7870 }
7871
7872 case Stmt::BinaryOperatorClass: {
7873 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7874 if (BO->getOpcode() == BO_Comma) {
7875 TypeExpr = BO->getRHS();
7876 continue;
7877 }
7878 return false;
7879 }
7880
7881 default:
7882 return false;
7883 }
7884 }
7885}
7886
7887/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7888///
7889/// \param TypeExpr Expression that specifies a type tag.
7890///
7891/// \param MagicValues Registered magic values.
7892///
7893/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7894/// kind.
7895///
7896/// \param TypeInfo Information about the corresponding C type.
7897///
7898/// \returns true if the corresponding C type was found.
7899bool GetMatchingCType(
7900 const IdentifierInfo *ArgumentKind,
7901 const Expr *TypeExpr, const ASTContext &Ctx,
7902 const llvm::DenseMap<Sema::TypeTagMagicValue,
7903 Sema::TypeTagData> *MagicValues,
7904 bool &FoundWrongKind,
7905 Sema::TypeTagData &TypeInfo) {
7906 FoundWrongKind = false;
7907
7908 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00007909 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007910
7911 uint64_t MagicValue;
7912
7913 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7914 return false;
7915
7916 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007917 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007918 if (I->getArgumentKind() != ArgumentKind) {
7919 FoundWrongKind = true;
7920 return false;
7921 }
7922 TypeInfo.Type = I->getMatchingCType();
7923 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7924 TypeInfo.MustBeNull = I->getMustBeNull();
7925 return true;
7926 }
7927 return false;
7928 }
7929
7930 if (!MagicValues)
7931 return false;
7932
7933 llvm::DenseMap<Sema::TypeTagMagicValue,
7934 Sema::TypeTagData>::const_iterator I =
7935 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7936 if (I == MagicValues->end())
7937 return false;
7938
7939 TypeInfo = I->second;
7940 return true;
7941}
7942} // unnamed namespace
7943
7944void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7945 uint64_t MagicValue, QualType Type,
7946 bool LayoutCompatible,
7947 bool MustBeNull) {
7948 if (!TypeTagForDatatypeMagicValues)
7949 TypeTagForDatatypeMagicValues.reset(
7950 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7951
7952 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7953 (*TypeTagForDatatypeMagicValues)[Magic] =
7954 TypeTagData(Type, LayoutCompatible, MustBeNull);
7955}
7956
7957namespace {
7958bool IsSameCharType(QualType T1, QualType T2) {
7959 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7960 if (!BT1)
7961 return false;
7962
7963 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7964 if (!BT2)
7965 return false;
7966
7967 BuiltinType::Kind T1Kind = BT1->getKind();
7968 BuiltinType::Kind T2Kind = BT2->getKind();
7969
7970 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7971 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7972 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7973 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7974}
7975} // unnamed namespace
7976
7977void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7978 const Expr * const *ExprArgs) {
7979 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7980 bool IsPointerAttr = Attr->getIsPointer();
7981
7982 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7983 bool FoundWrongKind;
7984 TypeTagData TypeInfo;
7985 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7986 TypeTagForDatatypeMagicValues.get(),
7987 FoundWrongKind, TypeInfo)) {
7988 if (FoundWrongKind)
7989 Diag(TypeTagExpr->getExprLoc(),
7990 diag::warn_type_tag_for_datatype_wrong_kind)
7991 << TypeTagExpr->getSourceRange();
7992 return;
7993 }
7994
7995 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7996 if (IsPointerAttr) {
7997 // Skip implicit cast of pointer to `void *' (as a function argument).
7998 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007999 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00008000 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008001 ArgumentExpr = ICE->getSubExpr();
8002 }
8003 QualType ArgumentType = ArgumentExpr->getType();
8004
8005 // Passing a `void*' pointer shouldn't trigger a warning.
8006 if (IsPointerAttr && ArgumentType->isVoidPointerType())
8007 return;
8008
8009 if (TypeInfo.MustBeNull) {
8010 // Type tag with matching void type requires a null pointer.
8011 if (!ArgumentExpr->isNullPointerConstant(Context,
8012 Expr::NPC_ValueDependentIsNotNull)) {
8013 Diag(ArgumentExpr->getExprLoc(),
8014 diag::warn_type_safety_null_pointer_required)
8015 << ArgumentKind->getName()
8016 << ArgumentExpr->getSourceRange()
8017 << TypeTagExpr->getSourceRange();
8018 }
8019 return;
8020 }
8021
8022 QualType RequiredType = TypeInfo.Type;
8023 if (IsPointerAttr)
8024 RequiredType = Context.getPointerType(RequiredType);
8025
8026 bool mismatch = false;
8027 if (!TypeInfo.LayoutCompatible) {
8028 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8029
8030 // C++11 [basic.fundamental] p1:
8031 // Plain char, signed char, and unsigned char are three distinct types.
8032 //
8033 // But we treat plain `char' as equivalent to `signed char' or `unsigned
8034 // char' depending on the current char signedness mode.
8035 if (mismatch)
8036 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8037 RequiredType->getPointeeType())) ||
8038 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8039 mismatch = false;
8040 } else
8041 if (IsPointerAttr)
8042 mismatch = !isLayoutCompatible(Context,
8043 ArgumentType->getPointeeType(),
8044 RequiredType->getPointeeType());
8045 else
8046 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8047
8048 if (mismatch)
8049 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00008050 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008051 << TypeInfo.LayoutCompatible << RequiredType
8052 << ArgumentExpr->getSourceRange()
8053 << TypeTagExpr->getSourceRange();
8054}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00008055