blob: c66da3a656903754b89a33591987014ed5890dd7 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000046 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +000047 PP.getLangOpts(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
104 ExprResult Arg(S.Owned(TheCall->getArg(0)));
105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
109 TheCall->setArg(0, Arg.take());
110 TheCall->setType(ResultType);
111 return false;
112}
113
John McCalldadc5752010-08-24 06:29:42 +0000114ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000116 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000117
Chris Lattner3be167f2010-10-01 23:23:24 +0000118 // Find out if any arguments are required to be integer constant expressions.
119 unsigned ICEArguments = 0;
120 ASTContext::GetBuiltinTypeError Error;
121 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122 if (Error != ASTContext::GE_None)
123 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
124
125 // If any arguments are required to be ICE's, check and diagnose.
126 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127 // Skip arguments not required to be ICE's.
128 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130 llvm::APSInt Result;
131 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132 return true;
133 ICEArguments &= ~(1 << ArgNo);
134 }
135
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000136 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000137 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000138 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000140 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000141 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000142 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000143 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000144 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinVAStart(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000148 case Builtin::BI__builtin_isgreater:
149 case Builtin::BI__builtin_isgreaterequal:
150 case Builtin::BI__builtin_isless:
151 case Builtin::BI__builtin_islessequal:
152 case Builtin::BI__builtin_islessgreater:
153 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000154 if (SemaBuiltinUnorderedCompare(TheCall))
155 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000156 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000157 case Builtin::BI__builtin_fpclassify:
158 if (SemaBuiltinFPClassification(TheCall, 6))
159 return ExprError();
160 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000161 case Builtin::BI__builtin_isfinite:
162 case Builtin::BI__builtin_isinf:
163 case Builtin::BI__builtin_isinf_sign:
164 case Builtin::BI__builtin_isnan:
165 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000166 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000167 return ExprError();
168 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000170 return SemaBuiltinShuffleVector(TheCall);
171 // TheCall will be freed by the smart pointer here, but that's fine, since
172 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000173 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000174 if (SemaBuiltinPrefetch(TheCall))
175 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000176 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000177 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000178 if (SemaBuiltinObjectSize(TheCall))
179 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000180 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000181 case Builtin::BI__builtin_longjmp:
182 if (SemaBuiltinLongjmp(TheCall))
183 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000184 break;
John McCallbebede42011-02-26 05:39:39 +0000185
186 case Builtin::BI__builtin_classify_type:
187 if (checkArgCount(*this, TheCall, 1)) return true;
188 TheCall->setType(Context.IntTy);
189 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000190 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000191 if (checkArgCount(*this, TheCall, 1)) return true;
192 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000193 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000194 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000195 case Builtin::BI__sync_fetch_and_add_1:
196 case Builtin::BI__sync_fetch_and_add_2:
197 case Builtin::BI__sync_fetch_and_add_4:
198 case Builtin::BI__sync_fetch_and_add_8:
199 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000200 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000201 case Builtin::BI__sync_fetch_and_sub_1:
202 case Builtin::BI__sync_fetch_and_sub_2:
203 case Builtin::BI__sync_fetch_and_sub_4:
204 case Builtin::BI__sync_fetch_and_sub_8:
205 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000206 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000207 case Builtin::BI__sync_fetch_and_or_1:
208 case Builtin::BI__sync_fetch_and_or_2:
209 case Builtin::BI__sync_fetch_and_or_4:
210 case Builtin::BI__sync_fetch_and_or_8:
211 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000212 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000213 case Builtin::BI__sync_fetch_and_and_1:
214 case Builtin::BI__sync_fetch_and_and_2:
215 case Builtin::BI__sync_fetch_and_and_4:
216 case Builtin::BI__sync_fetch_and_and_8:
217 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000218 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000219 case Builtin::BI__sync_fetch_and_xor_1:
220 case Builtin::BI__sync_fetch_and_xor_2:
221 case Builtin::BI__sync_fetch_and_xor_4:
222 case Builtin::BI__sync_fetch_and_xor_8:
223 case Builtin::BI__sync_fetch_and_xor_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000224 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000225 case Builtin::BI__sync_add_and_fetch_1:
226 case Builtin::BI__sync_add_and_fetch_2:
227 case Builtin::BI__sync_add_and_fetch_4:
228 case Builtin::BI__sync_add_and_fetch_8:
229 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000230 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000231 case Builtin::BI__sync_sub_and_fetch_1:
232 case Builtin::BI__sync_sub_and_fetch_2:
233 case Builtin::BI__sync_sub_and_fetch_4:
234 case Builtin::BI__sync_sub_and_fetch_8:
235 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000236 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000237 case Builtin::BI__sync_and_and_fetch_1:
238 case Builtin::BI__sync_and_and_fetch_2:
239 case Builtin::BI__sync_and_and_fetch_4:
240 case Builtin::BI__sync_and_and_fetch_8:
241 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000242 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000243 case Builtin::BI__sync_or_and_fetch_1:
244 case Builtin::BI__sync_or_and_fetch_2:
245 case Builtin::BI__sync_or_and_fetch_4:
246 case Builtin::BI__sync_or_and_fetch_8:
247 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000248 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000249 case Builtin::BI__sync_xor_and_fetch_1:
250 case Builtin::BI__sync_xor_and_fetch_2:
251 case Builtin::BI__sync_xor_and_fetch_4:
252 case Builtin::BI__sync_xor_and_fetch_8:
253 case Builtin::BI__sync_xor_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000254 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000255 case Builtin::BI__sync_val_compare_and_swap_1:
256 case Builtin::BI__sync_val_compare_and_swap_2:
257 case Builtin::BI__sync_val_compare_and_swap_4:
258 case Builtin::BI__sync_val_compare_and_swap_8:
259 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000260 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000261 case Builtin::BI__sync_bool_compare_and_swap_1:
262 case Builtin::BI__sync_bool_compare_and_swap_2:
263 case Builtin::BI__sync_bool_compare_and_swap_4:
264 case Builtin::BI__sync_bool_compare_and_swap_8:
265 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000266 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000267 case Builtin::BI__sync_lock_test_and_set_1:
268 case Builtin::BI__sync_lock_test_and_set_2:
269 case Builtin::BI__sync_lock_test_and_set_4:
270 case Builtin::BI__sync_lock_test_and_set_8:
271 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000272 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000273 case Builtin::BI__sync_lock_release_1:
274 case Builtin::BI__sync_lock_release_2:
275 case Builtin::BI__sync_lock_release_4:
276 case Builtin::BI__sync_lock_release_8:
277 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000278 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000279 case Builtin::BI__sync_swap_1:
280 case Builtin::BI__sync_swap_2:
281 case Builtin::BI__sync_swap_4:
282 case Builtin::BI__sync_swap_8:
283 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000284 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000288 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000289#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000290 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000291 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000292 return ExprError();
293 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000294 case Builtin::BI__builtin_addressof:
295 if (SemaBuiltinAddressof(*this, TheCall))
296 return ExprError();
297 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000298 }
299
300 // Since the target specific builtins for each arch overlap, only check those
301 // of the arch we are compiling for.
302 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000303 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000304 case llvm::Triple::arm:
305 case llvm::Triple::thumb:
306 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307 return ExprError();
308 break;
Tim Northover2fe823a2013-08-01 09:23:19 +0000309 case llvm::Triple::aarch64:
Christian Pirker9b019ae2014-02-25 13:51:00 +0000310 case llvm::Triple::aarch64_be:
Tim Northover2fe823a2013-08-01 09:23:19 +0000311 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
312 return ExprError();
313 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000314 case llvm::Triple::mips:
315 case llvm::Triple::mipsel:
316 case llvm::Triple::mips64:
317 case llvm::Triple::mips64el:
318 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
319 return ExprError();
320 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000321 case llvm::Triple::x86:
322 case llvm::Triple::x86_64:
323 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
324 return ExprError();
325 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000326 default:
327 break;
328 }
329 }
330
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000331 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000332}
333
Nate Begeman91e1fea2010-06-14 05:21:25 +0000334// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000335static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000336 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000337 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000338 switch (Type.getEltType()) {
339 case NeonTypeFlags::Int8:
340 case NeonTypeFlags::Poly8:
341 return shift ? 7 : (8 << IsQuad) - 1;
342 case NeonTypeFlags::Int16:
343 case NeonTypeFlags::Poly16:
344 return shift ? 15 : (4 << IsQuad) - 1;
345 case NeonTypeFlags::Int32:
346 return shift ? 31 : (2 << IsQuad) - 1;
347 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000348 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000349 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000350 case NeonTypeFlags::Poly128:
351 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000352 case NeonTypeFlags::Float16:
353 assert(!shift && "cannot shift float types!");
354 return (4 << IsQuad) - 1;
355 case NeonTypeFlags::Float32:
356 assert(!shift && "cannot shift float types!");
357 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000358 case NeonTypeFlags::Float64:
359 assert(!shift && "cannot shift float types!");
360 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000361 }
David Blaikie8a40f702012-01-17 06:56:22 +0000362 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000363}
364
Bob Wilsone4d77232011-11-08 05:04:11 +0000365/// getNeonEltType - Return the QualType corresponding to the elements of
366/// the vector type specified by the NeonTypeFlags. This is used to check
367/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000368static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
369 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000370 switch (Flags.getEltType()) {
371 case NeonTypeFlags::Int8:
372 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
373 case NeonTypeFlags::Int16:
374 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
375 case NeonTypeFlags::Int32:
376 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
377 case NeonTypeFlags::Int64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000378 if (IsAArch64)
379 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
380 else
381 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
382 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000383 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000384 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000385 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000386 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
387 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000388 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000389 case NeonTypeFlags::Poly128:
390 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000391 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000392 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000393 case NeonTypeFlags::Float32:
394 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000395 case NeonTypeFlags::Float64:
396 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000397 }
David Blaikie8a40f702012-01-17 06:56:22 +0000398 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000399}
400
Tim Northover12670412014-02-19 10:37:05 +0000401bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000402 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000403 uint64_t mask = 0;
404 unsigned TV = 0;
405 int PtrArgNum = -1;
406 bool HasConstPtr = false;
407 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000408#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000409#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000410#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000411 }
412
413 // For NEON intrinsics which are overloaded on vector element type, validate
414 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000415 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000416 if (mask) {
417 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
418 return true;
419
420 TV = Result.getLimitedValue(64);
421 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
422 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000423 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000424 }
425
426 if (PtrArgNum >= 0) {
427 // Check that pointer arguments have the specified type.
428 Expr *Arg = TheCall->getArg(PtrArgNum);
429 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
430 Arg = ICE->getSubExpr();
431 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
432 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000433
434 bool IsAArch64 =
435 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::aarch64;
436 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, IsAArch64);
Tim Northover2fe823a2013-08-01 09:23:19 +0000437 if (HasConstPtr)
438 EltTy = EltTy.withConst();
439 QualType LHSTy = Context.getPointerType(EltTy);
440 AssignConvertType ConvTy;
441 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
442 if (RHS.isInvalid())
443 return true;
444 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
445 RHS.get(), AA_Assigning))
446 return true;
447 }
448
449 // For NEON intrinsics which take an immediate value as part of the
450 // instruction, range check them here.
451 unsigned i = 0, l = 0, u = 0;
452 switch (BuiltinID) {
453 default:
454 return false;
Tim Northover12670412014-02-19 10:37:05 +0000455#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000456#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000457#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000458 }
459 ;
460
461 // We can't check the value of a dependent argument.
462 if (TheCall->getArg(i)->isTypeDependent() ||
463 TheCall->getArg(i)->isValueDependent())
464 return false;
465
466 // Check that the immediate argument is actually a constant.
467 if (SemaBuiltinConstantArg(TheCall, i, Result))
468 return true;
469
470 // Range check against the upper/lower values for this isntruction.
471 unsigned Val = Result.getZExtValue();
472 if (Val < l || Val > (u + l))
473 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
474 << l << u + l << TheCall->getArg(i)->getSourceRange();
475
476 return false;
477}
478
Tim Northover12670412014-02-19 10:37:05 +0000479bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
480 CallExpr *TheCall) {
481 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
482 return true;
483
484 return false;
485}
486
Tim Northover6aacd492013-07-16 09:47:53 +0000487bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
488 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
489 BuiltinID == ARM::BI__builtin_arm_strex) &&
490 "unexpected ARM builtin");
491 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
492
493 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
494
495 // Ensure that we have the proper number of arguments.
496 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
497 return true;
498
499 // Inspect the pointer argument of the atomic builtin. This should always be
500 // a pointer type, whose element is an integral scalar or pointer type.
501 // Because it is a pointer type, we don't have to worry about any implicit
502 // casts here.
503 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
504 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
505 if (PointerArgRes.isInvalid())
506 return true;
507 PointerArg = PointerArgRes.take();
508
509 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
510 if (!pointerType) {
511 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
512 << PointerArg->getType() << PointerArg->getSourceRange();
513 return true;
514 }
515
516 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
517 // task is to insert the appropriate casts into the AST. First work out just
518 // what the appropriate type is.
519 QualType ValType = pointerType->getPointeeType();
520 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
521 if (IsLdrex)
522 AddrType.addConst();
523
524 // Issue a warning if the cast is dodgy.
525 CastKind CastNeeded = CK_NoOp;
526 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
527 CastNeeded = CK_BitCast;
528 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
529 << PointerArg->getType()
530 << Context.getPointerType(AddrType)
531 << AA_Passing << PointerArg->getSourceRange();
532 }
533
534 // Finally, do the cast and replace the argument with the corrected version.
535 AddrType = Context.getPointerType(AddrType);
536 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
537 if (PointerArgRes.isInvalid())
538 return true;
539 PointerArg = PointerArgRes.take();
540
541 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
542
543 // In general, we allow ints, floats and pointers to be loaded and stored.
544 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
545 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
546 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
547 << PointerArg->getType() << PointerArg->getSourceRange();
548 return true;
549 }
550
551 // But ARM doesn't have instructions to deal with 128-bit versions.
552 if (Context.getTypeSize(ValType) > 64) {
553 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
554 << PointerArg->getType() << PointerArg->getSourceRange();
555 return true;
556 }
557
558 switch (ValType.getObjCLifetime()) {
559 case Qualifiers::OCL_None:
560 case Qualifiers::OCL_ExplicitNone:
561 // okay
562 break;
563
564 case Qualifiers::OCL_Weak:
565 case Qualifiers::OCL_Strong:
566 case Qualifiers::OCL_Autoreleasing:
567 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
568 << ValType << PointerArg->getSourceRange();
569 return true;
570 }
571
572
573 if (IsLdrex) {
574 TheCall->setType(ValType);
575 return false;
576 }
577
578 // Initialize the argument to be stored.
579 ExprResult ValArg = TheCall->getArg(0);
580 InitializedEntity Entity = InitializedEntity::InitializeParameter(
581 Context, ValType, /*consume*/ false);
582 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
583 if (ValArg.isInvalid())
584 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000585 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000586
587 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
588 // but the custom checker bypasses all default analysis.
589 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000590 return false;
591}
592
Nate Begeman4904e322010-06-08 02:47:44 +0000593bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000594 llvm::APSInt Result;
595
Tim Northover6aacd492013-07-16 09:47:53 +0000596 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
597 BuiltinID == ARM::BI__builtin_arm_strex) {
598 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
599 }
600
Tim Northover12670412014-02-19 10:37:05 +0000601 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
602 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000603
Nate Begemand773fe62010-06-13 04:47:52 +0000604 // For NEON intrinsics which take an immediate value as part of the
605 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000606 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000607 switch (BuiltinID) {
608 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000609 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
610 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000611 case ARM::BI__builtin_arm_vcvtr_f:
612 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000613 case ARM::BI__builtin_arm_dmb:
614 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begemand773fe62010-06-13 04:47:52 +0000615 };
616
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000617 // We can't check the value of a dependent argument.
618 if (TheCall->getArg(i)->isTypeDependent() ||
619 TheCall->getArg(i)->isValueDependent())
620 return false;
621
Nate Begeman91e1fea2010-06-14 05:21:25 +0000622 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000623 if (SemaBuiltinConstantArg(TheCall, i, Result))
624 return true;
625
Nate Begeman91e1fea2010-06-14 05:21:25 +0000626 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000627 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000628 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000629 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000630 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000631
Nate Begemanf568b072010-08-03 21:32:34 +0000632 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000633 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000634}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000635
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000636bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
637 unsigned i = 0, l = 0, u = 0;
638 switch (BuiltinID) {
639 default: return false;
640 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
641 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000642 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
643 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
644 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
645 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
646 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000647 };
648
649 // We can't check the value of a dependent argument.
650 if (TheCall->getArg(i)->isTypeDependent() ||
651 TheCall->getArg(i)->isValueDependent())
652 return false;
653
654 // Check that the immediate argument is actually a constant.
655 llvm::APSInt Result;
656 if (SemaBuiltinConstantArg(TheCall, i, Result))
657 return true;
658
659 // Range check against the upper/lower values for this instruction.
660 unsigned Val = Result.getZExtValue();
661 if (Val < l || Val > u)
662 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
663 << l << u << TheCall->getArg(i)->getSourceRange();
664
665 return false;
666}
667
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000668bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
669 switch (BuiltinID) {
670 case X86::BI_mm_prefetch:
671 return SemaBuiltinMMPrefetch(TheCall);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000672 }
673 return false;
674}
675
Richard Smith55ce3522012-06-25 20:30:08 +0000676/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
677/// parameter with the FormatAttr's correct format_idx and firstDataArg.
678/// Returns true when the format fits the function and the FormatStringInfo has
679/// been populated.
680bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
681 FormatStringInfo *FSI) {
682 FSI->HasVAListArg = Format->getFirstArg() == 0;
683 FSI->FormatIdx = Format->getFormatIdx() - 1;
684 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000685
Richard Smith55ce3522012-06-25 20:30:08 +0000686 // The way the format attribute works in GCC, the implicit this argument
687 // of member functions is counted. However, it doesn't appear in our own
688 // lists, so decrement format_idx in that case.
689 if (IsCXXMember) {
690 if(FSI->FormatIdx == 0)
691 return false;
692 --FSI->FormatIdx;
693 if (FSI->FirstDataArg != 0)
694 --FSI->FirstDataArg;
695 }
696 return true;
697}
Mike Stump11289f42009-09-09 15:08:12 +0000698
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000699/// Checks if a the given expression evaluates to null.
700///
701/// \brief Returns true if the value evaluates to null.
702static bool CheckNonNullExpr(Sema &S,
703 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000704 // As a special case, transparent unions initialized with zero are
705 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000706 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000707 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
708 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000709 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000710 if (const InitListExpr *ILE =
711 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000712 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000713 }
714
715 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000716 return (!Expr->isValueDependent() &&
717 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
718 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000719}
720
721static void CheckNonNullArgument(Sema &S,
722 const Expr *ArgExpr,
723 SourceLocation CallSiteLoc) {
724 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000725 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
726}
727
Ted Kremenek2bc73332014-01-17 06:24:43 +0000728static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000729 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000730 const Expr * const *ExprArgs,
731 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000732 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000733 for (specific_attr_iterator<NonNullAttr>
734 I = FDecl->specific_attr_begin<NonNullAttr>(),
735 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000736
Ted Kremeneka146db32014-01-17 06:24:47 +0000737 const NonNullAttr *NonNull = *I;
738 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
739 e = NonNull->args_end();
740 i != e; ++i) {
741 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000742 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000743 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000744
745 // Check the attributes on the parameters.
746 ArrayRef<ParmVarDecl*> parms;
747 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
748 parms = FD->parameters();
749 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
750 parms = MD->parameters();
751
752 unsigned argIndex = 0;
753 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
754 I != E; ++I, ++argIndex) {
755 const ParmVarDecl *PVD = *I;
756 if (PVD->hasAttr<NonNullAttr>())
757 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
758 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000759}
760
Richard Smith55ce3522012-06-25 20:30:08 +0000761/// Handles the checks for format strings, non-POD arguments to vararg
762/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000763void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
764 unsigned NumParams, bool IsMemberFunction,
765 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000766 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000767 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000768 if (CurContext->isDependentContext())
769 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000770
Ted Kremenekb8176da2010-09-09 04:33:05 +0000771 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000772 llvm::SmallBitVector CheckedVarArgs;
773 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000774 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000775 I = FDecl->specific_attr_begin<FormatAttr>(),
776 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000777 I != E; ++I) {
778 // Only create vector if there are format attributes.
779 CheckedVarArgs.resize(Args.size());
780
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000781 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
782 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000783 }
Richard Smithd7293d72013-08-05 18:49:43 +0000784 }
Richard Smith55ce3522012-06-25 20:30:08 +0000785
786 // Refuse POD arguments that weren't caught by the format string
787 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000788 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000789 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000790 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000791 if (const Expr *Arg = Args[ArgIdx]) {
792 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
793 checkVariadicArgument(Arg, CallType);
794 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000795 }
Richard Smithd7293d72013-08-05 18:49:43 +0000796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Richard Trieu41bc0992013-06-22 00:20:41 +0000798 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000799 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000800
Richard Trieu41bc0992013-06-22 00:20:41 +0000801 // Type safety checking.
802 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
803 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
804 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
805 i != e; ++i) {
806 CheckArgumentWithTypeTag(*i, Args.data());
807 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000808 }
Richard Smith55ce3522012-06-25 20:30:08 +0000809}
810
811/// CheckConstructorCall - Check a constructor call for correctness and safety
812/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000813void Sema::CheckConstructorCall(FunctionDecl *FDecl,
814 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000815 const FunctionProtoType *Proto,
816 SourceLocation Loc) {
817 VariadicCallType CallType =
818 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000819 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000820 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
821}
822
823/// CheckFunctionCall - Check a direct function call for various correctness
824/// and safety properties not strictly enforced by the C type system.
825bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
826 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000827 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
828 isa<CXXMethodDecl>(FDecl);
829 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
830 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000831 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
832 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000833 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000834 Expr** Args = TheCall->getArgs();
835 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000836 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000837 // If this is a call to a member operator, hide the first argument
838 // from checkCall.
839 // FIXME: Our choice of AST representation here is less than ideal.
840 ++Args;
841 --NumArgs;
842 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000843 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000844 IsMemberFunction, TheCall->getRParenLoc(),
845 TheCall->getCallee()->getSourceRange(), CallType);
846
847 IdentifierInfo *FnInfo = FDecl->getIdentifier();
848 // None of the checks below are needed for functions that don't have
849 // simple names (e.g., C++ conversion functions).
850 if (!FnInfo)
851 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000852
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000853 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
854
Anna Zaks22122702012-01-17 00:37:07 +0000855 unsigned CMId = FDecl->getMemoryFunctionKind();
856 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000857 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000858
Anna Zaks201d4892012-01-13 21:52:01 +0000859 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000860 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000861 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000862 else if (CMId == Builtin::BIstrncat)
863 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000864 else
Anna Zaks22122702012-01-17 00:37:07 +0000865 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000866
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000867 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000868}
869
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000870bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000871 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000872 VariadicCallType CallType =
873 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000874
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000875 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000876 /*IsMemberFunction=*/false,
877 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000878
879 return false;
880}
881
Richard Trieu664c4c62013-06-20 21:03:13 +0000882bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
883 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000884 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
885 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000886 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000887
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000888 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000889 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000890 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000891
Richard Trieu664c4c62013-06-20 21:03:13 +0000892 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000893 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000894 CallType = VariadicDoesNotApply;
895 } else if (Ty->isBlockPointerType()) {
896 CallType = VariadicBlock;
897 } else { // Ty->isFunctionPointerType()
898 CallType = VariadicFunction;
899 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000900 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000901
Alp Toker9cacbab2014-01-20 20:26:09 +0000902 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
903 TheCall->getNumArgs()),
904 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000905 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000906
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000907 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000908}
909
Richard Trieu41bc0992013-06-22 00:20:41 +0000910/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
911/// such as function pointers returned from functions.
912bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
913 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
914 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000915 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000916
Alp Toker9cacbab2014-01-20 20:26:09 +0000917 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
918 TheCall->getArgs(), TheCall->getNumArgs()),
919 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000920 TheCall->getCallee()->getSourceRange(), CallType);
921
922 return false;
923}
924
Richard Smithfeea8832012-04-12 05:08:17 +0000925ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
926 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000927 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
928 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000929
Richard Smithfeea8832012-04-12 05:08:17 +0000930 // All these operations take one of the following forms:
931 enum {
932 // C __c11_atomic_init(A *, C)
933 Init,
934 // C __c11_atomic_load(A *, int)
935 Load,
936 // void __atomic_load(A *, CP, int)
937 Copy,
938 // C __c11_atomic_add(A *, M, int)
939 Arithmetic,
940 // C __atomic_exchange_n(A *, CP, int)
941 Xchg,
942 // void __atomic_exchange(A *, C *, CP, int)
943 GNUXchg,
944 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
945 C11CmpXchg,
946 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
947 GNUCmpXchg
948 } Form = Init;
949 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
950 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
951 // where:
952 // C is an appropriate type,
953 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
954 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
955 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
956 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000957
Richard Smithfeea8832012-04-12 05:08:17 +0000958 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
959 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
960 && "need to update code for modified C11 atomics");
961 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
962 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
963 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
964 Op == AtomicExpr::AO__atomic_store_n ||
965 Op == AtomicExpr::AO__atomic_exchange_n ||
966 Op == AtomicExpr::AO__atomic_compare_exchange_n;
967 bool IsAddSub = false;
968
969 switch (Op) {
970 case AtomicExpr::AO__c11_atomic_init:
971 Form = Init;
972 break;
973
974 case AtomicExpr::AO__c11_atomic_load:
975 case AtomicExpr::AO__atomic_load_n:
976 Form = Load;
977 break;
978
979 case AtomicExpr::AO__c11_atomic_store:
980 case AtomicExpr::AO__atomic_load:
981 case AtomicExpr::AO__atomic_store:
982 case AtomicExpr::AO__atomic_store_n:
983 Form = Copy;
984 break;
985
986 case AtomicExpr::AO__c11_atomic_fetch_add:
987 case AtomicExpr::AO__c11_atomic_fetch_sub:
988 case AtomicExpr::AO__atomic_fetch_add:
989 case AtomicExpr::AO__atomic_fetch_sub:
990 case AtomicExpr::AO__atomic_add_fetch:
991 case AtomicExpr::AO__atomic_sub_fetch:
992 IsAddSub = true;
993 // Fall through.
994 case AtomicExpr::AO__c11_atomic_fetch_and:
995 case AtomicExpr::AO__c11_atomic_fetch_or:
996 case AtomicExpr::AO__c11_atomic_fetch_xor:
997 case AtomicExpr::AO__atomic_fetch_and:
998 case AtomicExpr::AO__atomic_fetch_or:
999 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001000 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001001 case AtomicExpr::AO__atomic_and_fetch:
1002 case AtomicExpr::AO__atomic_or_fetch:
1003 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001004 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001005 Form = Arithmetic;
1006 break;
1007
1008 case AtomicExpr::AO__c11_atomic_exchange:
1009 case AtomicExpr::AO__atomic_exchange_n:
1010 Form = Xchg;
1011 break;
1012
1013 case AtomicExpr::AO__atomic_exchange:
1014 Form = GNUXchg;
1015 break;
1016
1017 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1018 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1019 Form = C11CmpXchg;
1020 break;
1021
1022 case AtomicExpr::AO__atomic_compare_exchange:
1023 case AtomicExpr::AO__atomic_compare_exchange_n:
1024 Form = GNUCmpXchg;
1025 break;
1026 }
1027
1028 // Check we have the right number of arguments.
1029 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001030 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001031 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001032 << TheCall->getCallee()->getSourceRange();
1033 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001034 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1035 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001036 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001037 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001038 << TheCall->getCallee()->getSourceRange();
1039 return ExprError();
1040 }
1041
Richard Smithfeea8832012-04-12 05:08:17 +00001042 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001043 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001044 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1045 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1046 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001047 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001048 << Ptr->getType() << Ptr->getSourceRange();
1049 return ExprError();
1050 }
1051
Richard Smithfeea8832012-04-12 05:08:17 +00001052 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1053 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1054 QualType ValType = AtomTy; // 'C'
1055 if (IsC11) {
1056 if (!AtomTy->isAtomicType()) {
1057 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1058 << Ptr->getType() << Ptr->getSourceRange();
1059 return ExprError();
1060 }
Richard Smithe00921a2012-09-15 06:09:58 +00001061 if (AtomTy.isConstQualified()) {
1062 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1063 << Ptr->getType() << Ptr->getSourceRange();
1064 return ExprError();
1065 }
Richard Smithfeea8832012-04-12 05:08:17 +00001066 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001067 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001068
Richard Smithfeea8832012-04-12 05:08:17 +00001069 // For an arithmetic operation, the implied arithmetic must be well-formed.
1070 if (Form == Arithmetic) {
1071 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1072 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1073 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1074 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1075 return ExprError();
1076 }
1077 if (!IsAddSub && !ValType->isIntegerType()) {
1078 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1079 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1080 return ExprError();
1081 }
1082 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1083 // For __atomic_*_n operations, the value type must be a scalar integral or
1084 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001085 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001086 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1087 return ExprError();
1088 }
1089
Eli Friedmanaa769812013-09-11 03:49:34 +00001090 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1091 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001092 // For GNU atomics, require a trivially-copyable type. This is not part of
1093 // the GNU atomics specification, but we enforce it for sanity.
1094 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001095 << Ptr->getType() << Ptr->getSourceRange();
1096 return ExprError();
1097 }
1098
Richard Smithfeea8832012-04-12 05:08:17 +00001099 // FIXME: For any builtin other than a load, the ValType must not be
1100 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001101
1102 switch (ValType.getObjCLifetime()) {
1103 case Qualifiers::OCL_None:
1104 case Qualifiers::OCL_ExplicitNone:
1105 // okay
1106 break;
1107
1108 case Qualifiers::OCL_Weak:
1109 case Qualifiers::OCL_Strong:
1110 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001111 // FIXME: Can this happen? By this point, ValType should be known
1112 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001113 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1114 << ValType << Ptr->getSourceRange();
1115 return ExprError();
1116 }
1117
1118 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001119 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001120 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001121 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001122 ResultType = Context.BoolTy;
1123
Richard Smithfeea8832012-04-12 05:08:17 +00001124 // The type of a parameter passed 'by value'. In the GNU atomics, such
1125 // arguments are actually passed as pointers.
1126 QualType ByValType = ValType; // 'CP'
1127 if (!IsC11 && !IsN)
1128 ByValType = Ptr->getType();
1129
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001130 // The first argument --- the pointer --- has a fixed type; we
1131 // deduce the types of the rest of the arguments accordingly. Walk
1132 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001133 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001134 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001135 if (i < NumVals[Form] + 1) {
1136 switch (i) {
1137 case 1:
1138 // The second argument is the non-atomic operand. For arithmetic, this
1139 // is always passed by value, and for a compare_exchange it is always
1140 // passed by address. For the rest, GNU uses by-address and C11 uses
1141 // by-value.
1142 assert(Form != Load);
1143 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1144 Ty = ValType;
1145 else if (Form == Copy || Form == Xchg)
1146 Ty = ByValType;
1147 else if (Form == Arithmetic)
1148 Ty = Context.getPointerDiffType();
1149 else
1150 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1151 break;
1152 case 2:
1153 // The third argument to compare_exchange / GNU exchange is a
1154 // (pointer to a) desired value.
1155 Ty = ByValType;
1156 break;
1157 case 3:
1158 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1159 Ty = Context.BoolTy;
1160 break;
1161 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001162 } else {
1163 // The order(s) are always converted to int.
1164 Ty = Context.IntTy;
1165 }
Richard Smithfeea8832012-04-12 05:08:17 +00001166
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001167 InitializedEntity Entity =
1168 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001169 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001170 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1171 if (Arg.isInvalid())
1172 return true;
1173 TheCall->setArg(i, Arg.get());
1174 }
1175
Richard Smithfeea8832012-04-12 05:08:17 +00001176 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001177 SmallVector<Expr*, 5> SubExprs;
1178 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001179 switch (Form) {
1180 case Init:
1181 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001182 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001183 break;
1184 case Load:
1185 SubExprs.push_back(TheCall->getArg(1)); // Order
1186 break;
1187 case Copy:
1188 case Arithmetic:
1189 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001190 SubExprs.push_back(TheCall->getArg(2)); // Order
1191 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001192 break;
1193 case GNUXchg:
1194 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1195 SubExprs.push_back(TheCall->getArg(3)); // Order
1196 SubExprs.push_back(TheCall->getArg(1)); // Val1
1197 SubExprs.push_back(TheCall->getArg(2)); // Val2
1198 break;
1199 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001200 SubExprs.push_back(TheCall->getArg(3)); // Order
1201 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001202 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001203 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001204 break;
1205 case GNUCmpXchg:
1206 SubExprs.push_back(TheCall->getArg(4)); // Order
1207 SubExprs.push_back(TheCall->getArg(1)); // Val1
1208 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1209 SubExprs.push_back(TheCall->getArg(2)); // Val2
1210 SubExprs.push_back(TheCall->getArg(3)); // Weak
1211 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001212 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001213
1214 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1215 SubExprs, ResultType, Op,
1216 TheCall->getRParenLoc());
1217
1218 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1219 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1220 Context.AtomicUsesUnsupportedLibcall(AE))
1221 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1222 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001223
Fariborz Jahanian615de762013-05-28 17:37:39 +00001224 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001225}
1226
1227
John McCall29ad95b2011-08-27 01:09:30 +00001228/// checkBuiltinArgument - Given a call to a builtin function, perform
1229/// normal type-checking on the given argument, updating the call in
1230/// place. This is useful when a builtin function requires custom
1231/// type-checking for some of its arguments but not necessarily all of
1232/// them.
1233///
1234/// Returns true on error.
1235static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1236 FunctionDecl *Fn = E->getDirectCallee();
1237 assert(Fn && "builtin call without direct callee!");
1238
1239 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1240 InitializedEntity Entity =
1241 InitializedEntity::InitializeParameter(S.Context, Param);
1242
1243 ExprResult Arg = E->getArg(0);
1244 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1245 if (Arg.isInvalid())
1246 return true;
1247
1248 E->setArg(ArgIndex, Arg.take());
1249 return false;
1250}
1251
Chris Lattnerdc046542009-05-08 06:58:22 +00001252/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1253/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1254/// type of its first argument. The main ActOnCallExpr routines have already
1255/// promoted the types of arguments because all of these calls are prototyped as
1256/// void(...).
1257///
1258/// This function goes through and does final semantic checking for these
1259/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001260ExprResult
1261Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001262 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001263 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1264 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1265
1266 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001267 if (TheCall->getNumArgs() < 1) {
1268 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1269 << 0 << 1 << TheCall->getNumArgs()
1270 << TheCall->getCallee()->getSourceRange();
1271 return ExprError();
1272 }
Mike Stump11289f42009-09-09 15:08:12 +00001273
Chris Lattnerdc046542009-05-08 06:58:22 +00001274 // Inspect the first argument of the atomic builtin. This should always be
1275 // a pointer type, whose element is an integral scalar or pointer type.
1276 // Because it is a pointer type, we don't have to worry about any implicit
1277 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001278 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001279 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001280 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1281 if (FirstArgResult.isInvalid())
1282 return ExprError();
1283 FirstArg = FirstArgResult.take();
1284 TheCall->setArg(0, FirstArg);
1285
John McCall31168b02011-06-15 23:02:42 +00001286 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1287 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001288 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1289 << FirstArg->getType() << FirstArg->getSourceRange();
1290 return ExprError();
1291 }
Mike Stump11289f42009-09-09 15:08:12 +00001292
John McCall31168b02011-06-15 23:02:42 +00001293 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001294 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001295 !ValType->isBlockPointerType()) {
1296 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1297 << FirstArg->getType() << FirstArg->getSourceRange();
1298 return ExprError();
1299 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001300
John McCall31168b02011-06-15 23:02:42 +00001301 switch (ValType.getObjCLifetime()) {
1302 case Qualifiers::OCL_None:
1303 case Qualifiers::OCL_ExplicitNone:
1304 // okay
1305 break;
1306
1307 case Qualifiers::OCL_Weak:
1308 case Qualifiers::OCL_Strong:
1309 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001310 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001311 << ValType << FirstArg->getSourceRange();
1312 return ExprError();
1313 }
1314
John McCallb50451a2011-10-05 07:41:44 +00001315 // Strip any qualifiers off ValType.
1316 ValType = ValType.getUnqualifiedType();
1317
Chandler Carruth3973af72010-07-18 20:54:12 +00001318 // The majority of builtins return a value, but a few have special return
1319 // types, so allow them to override appropriately below.
1320 QualType ResultType = ValType;
1321
Chris Lattnerdc046542009-05-08 06:58:22 +00001322 // We need to figure out which concrete builtin this maps onto. For example,
1323 // __sync_fetch_and_add with a 2 byte object turns into
1324 // __sync_fetch_and_add_2.
1325#define BUILTIN_ROW(x) \
1326 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1327 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Chris Lattnerdc046542009-05-08 06:58:22 +00001329 static const unsigned BuiltinIndices[][5] = {
1330 BUILTIN_ROW(__sync_fetch_and_add),
1331 BUILTIN_ROW(__sync_fetch_and_sub),
1332 BUILTIN_ROW(__sync_fetch_and_or),
1333 BUILTIN_ROW(__sync_fetch_and_and),
1334 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001335
Chris Lattnerdc046542009-05-08 06:58:22 +00001336 BUILTIN_ROW(__sync_add_and_fetch),
1337 BUILTIN_ROW(__sync_sub_and_fetch),
1338 BUILTIN_ROW(__sync_and_and_fetch),
1339 BUILTIN_ROW(__sync_or_and_fetch),
1340 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001341
Chris Lattnerdc046542009-05-08 06:58:22 +00001342 BUILTIN_ROW(__sync_val_compare_and_swap),
1343 BUILTIN_ROW(__sync_bool_compare_and_swap),
1344 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001345 BUILTIN_ROW(__sync_lock_release),
1346 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001347 };
Mike Stump11289f42009-09-09 15:08:12 +00001348#undef BUILTIN_ROW
1349
Chris Lattnerdc046542009-05-08 06:58:22 +00001350 // Determine the index of the size.
1351 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001352 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001353 case 1: SizeIndex = 0; break;
1354 case 2: SizeIndex = 1; break;
1355 case 4: SizeIndex = 2; break;
1356 case 8: SizeIndex = 3; break;
1357 case 16: SizeIndex = 4; break;
1358 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001359 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1360 << FirstArg->getType() << FirstArg->getSourceRange();
1361 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001362 }
Mike Stump11289f42009-09-09 15:08:12 +00001363
Chris Lattnerdc046542009-05-08 06:58:22 +00001364 // Each of these builtins has one pointer argument, followed by some number of
1365 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1366 // that we ignore. Find out which row of BuiltinIndices to read from as well
1367 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001368 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001369 unsigned BuiltinIndex, NumFixed = 1;
1370 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001371 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001372 case Builtin::BI__sync_fetch_and_add:
1373 case Builtin::BI__sync_fetch_and_add_1:
1374 case Builtin::BI__sync_fetch_and_add_2:
1375 case Builtin::BI__sync_fetch_and_add_4:
1376 case Builtin::BI__sync_fetch_and_add_8:
1377 case Builtin::BI__sync_fetch_and_add_16:
1378 BuiltinIndex = 0;
1379 break;
1380
1381 case Builtin::BI__sync_fetch_and_sub:
1382 case Builtin::BI__sync_fetch_and_sub_1:
1383 case Builtin::BI__sync_fetch_and_sub_2:
1384 case Builtin::BI__sync_fetch_and_sub_4:
1385 case Builtin::BI__sync_fetch_and_sub_8:
1386 case Builtin::BI__sync_fetch_and_sub_16:
1387 BuiltinIndex = 1;
1388 break;
1389
1390 case Builtin::BI__sync_fetch_and_or:
1391 case Builtin::BI__sync_fetch_and_or_1:
1392 case Builtin::BI__sync_fetch_and_or_2:
1393 case Builtin::BI__sync_fetch_and_or_4:
1394 case Builtin::BI__sync_fetch_and_or_8:
1395 case Builtin::BI__sync_fetch_and_or_16:
1396 BuiltinIndex = 2;
1397 break;
1398
1399 case Builtin::BI__sync_fetch_and_and:
1400 case Builtin::BI__sync_fetch_and_and_1:
1401 case Builtin::BI__sync_fetch_and_and_2:
1402 case Builtin::BI__sync_fetch_and_and_4:
1403 case Builtin::BI__sync_fetch_and_and_8:
1404 case Builtin::BI__sync_fetch_and_and_16:
1405 BuiltinIndex = 3;
1406 break;
Mike Stump11289f42009-09-09 15:08:12 +00001407
Douglas Gregor73722482011-11-28 16:30:08 +00001408 case Builtin::BI__sync_fetch_and_xor:
1409 case Builtin::BI__sync_fetch_and_xor_1:
1410 case Builtin::BI__sync_fetch_and_xor_2:
1411 case Builtin::BI__sync_fetch_and_xor_4:
1412 case Builtin::BI__sync_fetch_and_xor_8:
1413 case Builtin::BI__sync_fetch_and_xor_16:
1414 BuiltinIndex = 4;
1415 break;
1416
1417 case Builtin::BI__sync_add_and_fetch:
1418 case Builtin::BI__sync_add_and_fetch_1:
1419 case Builtin::BI__sync_add_and_fetch_2:
1420 case Builtin::BI__sync_add_and_fetch_4:
1421 case Builtin::BI__sync_add_and_fetch_8:
1422 case Builtin::BI__sync_add_and_fetch_16:
1423 BuiltinIndex = 5;
1424 break;
1425
1426 case Builtin::BI__sync_sub_and_fetch:
1427 case Builtin::BI__sync_sub_and_fetch_1:
1428 case Builtin::BI__sync_sub_and_fetch_2:
1429 case Builtin::BI__sync_sub_and_fetch_4:
1430 case Builtin::BI__sync_sub_and_fetch_8:
1431 case Builtin::BI__sync_sub_and_fetch_16:
1432 BuiltinIndex = 6;
1433 break;
1434
1435 case Builtin::BI__sync_and_and_fetch:
1436 case Builtin::BI__sync_and_and_fetch_1:
1437 case Builtin::BI__sync_and_and_fetch_2:
1438 case Builtin::BI__sync_and_and_fetch_4:
1439 case Builtin::BI__sync_and_and_fetch_8:
1440 case Builtin::BI__sync_and_and_fetch_16:
1441 BuiltinIndex = 7;
1442 break;
1443
1444 case Builtin::BI__sync_or_and_fetch:
1445 case Builtin::BI__sync_or_and_fetch_1:
1446 case Builtin::BI__sync_or_and_fetch_2:
1447 case Builtin::BI__sync_or_and_fetch_4:
1448 case Builtin::BI__sync_or_and_fetch_8:
1449 case Builtin::BI__sync_or_and_fetch_16:
1450 BuiltinIndex = 8;
1451 break;
1452
1453 case Builtin::BI__sync_xor_and_fetch:
1454 case Builtin::BI__sync_xor_and_fetch_1:
1455 case Builtin::BI__sync_xor_and_fetch_2:
1456 case Builtin::BI__sync_xor_and_fetch_4:
1457 case Builtin::BI__sync_xor_and_fetch_8:
1458 case Builtin::BI__sync_xor_and_fetch_16:
1459 BuiltinIndex = 9;
1460 break;
Mike Stump11289f42009-09-09 15:08:12 +00001461
Chris Lattnerdc046542009-05-08 06:58:22 +00001462 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001463 case Builtin::BI__sync_val_compare_and_swap_1:
1464 case Builtin::BI__sync_val_compare_and_swap_2:
1465 case Builtin::BI__sync_val_compare_and_swap_4:
1466 case Builtin::BI__sync_val_compare_and_swap_8:
1467 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001468 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001469 NumFixed = 2;
1470 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001471
Chris Lattnerdc046542009-05-08 06:58:22 +00001472 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001473 case Builtin::BI__sync_bool_compare_and_swap_1:
1474 case Builtin::BI__sync_bool_compare_and_swap_2:
1475 case Builtin::BI__sync_bool_compare_and_swap_4:
1476 case Builtin::BI__sync_bool_compare_and_swap_8:
1477 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001478 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001479 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001480 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001481 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001482
1483 case Builtin::BI__sync_lock_test_and_set:
1484 case Builtin::BI__sync_lock_test_and_set_1:
1485 case Builtin::BI__sync_lock_test_and_set_2:
1486 case Builtin::BI__sync_lock_test_and_set_4:
1487 case Builtin::BI__sync_lock_test_and_set_8:
1488 case Builtin::BI__sync_lock_test_and_set_16:
1489 BuiltinIndex = 12;
1490 break;
1491
Chris Lattnerdc046542009-05-08 06:58:22 +00001492 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001493 case Builtin::BI__sync_lock_release_1:
1494 case Builtin::BI__sync_lock_release_2:
1495 case Builtin::BI__sync_lock_release_4:
1496 case Builtin::BI__sync_lock_release_8:
1497 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001498 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001499 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001500 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001501 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001502
1503 case Builtin::BI__sync_swap:
1504 case Builtin::BI__sync_swap_1:
1505 case Builtin::BI__sync_swap_2:
1506 case Builtin::BI__sync_swap_4:
1507 case Builtin::BI__sync_swap_8:
1508 case Builtin::BI__sync_swap_16:
1509 BuiltinIndex = 14;
1510 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001511 }
Mike Stump11289f42009-09-09 15:08:12 +00001512
Chris Lattnerdc046542009-05-08 06:58:22 +00001513 // Now that we know how many fixed arguments we expect, first check that we
1514 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001515 if (TheCall->getNumArgs() < 1+NumFixed) {
1516 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1517 << 0 << 1+NumFixed << TheCall->getNumArgs()
1518 << TheCall->getCallee()->getSourceRange();
1519 return ExprError();
1520 }
Mike Stump11289f42009-09-09 15:08:12 +00001521
Chris Lattner5b9241b2009-05-08 15:36:58 +00001522 // Get the decl for the concrete builtin from this, we can tell what the
1523 // concrete integer type we should convert to is.
1524 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1525 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001526 FunctionDecl *NewBuiltinDecl;
1527 if (NewBuiltinID == BuiltinID)
1528 NewBuiltinDecl = FDecl;
1529 else {
1530 // Perform builtin lookup to avoid redeclaring it.
1531 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1532 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1533 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1534 assert(Res.getFoundDecl());
1535 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1536 if (NewBuiltinDecl == 0)
1537 return ExprError();
1538 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001539
John McCallcf142162010-08-07 06:22:56 +00001540 // The first argument --- the pointer --- has a fixed type; we
1541 // deduce the types of the rest of the arguments accordingly. Walk
1542 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001543 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001544 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001545
Chris Lattnerdc046542009-05-08 06:58:22 +00001546 // GCC does an implicit conversion to the pointer or integer ValType. This
1547 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001548 // Initialize the argument.
1549 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1550 ValType, /*consume*/ false);
1551 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001552 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001553 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001554
Chris Lattnerdc046542009-05-08 06:58:22 +00001555 // Okay, we have something that *can* be converted to the right type. Check
1556 // to see if there is a potentially weird extension going on here. This can
1557 // happen when you do an atomic operation on something like an char* and
1558 // pass in 42. The 42 gets converted to char. This is even more strange
1559 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001560 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001561 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001562 }
Mike Stump11289f42009-09-09 15:08:12 +00001563
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001564 ASTContext& Context = this->getASTContext();
1565
1566 // Create a new DeclRefExpr to refer to the new decl.
1567 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1568 Context,
1569 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001570 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001571 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001572 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001573 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001574 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001575 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001576
Chris Lattnerdc046542009-05-08 06:58:22 +00001577 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001578 // FIXME: This loses syntactic information.
1579 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1580 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1581 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001582 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001583
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001584 // Change the result type of the call to match the original value type. This
1585 // is arbitrary, but the codegen for these builtins ins design to handle it
1586 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001587 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001588
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001589 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001590}
1591
Chris Lattner6436fb62009-02-18 06:01:06 +00001592/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001593/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001594/// Note: It might also make sense to do the UTF-16 conversion here (would
1595/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001596bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001597 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001598 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1599
Douglas Gregorfb65e592011-07-27 05:40:30 +00001600 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001601 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1602 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001603 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001604 }
Mike Stump11289f42009-09-09 15:08:12 +00001605
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001606 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001607 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001608 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001609 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001610 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001611 UTF16 *ToPtr = &ToBuf[0];
1612
1613 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1614 &ToPtr, ToPtr + NumBytes,
1615 strictConversion);
1616 // Check for conversion failure.
1617 if (Result != conversionOK)
1618 Diag(Arg->getLocStart(),
1619 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1620 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001621 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001622}
1623
Chris Lattnere202e6a2007-12-20 00:05:45 +00001624/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1625/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001626bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1627 Expr *Fn = TheCall->getCallee();
1628 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001629 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001630 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001631 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1632 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001633 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001634 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001635 return true;
1636 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001637
1638 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001639 return Diag(TheCall->getLocEnd(),
1640 diag::err_typecheck_call_too_few_args_at_least)
1641 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001642 }
1643
John McCall29ad95b2011-08-27 01:09:30 +00001644 // Type-check the first argument normally.
1645 if (checkBuiltinArgument(*this, TheCall, 0))
1646 return true;
1647
Chris Lattnere202e6a2007-12-20 00:05:45 +00001648 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001649 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001650 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001651 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001652 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001653 else if (FunctionDecl *FD = getCurFunctionDecl())
1654 isVariadic = FD->isVariadic();
1655 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001656 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001657
Chris Lattnere202e6a2007-12-20 00:05:45 +00001658 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001659 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1660 return true;
1661 }
Mike Stump11289f42009-09-09 15:08:12 +00001662
Chris Lattner43be2e62007-12-19 23:59:04 +00001663 // Verify that the second argument to the builtin is the last argument of the
1664 // current function or method.
1665 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001666 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001667
Nico Weber9eea7642013-05-24 23:31:57 +00001668 // These are valid if SecondArgIsLastNamedArgument is false after the next
1669 // block.
1670 QualType Type;
1671 SourceLocation ParamLoc;
1672
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001673 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1674 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001675 // FIXME: This isn't correct for methods (results in bogus warning).
1676 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001677 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001678 if (CurBlock)
1679 LastArg = *(CurBlock->TheDecl->param_end()-1);
1680 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001681 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001682 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001683 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001684 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001685
1686 Type = PV->getType();
1687 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001688 }
1689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattner43be2e62007-12-19 23:59:04 +00001691 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001692 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001693 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001694 else if (Type->isReferenceType()) {
1695 Diag(Arg->getLocStart(),
1696 diag::warn_va_start_of_reference_type_is_undefined);
1697 Diag(ParamLoc, diag::note_parameter_type) << Type;
1698 }
1699
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001700 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001701 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001702}
Chris Lattner43be2e62007-12-19 23:59:04 +00001703
Chris Lattner2da14fb2007-12-20 00:26:33 +00001704/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1705/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001706bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1707 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001708 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001709 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001710 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001711 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001712 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001713 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001714 << SourceRange(TheCall->getArg(2)->getLocStart(),
1715 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001716
John Wiegley01296292011-04-08 18:41:53 +00001717 ExprResult OrigArg0 = TheCall->getArg(0);
1718 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001719
Chris Lattner2da14fb2007-12-20 00:26:33 +00001720 // Do standard promotions between the two arguments, returning their common
1721 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001722 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001723 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1724 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001725
1726 // Make sure any conversions are pushed back into the call; this is
1727 // type safe since unordered compare builtins are declared as "_Bool
1728 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001729 TheCall->setArg(0, OrigArg0.get());
1730 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001731
John Wiegley01296292011-04-08 18:41:53 +00001732 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001733 return false;
1734
Chris Lattner2da14fb2007-12-20 00:26:33 +00001735 // If the common type isn't a real floating type, then the arguments were
1736 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001737 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001738 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001739 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001740 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1741 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattner2da14fb2007-12-20 00:26:33 +00001743 return false;
1744}
1745
Benjamin Kramer634fc102010-02-15 22:42:31 +00001746/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1747/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001748/// to check everything. We expect the last argument to be a floating point
1749/// value.
1750bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1751 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001752 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001753 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001754 if (TheCall->getNumArgs() > NumArgs)
1755 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001756 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001757 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001758 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001759 (*(TheCall->arg_end()-1))->getLocEnd());
1760
Benjamin Kramer64aae502010-02-16 10:07:31 +00001761 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001762
Eli Friedman7e4faac2009-08-31 20:06:00 +00001763 if (OrigArg->isTypeDependent())
1764 return false;
1765
Chris Lattner68784ef2010-05-06 05:50:07 +00001766 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001767 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001768 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001769 diag::err_typecheck_call_invalid_unary_fp)
1770 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattner68784ef2010-05-06 05:50:07 +00001772 // If this is an implicit conversion from float -> double, remove it.
1773 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1774 Expr *CastArg = Cast->getSubExpr();
1775 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1776 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1777 "promotion from float to double is the only expected cast here");
1778 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001779 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001780 }
1781 }
1782
Eli Friedman7e4faac2009-08-31 20:06:00 +00001783 return false;
1784}
1785
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001786/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1787// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001788ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001789 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001790 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001791 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001792 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1793 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001794
Nate Begemana0110022010-06-08 00:16:34 +00001795 // Determine which of the following types of shufflevector we're checking:
1796 // 1) unary, vector mask: (lhs, mask)
1797 // 2) binary, vector mask: (lhs, rhs, mask)
1798 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1799 QualType resType = TheCall->getArg(0)->getType();
1800 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001801
Douglas Gregorc25f7662009-05-19 22:10:17 +00001802 if (!TheCall->getArg(0)->isTypeDependent() &&
1803 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001804 QualType LHSType = TheCall->getArg(0)->getType();
1805 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001806
Craig Topperbaca3892013-07-29 06:47:04 +00001807 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1808 return ExprError(Diag(TheCall->getLocStart(),
1809 diag::err_shufflevector_non_vector)
1810 << SourceRange(TheCall->getArg(0)->getLocStart(),
1811 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001812
Nate Begemana0110022010-06-08 00:16:34 +00001813 numElements = LHSType->getAs<VectorType>()->getNumElements();
1814 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001815
Nate Begemana0110022010-06-08 00:16:34 +00001816 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1817 // with mask. If so, verify that RHS is an integer vector type with the
1818 // same number of elts as lhs.
1819 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001820 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001821 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001822 return ExprError(Diag(TheCall->getLocStart(),
1823 diag::err_shufflevector_incompatible_vector)
1824 << SourceRange(TheCall->getArg(1)->getLocStart(),
1825 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001826 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001827 return ExprError(Diag(TheCall->getLocStart(),
1828 diag::err_shufflevector_incompatible_vector)
1829 << SourceRange(TheCall->getArg(0)->getLocStart(),
1830 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001831 } else if (numElements != numResElements) {
1832 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001833 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001834 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001835 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001836 }
1837
1838 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001839 if (TheCall->getArg(i)->isTypeDependent() ||
1840 TheCall->getArg(i)->isValueDependent())
1841 continue;
1842
Nate Begemana0110022010-06-08 00:16:34 +00001843 llvm::APSInt Result(32);
1844 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1845 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001846 diag::err_shufflevector_nonconstant_argument)
1847 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001848
Craig Topper50ad5b72013-08-03 17:40:38 +00001849 // Allow -1 which will be translated to undef in the IR.
1850 if (Result.isSigned() && Result.isAllOnesValue())
1851 continue;
1852
Chris Lattner7ab824e2008-08-10 02:05:13 +00001853 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001854 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001855 diag::err_shufflevector_argument_too_large)
1856 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001857 }
1858
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001859 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001860
Chris Lattner7ab824e2008-08-10 02:05:13 +00001861 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001862 exprs.push_back(TheCall->getArg(i));
1863 TheCall->setArg(i, 0);
1864 }
1865
Benjamin Kramerc215e762012-08-24 11:54:20 +00001866 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001867 TheCall->getCallee()->getLocStart(),
1868 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001869}
Chris Lattner43be2e62007-12-19 23:59:04 +00001870
Hal Finkelc4d7c822013-09-18 03:29:45 +00001871/// SemaConvertVectorExpr - Handle __builtin_convertvector
1872ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1873 SourceLocation BuiltinLoc,
1874 SourceLocation RParenLoc) {
1875 ExprValueKind VK = VK_RValue;
1876 ExprObjectKind OK = OK_Ordinary;
1877 QualType DstTy = TInfo->getType();
1878 QualType SrcTy = E->getType();
1879
1880 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1881 return ExprError(Diag(BuiltinLoc,
1882 diag::err_convertvector_non_vector)
1883 << E->getSourceRange());
1884 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1885 return ExprError(Diag(BuiltinLoc,
1886 diag::err_convertvector_non_vector_type));
1887
1888 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1889 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1890 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1891 if (SrcElts != DstElts)
1892 return ExprError(Diag(BuiltinLoc,
1893 diag::err_convertvector_incompatible_vector)
1894 << E->getSourceRange());
1895 }
1896
1897 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1898 BuiltinLoc, RParenLoc));
1899
1900}
1901
Daniel Dunbarb7257262008-07-21 22:59:13 +00001902/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1903// This is declared to take (const void*, ...) and can take two
1904// optional constant int args.
1905bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001906 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001907
Chris Lattner3b054132008-11-19 05:08:23 +00001908 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001909 return Diag(TheCall->getLocEnd(),
1910 diag::err_typecheck_call_too_many_args_at_most)
1911 << 0 /*function call*/ << 3 << NumArgs
1912 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001913
1914 // Argument 0 is checked for us and the remaining arguments must be
1915 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001916 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001917 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001918
1919 // We can't check the value of a dependent argument.
1920 if (Arg->isTypeDependent() || Arg->isValueDependent())
1921 continue;
1922
Eli Friedman5efba262009-12-04 00:30:06 +00001923 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001924 if (SemaBuiltinConstantArg(TheCall, i, Result))
1925 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001926
Daniel Dunbarb7257262008-07-21 22:59:13 +00001927 // FIXME: gcc issues a warning and rewrites these to 0. These
1928 // seems especially odd for the third argument since the default
1929 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001930 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001931 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001932 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001933 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001934 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001935 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001936 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001937 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001938 }
1939 }
1940
Chris Lattner3b054132008-11-19 05:08:23 +00001941 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001942}
1943
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001944/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1945// This is declared to take (const char*, int)
1946bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1947 Expr *Arg = TheCall->getArg(1);
1948
1949 // We can't check the value of a dependent argument.
1950 if (Arg->isTypeDependent() || Arg->isValueDependent())
1951 return false;
1952
1953 llvm::APSInt Result;
1954 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1955 return true;
1956
1957 if (Result.getLimitedValue() > 3)
1958 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1959 << "0" << "3" << Arg->getSourceRange();
1960
1961 return false;
1962}
1963
Eric Christopher8d0c6212010-04-17 02:26:23 +00001964/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1965/// TheCall is a constant expression.
1966bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1967 llvm::APSInt &Result) {
1968 Expr *Arg = TheCall->getArg(ArgNum);
1969 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1970 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1971
1972 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1973
1974 if (!Arg->isIntegerConstantExpr(Result, Context))
1975 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001976 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001977
Chris Lattnerd545ad12009-09-23 06:06:36 +00001978 return false;
1979}
1980
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001981/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1982/// int type). This simply type checks that type is one of the defined
1983/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001984// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001985bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001986 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001987
1988 // We can't check the value of a dependent argument.
1989 if (TheCall->getArg(1)->isTypeDependent() ||
1990 TheCall->getArg(1)->isValueDependent())
1991 return false;
1992
Eric Christopher8d0c6212010-04-17 02:26:23 +00001993 // Check constant-ness first.
1994 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1995 return true;
1996
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001997 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001998 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001999 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2000 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002001 }
2002
2003 return false;
2004}
2005
Eli Friedmanc97d0142009-05-03 06:04:26 +00002006/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002007/// This checks that val is a constant 1.
2008bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2009 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002010 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002011
Eric Christopher8d0c6212010-04-17 02:26:23 +00002012 // TODO: This is less than ideal. Overload this to take a value.
2013 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2014 return true;
2015
2016 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002017 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2018 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2019
2020 return false;
2021}
2022
Richard Smithd7293d72013-08-05 18:49:43 +00002023namespace {
2024enum StringLiteralCheckType {
2025 SLCT_NotALiteral,
2026 SLCT_UncheckedLiteral,
2027 SLCT_CheckedLiteral
2028};
2029}
2030
Richard Smith55ce3522012-06-25 20:30:08 +00002031// Determine if an expression is a string literal or constant string.
2032// If this function returns false on the arguments to a function expecting a
2033// format string, we will usually need to emit a warning.
2034// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002035static StringLiteralCheckType
2036checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2037 bool HasVAListArg, unsigned format_idx,
2038 unsigned firstDataArg, Sema::FormatStringType Type,
2039 Sema::VariadicCallType CallType, bool InFunctionCall,
2040 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002041 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002042 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002043 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002044
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002045 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002046
Richard Smithd7293d72013-08-05 18:49:43 +00002047 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002048 // Technically -Wformat-nonliteral does not warn about this case.
2049 // The behavior of printf and friends in this case is implementation
2050 // dependent. Ideally if the format string cannot be null then
2051 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002052 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002053
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002054 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002055 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002056 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002057 // The expression is a literal if both sub-expressions were, and it was
2058 // completely checked only if both sub-expressions were checked.
2059 const AbstractConditionalOperator *C =
2060 cast<AbstractConditionalOperator>(E);
2061 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002062 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002063 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002064 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002065 if (Left == SLCT_NotALiteral)
2066 return SLCT_NotALiteral;
2067 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002068 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002069 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002070 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002071 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002072 }
2073
2074 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002075 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2076 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002077 }
2078
John McCallc07a0c72011-02-17 10:25:35 +00002079 case Stmt::OpaqueValueExprClass:
2080 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2081 E = src;
2082 goto tryAgain;
2083 }
Richard Smith55ce3522012-06-25 20:30:08 +00002084 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002085
Ted Kremeneka8890832011-02-24 23:03:04 +00002086 case Stmt::PredefinedExprClass:
2087 // While __func__, etc., are technically not string literals, they
2088 // cannot contain format specifiers and thus are not a security
2089 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002090 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002091
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002092 case Stmt::DeclRefExprClass: {
2093 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002094
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002095 // As an exception, do not flag errors for variables binding to
2096 // const string literals.
2097 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2098 bool isConstant = false;
2099 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002100
Richard Smithd7293d72013-08-05 18:49:43 +00002101 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2102 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002103 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002104 isConstant = T.isConstant(S.Context) &&
2105 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002106 } else if (T->isObjCObjectPointerType()) {
2107 // In ObjC, there is usually no "const ObjectPointer" type,
2108 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002109 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002110 }
Mike Stump11289f42009-09-09 15:08:12 +00002111
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002112 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002113 if (const Expr *Init = VD->getAnyInitializer()) {
2114 // Look through initializers like const char c[] = { "foo" }
2115 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2116 if (InitList->isStringLiteralInit())
2117 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2118 }
Richard Smithd7293d72013-08-05 18:49:43 +00002119 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002120 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002121 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002122 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002123 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Anders Carlssonb012ca92009-06-28 19:55:58 +00002126 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2127 // special check to see if the format string is a function parameter
2128 // of the function calling the printf function. If the function
2129 // has an attribute indicating it is a printf-like function, then we
2130 // should suppress warnings concerning non-literals being used in a call
2131 // to a vprintf function. For example:
2132 //
2133 // void
2134 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2135 // va_list ap;
2136 // va_start(ap, fmt);
2137 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2138 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002139 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002140 if (HasVAListArg) {
2141 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2142 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2143 int PVIndex = PV->getFunctionScopeIndex() + 1;
2144 for (specific_attr_iterator<FormatAttr>
2145 i = ND->specific_attr_begin<FormatAttr>(),
2146 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2147 FormatAttr *PVFormat = *i;
2148 // adjust for implicit parameter
2149 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2150 if (MD->isInstance())
2151 ++PVIndex;
2152 // We also check if the formats are compatible.
2153 // We can't pass a 'scanf' string to a 'printf' function.
2154 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002155 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002156 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002157 }
2158 }
2159 }
2160 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002161 }
Mike Stump11289f42009-09-09 15:08:12 +00002162
Richard Smith55ce3522012-06-25 20:30:08 +00002163 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002164 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002165
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002166 case Stmt::CallExprClass:
2167 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002168 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002169 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2170 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2171 unsigned ArgIndex = FA->getFormatIdx();
2172 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2173 if (MD->isInstance())
2174 --ArgIndex;
2175 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002176
Richard Smithd7293d72013-08-05 18:49:43 +00002177 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002178 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002179 Type, CallType, InFunctionCall,
2180 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002181 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2182 unsigned BuiltinID = FD->getBuiltinID();
2183 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2184 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2185 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002186 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002187 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002188 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002189 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002190 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002191 }
2192 }
Mike Stump11289f42009-09-09 15:08:12 +00002193
Richard Smith55ce3522012-06-25 20:30:08 +00002194 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002195 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002196 case Stmt::ObjCStringLiteralClass:
2197 case Stmt::StringLiteralClass: {
2198 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002199
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002200 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002201 StrE = ObjCFExpr->getString();
2202 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002203 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002204
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002205 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002206 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2207 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002208 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002209 }
Mike Stump11289f42009-09-09 15:08:12 +00002210
Richard Smith55ce3522012-06-25 20:30:08 +00002211 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002212 }
Mike Stump11289f42009-09-09 15:08:12 +00002213
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002214 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002215 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002216 }
2217}
2218
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002219Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002220 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002221 .Case("scanf", FST_Scanf)
2222 .Cases("printf", "printf0", FST_Printf)
2223 .Cases("NSString", "CFString", FST_NSString)
2224 .Case("strftime", FST_Strftime)
2225 .Case("strfmon", FST_Strfmon)
2226 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2227 .Default(FST_Unknown);
2228}
2229
Jordan Rose3e0ec582012-07-19 18:10:23 +00002230/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002231/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002232/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002233bool Sema::CheckFormatArguments(const FormatAttr *Format,
2234 ArrayRef<const Expr *> Args,
2235 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002236 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002237 SourceLocation Loc, SourceRange Range,
2238 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002239 FormatStringInfo FSI;
2240 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002241 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002242 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002243 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002244 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002245}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002246
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002247bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002248 bool HasVAListArg, unsigned format_idx,
2249 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002250 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002251 SourceLocation Loc, SourceRange Range,
2252 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002253 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002254 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002255 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002256 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002257 }
Mike Stump11289f42009-09-09 15:08:12 +00002258
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002259 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002260
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002261 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002262 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002263 // Dynamically generated format strings are difficult to
2264 // automatically vet at compile time. Requiring that format strings
2265 // are string literals: (1) permits the checking of format strings by
2266 // the compiler and thereby (2) can practically remove the source of
2267 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002268
Mike Stump11289f42009-09-09 15:08:12 +00002269 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002270 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002271 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002272 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002273 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002274 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2275 format_idx, firstDataArg, Type, CallType,
2276 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002277 if (CT != SLCT_NotALiteral)
2278 // Literal format string found, check done!
2279 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002280
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002281 // Strftime is particular as it always uses a single 'time' argument,
2282 // so it is safe to pass a non-literal string.
2283 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002284 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002285
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002286 // Do not emit diag when the string param is a macro expansion and the
2287 // format is either NSString or CFString. This is a hack to prevent
2288 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2289 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002290 if (Type == FST_NSString &&
2291 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002292 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002293
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002294 // If there are no arguments specified, warn with -Wformat-security, otherwise
2295 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002296 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002297 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002298 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002299 << OrigFormatExpr->getSourceRange();
2300 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002301 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002302 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002303 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002304 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002305}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002306
Ted Kremenekab278de2010-01-28 23:39:18 +00002307namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002308class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2309protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002310 Sema &S;
2311 const StringLiteral *FExpr;
2312 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002313 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002314 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002315 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002316 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002317 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002318 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002319 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002320 bool usesPositionalArgs;
2321 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002322 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002323 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002324 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002325public:
Ted Kremenek02087932010-07-16 02:11:22 +00002326 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002327 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002328 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002329 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002330 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002331 Sema::VariadicCallType callType,
2332 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002333 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002334 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2335 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002336 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002337 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002338 inFunctionCall(inFunctionCall), CallType(callType),
2339 CheckedVarArgs(CheckedVarArgs) {
2340 CoveredArgs.resize(numDataArgs);
2341 CoveredArgs.reset();
2342 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002343
Ted Kremenek019d2242010-01-29 01:50:07 +00002344 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002345
Ted Kremenek02087932010-07-16 02:11:22 +00002346 void HandleIncompleteSpecifier(const char *startSpecifier,
2347 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002348
Jordan Rose92303592012-09-08 04:00:03 +00002349 void HandleInvalidLengthModifier(
2350 const analyze_format_string::FormatSpecifier &FS,
2351 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002352 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002353
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002354 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002355 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002356 const char *startSpecifier, unsigned specifierLen);
2357
2358 void HandleNonStandardConversionSpecifier(
2359 const analyze_format_string::ConversionSpecifier &CS,
2360 const char *startSpecifier, unsigned specifierLen);
2361
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002362 virtual void HandlePosition(const char *startPos, unsigned posLen);
2363
Ted Kremenekd1668192010-02-27 01:41:03 +00002364 virtual void HandleInvalidPosition(const char *startSpecifier,
2365 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002366 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002367
2368 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2369
Ted Kremenekab278de2010-01-28 23:39:18 +00002370 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002371
Richard Trieu03cf7b72011-10-28 00:41:25 +00002372 template <typename Range>
2373 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2374 const Expr *ArgumentExpr,
2375 PartialDiagnostic PDiag,
2376 SourceLocation StringLoc,
2377 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002378 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002379
Ted Kremenek02087932010-07-16 02:11:22 +00002380protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002381 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2382 const char *startSpec,
2383 unsigned specifierLen,
2384 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002385
2386 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2387 const char *startSpec,
2388 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002389
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002390 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002391 CharSourceRange getSpecifierRange(const char *startSpecifier,
2392 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002393 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002394
Ted Kremenek5739de72010-01-29 01:06:55 +00002395 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002396
2397 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2398 const analyze_format_string::ConversionSpecifier &CS,
2399 const char *startSpecifier, unsigned specifierLen,
2400 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002401
2402 template <typename Range>
2403 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2404 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002405 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002406
2407 void CheckPositionalAndNonpositionalArgs(
2408 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002409};
2410}
2411
Ted Kremenek02087932010-07-16 02:11:22 +00002412SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002413 return OrigFormatExpr->getSourceRange();
2414}
2415
Ted Kremenek02087932010-07-16 02:11:22 +00002416CharSourceRange CheckFormatHandler::
2417getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002418 SourceLocation Start = getLocationOfByte(startSpecifier);
2419 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2420
2421 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002422 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002423
2424 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002425}
2426
Ted Kremenek02087932010-07-16 02:11:22 +00002427SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002428 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002429}
2430
Ted Kremenek02087932010-07-16 02:11:22 +00002431void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2432 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002433 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2434 getLocationOfByte(startSpecifier),
2435 /*IsStringLocation*/true,
2436 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002437}
2438
Jordan Rose92303592012-09-08 04:00:03 +00002439void CheckFormatHandler::HandleInvalidLengthModifier(
2440 const analyze_format_string::FormatSpecifier &FS,
2441 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002442 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002443 using namespace analyze_format_string;
2444
2445 const LengthModifier &LM = FS.getLengthModifier();
2446 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2447
2448 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002449 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002450 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002451 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002452 getLocationOfByte(LM.getStart()),
2453 /*IsStringLocation*/true,
2454 getSpecifierRange(startSpecifier, specifierLen));
2455
2456 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2457 << FixedLM->toString()
2458 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2459
2460 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002461 FixItHint Hint;
2462 if (DiagID == diag::warn_format_nonsensical_length)
2463 Hint = FixItHint::CreateRemoval(LMRange);
2464
2465 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002466 getLocationOfByte(LM.getStart()),
2467 /*IsStringLocation*/true,
2468 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002469 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002470 }
2471}
2472
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002473void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002474 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002475 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002476 using namespace analyze_format_string;
2477
2478 const LengthModifier &LM = FS.getLengthModifier();
2479 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2480
2481 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002482 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002483 if (FixedLM) {
2484 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2485 << LM.toString() << 0,
2486 getLocationOfByte(LM.getStart()),
2487 /*IsStringLocation*/true,
2488 getSpecifierRange(startSpecifier, specifierLen));
2489
2490 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2491 << FixedLM->toString()
2492 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2493
2494 } else {
2495 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2496 << LM.toString() << 0,
2497 getLocationOfByte(LM.getStart()),
2498 /*IsStringLocation*/true,
2499 getSpecifierRange(startSpecifier, specifierLen));
2500 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002501}
2502
2503void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2504 const analyze_format_string::ConversionSpecifier &CS,
2505 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002506 using namespace analyze_format_string;
2507
2508 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002509 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002510 if (FixedCS) {
2511 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2512 << CS.toString() << /*conversion specifier*/1,
2513 getLocationOfByte(CS.getStart()),
2514 /*IsStringLocation*/true,
2515 getSpecifierRange(startSpecifier, specifierLen));
2516
2517 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2518 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2519 << FixedCS->toString()
2520 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2521 } else {
2522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2523 << CS.toString() << /*conversion specifier*/1,
2524 getLocationOfByte(CS.getStart()),
2525 /*IsStringLocation*/true,
2526 getSpecifierRange(startSpecifier, specifierLen));
2527 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002528}
2529
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002530void CheckFormatHandler::HandlePosition(const char *startPos,
2531 unsigned posLen) {
2532 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2533 getLocationOfByte(startPos),
2534 /*IsStringLocation*/true,
2535 getSpecifierRange(startPos, posLen));
2536}
2537
Ted Kremenekd1668192010-02-27 01:41:03 +00002538void
Ted Kremenek02087932010-07-16 02:11:22 +00002539CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2540 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002541 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2542 << (unsigned) p,
2543 getLocationOfByte(startPos), /*IsStringLocation*/true,
2544 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002545}
2546
Ted Kremenek02087932010-07-16 02:11:22 +00002547void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002548 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002549 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2550 getLocationOfByte(startPos),
2551 /*IsStringLocation*/true,
2552 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002553}
2554
Ted Kremenek02087932010-07-16 02:11:22 +00002555void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002556 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002557 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002558 EmitFormatDiagnostic(
2559 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2560 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2561 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002562 }
Ted Kremenek02087932010-07-16 02:11:22 +00002563}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002564
Jordan Rose58bbe422012-07-19 18:10:08 +00002565// Note that this may return NULL if there was an error parsing or building
2566// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002567const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002568 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002569}
2570
2571void CheckFormatHandler::DoneProcessing() {
2572 // Does the number of data arguments exceed the number of
2573 // format conversions in the format string?
2574 if (!HasVAListArg) {
2575 // Find any arguments that weren't covered.
2576 CoveredArgs.flip();
2577 signed notCoveredArg = CoveredArgs.find_first();
2578 if (notCoveredArg >= 0) {
2579 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002580 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2581 SourceLocation Loc = E->getLocStart();
2582 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2583 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2584 Loc, /*IsStringLocation*/false,
2585 getFormatStringRange());
2586 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002587 }
Ted Kremenek02087932010-07-16 02:11:22 +00002588 }
2589 }
2590}
2591
Ted Kremenekce815422010-07-19 21:25:57 +00002592bool
2593CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2594 SourceLocation Loc,
2595 const char *startSpec,
2596 unsigned specifierLen,
2597 const char *csStart,
2598 unsigned csLen) {
2599
2600 bool keepGoing = true;
2601 if (argIndex < NumDataArgs) {
2602 // Consider the argument coverered, even though the specifier doesn't
2603 // make sense.
2604 CoveredArgs.set(argIndex);
2605 }
2606 else {
2607 // If argIndex exceeds the number of data arguments we
2608 // don't issue a warning because that is just a cascade of warnings (and
2609 // they may have intended '%%' anyway). We don't want to continue processing
2610 // the format string after this point, however, as we will like just get
2611 // gibberish when trying to match arguments.
2612 keepGoing = false;
2613 }
2614
Richard Trieu03cf7b72011-10-28 00:41:25 +00002615 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2616 << StringRef(csStart, csLen),
2617 Loc, /*IsStringLocation*/true,
2618 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002619
2620 return keepGoing;
2621}
2622
Richard Trieu03cf7b72011-10-28 00:41:25 +00002623void
2624CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2625 const char *startSpec,
2626 unsigned specifierLen) {
2627 EmitFormatDiagnostic(
2628 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2629 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2630}
2631
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002632bool
2633CheckFormatHandler::CheckNumArgs(
2634 const analyze_format_string::FormatSpecifier &FS,
2635 const analyze_format_string::ConversionSpecifier &CS,
2636 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2637
2638 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002639 PartialDiagnostic PDiag = FS.usesPositionalArg()
2640 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2641 << (argIndex+1) << NumDataArgs)
2642 : S.PDiag(diag::warn_printf_insufficient_data_args);
2643 EmitFormatDiagnostic(
2644 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2645 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002646 return false;
2647 }
2648 return true;
2649}
2650
Richard Trieu03cf7b72011-10-28 00:41:25 +00002651template<typename Range>
2652void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2653 SourceLocation Loc,
2654 bool IsStringLocation,
2655 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002656 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002657 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002658 Loc, IsStringLocation, StringRange, FixIt);
2659}
2660
2661/// \brief If the format string is not within the funcion call, emit a note
2662/// so that the function call and string are in diagnostic messages.
2663///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002664/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002665/// call and only one diagnostic message will be produced. Otherwise, an
2666/// extra note will be emitted pointing to location of the format string.
2667///
2668/// \param ArgumentExpr the expression that is passed as the format string
2669/// argument in the function call. Used for getting locations when two
2670/// diagnostics are emitted.
2671///
2672/// \param PDiag the callee should already have provided any strings for the
2673/// diagnostic message. This function only adds locations and fixits
2674/// to diagnostics.
2675///
2676/// \param Loc primary location for diagnostic. If two diagnostics are
2677/// required, one will be at Loc and a new SourceLocation will be created for
2678/// the other one.
2679///
2680/// \param IsStringLocation if true, Loc points to the format string should be
2681/// used for the note. Otherwise, Loc points to the argument list and will
2682/// be used with PDiag.
2683///
2684/// \param StringRange some or all of the string to highlight. This is
2685/// templated so it can accept either a CharSourceRange or a SourceRange.
2686///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002687/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002688template<typename Range>
2689void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2690 const Expr *ArgumentExpr,
2691 PartialDiagnostic PDiag,
2692 SourceLocation Loc,
2693 bool IsStringLocation,
2694 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002695 ArrayRef<FixItHint> FixIt) {
2696 if (InFunctionCall) {
2697 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2698 D << StringRange;
2699 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2700 I != E; ++I) {
2701 D << *I;
2702 }
2703 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002704 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2705 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002706
2707 const Sema::SemaDiagnosticBuilder &Note =
2708 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2709 diag::note_format_string_defined);
2710
2711 Note << StringRange;
2712 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2713 I != E; ++I) {
2714 Note << *I;
2715 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002716 }
2717}
2718
Ted Kremenek02087932010-07-16 02:11:22 +00002719//===--- CHECK: Printf format string checking ------------------------------===//
2720
2721namespace {
2722class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002723 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002724public:
2725 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2726 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002727 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002728 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002729 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002730 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002731 Sema::VariadicCallType CallType,
2732 llvm::SmallBitVector &CheckedVarArgs)
2733 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2734 numDataArgs, beg, hasVAListArg, Args,
2735 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2736 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002737 {}
2738
Ted Kremenek02087932010-07-16 02:11:22 +00002739
2740 bool HandleInvalidPrintfConversionSpecifier(
2741 const analyze_printf::PrintfSpecifier &FS,
2742 const char *startSpecifier,
2743 unsigned specifierLen);
2744
2745 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2746 const char *startSpecifier,
2747 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002748 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2749 const char *StartSpecifier,
2750 unsigned SpecifierLen,
2751 const Expr *E);
2752
Ted Kremenek02087932010-07-16 02:11:22 +00002753 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2754 const char *startSpecifier, unsigned specifierLen);
2755 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2756 const analyze_printf::OptionalAmount &Amt,
2757 unsigned type,
2758 const char *startSpecifier, unsigned specifierLen);
2759 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2760 const analyze_printf::OptionalFlag &flag,
2761 const char *startSpecifier, unsigned specifierLen);
2762 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2763 const analyze_printf::OptionalFlag &ignoredFlag,
2764 const analyze_printf::OptionalFlag &flag,
2765 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002766 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002767 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002768
Ted Kremenek02087932010-07-16 02:11:22 +00002769};
2770}
2771
2772bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2773 const analyze_printf::PrintfSpecifier &FS,
2774 const char *startSpecifier,
2775 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002776 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002777 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002778
Ted Kremenekce815422010-07-19 21:25:57 +00002779 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2780 getLocationOfByte(CS.getStart()),
2781 startSpecifier, specifierLen,
2782 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002783}
2784
Ted Kremenek02087932010-07-16 02:11:22 +00002785bool CheckPrintfHandler::HandleAmount(
2786 const analyze_format_string::OptionalAmount &Amt,
2787 unsigned k, const char *startSpecifier,
2788 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002789
2790 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002791 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002792 unsigned argIndex = Amt.getArgIndex();
2793 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002794 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2795 << k,
2796 getLocationOfByte(Amt.getStart()),
2797 /*IsStringLocation*/true,
2798 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002799 // Don't do any more checking. We will just emit
2800 // spurious errors.
2801 return false;
2802 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002803
Ted Kremenek5739de72010-01-29 01:06:55 +00002804 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002805 // Although not in conformance with C99, we also allow the argument to be
2806 // an 'unsigned int' as that is a reasonably safe case. GCC also
2807 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002808 CoveredArgs.set(argIndex);
2809 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002810 if (!Arg)
2811 return false;
2812
Ted Kremenek5739de72010-01-29 01:06:55 +00002813 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002814
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002815 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2816 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002817
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002818 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002819 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002820 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002821 << T << Arg->getSourceRange(),
2822 getLocationOfByte(Amt.getStart()),
2823 /*IsStringLocation*/true,
2824 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002825 // Don't do any more checking. We will just emit
2826 // spurious errors.
2827 return false;
2828 }
2829 }
2830 }
2831 return true;
2832}
Ted Kremenek5739de72010-01-29 01:06:55 +00002833
Tom Careb49ec692010-06-17 19:00:27 +00002834void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002835 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002836 const analyze_printf::OptionalAmount &Amt,
2837 unsigned type,
2838 const char *startSpecifier,
2839 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002840 const analyze_printf::PrintfConversionSpecifier &CS =
2841 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002842
Richard Trieu03cf7b72011-10-28 00:41:25 +00002843 FixItHint fixit =
2844 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2845 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2846 Amt.getConstantLength()))
2847 : FixItHint();
2848
2849 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2850 << type << CS.toString(),
2851 getLocationOfByte(Amt.getStart()),
2852 /*IsStringLocation*/true,
2853 getSpecifierRange(startSpecifier, specifierLen),
2854 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002855}
2856
Ted Kremenek02087932010-07-16 02:11:22 +00002857void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002858 const analyze_printf::OptionalFlag &flag,
2859 const char *startSpecifier,
2860 unsigned specifierLen) {
2861 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002862 const analyze_printf::PrintfConversionSpecifier &CS =
2863 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2865 << flag.toString() << CS.toString(),
2866 getLocationOfByte(flag.getPosition()),
2867 /*IsStringLocation*/true,
2868 getSpecifierRange(startSpecifier, specifierLen),
2869 FixItHint::CreateRemoval(
2870 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002871}
2872
2873void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002874 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002875 const analyze_printf::OptionalFlag &ignoredFlag,
2876 const analyze_printf::OptionalFlag &flag,
2877 const char *startSpecifier,
2878 unsigned specifierLen) {
2879 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002880 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2881 << ignoredFlag.toString() << flag.toString(),
2882 getLocationOfByte(ignoredFlag.getPosition()),
2883 /*IsStringLocation*/true,
2884 getSpecifierRange(startSpecifier, specifierLen),
2885 FixItHint::CreateRemoval(
2886 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002887}
2888
Richard Smith55ce3522012-06-25 20:30:08 +00002889// Determines if the specified is a C++ class or struct containing
2890// a member with the specified name and kind (e.g. a CXXMethodDecl named
2891// "c_str()").
2892template<typename MemberKind>
2893static llvm::SmallPtrSet<MemberKind*, 1>
2894CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2895 const RecordType *RT = Ty->getAs<RecordType>();
2896 llvm::SmallPtrSet<MemberKind*, 1> Results;
2897
2898 if (!RT)
2899 return Results;
2900 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002901 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002902 return Results;
2903
2904 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2905 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002906 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002907
2908 // We just need to include all members of the right kind turned up by the
2909 // filter, at this point.
2910 if (S.LookupQualifiedName(R, RT->getDecl()))
2911 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2912 NamedDecl *decl = (*I)->getUnderlyingDecl();
2913 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2914 Results.insert(FK);
2915 }
2916 return Results;
2917}
2918
Richard Smith2868a732014-02-28 01:36:39 +00002919/// Check if we could call '.c_str()' on an object.
2920///
2921/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2922/// allow the call, or if it would be ambiguous).
2923bool Sema::hasCStrMethod(const Expr *E) {
2924 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2925 MethodSet Results =
2926 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2927 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2928 MI != ME; ++MI)
2929 if ((*MI)->getMinRequiredArguments() == 0)
2930 return true;
2931 return false;
2932}
2933
Richard Smith55ce3522012-06-25 20:30:08 +00002934// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002935// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002936// Returns true when a c_str() conversion method is found.
2937bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002938 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002939 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2940
2941 MethodSet Results =
2942 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2943
2944 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2945 MI != ME; ++MI) {
2946 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002947 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002948 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002949 // FIXME: Suggest parens if the expression needs them.
2950 SourceLocation EndLoc =
2951 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2952 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2953 << "c_str()"
2954 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2955 return true;
2956 }
2957 }
2958
2959 return false;
2960}
2961
Ted Kremenekab278de2010-01-28 23:39:18 +00002962bool
Ted Kremenek02087932010-07-16 02:11:22 +00002963CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002964 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002965 const char *startSpecifier,
2966 unsigned specifierLen) {
2967
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002968 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002969 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002970 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002971
Ted Kremenek6cd69422010-07-19 22:01:06 +00002972 if (FS.consumesDataArgument()) {
2973 if (atFirstArg) {
2974 atFirstArg = false;
2975 usesPositionalArgs = FS.usesPositionalArg();
2976 }
2977 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002978 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2979 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002980 return false;
2981 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002982 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002983
Ted Kremenekd1668192010-02-27 01:41:03 +00002984 // First check if the field width, precision, and conversion specifier
2985 // have matching data arguments.
2986 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2987 startSpecifier, specifierLen)) {
2988 return false;
2989 }
2990
2991 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2992 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002993 return false;
2994 }
2995
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002996 if (!CS.consumesDataArgument()) {
2997 // FIXME: Technically specifying a precision or field width here
2998 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002999 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003000 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003001
Ted Kremenek4a49d982010-02-26 19:18:41 +00003002 // Consume the argument.
3003 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003004 if (argIndex < NumDataArgs) {
3005 // The check to see if the argIndex is valid will come later.
3006 // We set the bit here because we may exit early from this
3007 // function if we encounter some other error.
3008 CoveredArgs.set(argIndex);
3009 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003010
3011 // Check for using an Objective-C specific conversion specifier
3012 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003013 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003014 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3015 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003016 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003017
Tom Careb49ec692010-06-17 19:00:27 +00003018 // Check for invalid use of field width
3019 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003020 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003021 startSpecifier, specifierLen);
3022 }
3023
3024 // Check for invalid use of precision
3025 if (!FS.hasValidPrecision()) {
3026 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3027 startSpecifier, specifierLen);
3028 }
3029
3030 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003031 if (!FS.hasValidThousandsGroupingPrefix())
3032 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003033 if (!FS.hasValidLeadingZeros())
3034 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3035 if (!FS.hasValidPlusPrefix())
3036 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003037 if (!FS.hasValidSpacePrefix())
3038 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003039 if (!FS.hasValidAlternativeForm())
3040 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3041 if (!FS.hasValidLeftJustified())
3042 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3043
3044 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003045 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3046 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3047 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003048 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3049 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3050 startSpecifier, specifierLen);
3051
3052 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003053 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003054 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3055 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003056 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003057 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003058 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003059 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3060 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003061
Jordan Rose92303592012-09-08 04:00:03 +00003062 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3063 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3064
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003065 // The remaining checks depend on the data arguments.
3066 if (HasVAListArg)
3067 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003068
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003069 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003070 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003071
Jordan Rose58bbe422012-07-19 18:10:08 +00003072 const Expr *Arg = getDataArg(argIndex);
3073 if (!Arg)
3074 return true;
3075
3076 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003077}
3078
Jordan Roseaee34382012-09-05 22:56:26 +00003079static bool requiresParensToAddCast(const Expr *E) {
3080 // FIXME: We should have a general way to reason about operator
3081 // precedence and whether parens are actually needed here.
3082 // Take care of a few common cases where they aren't.
3083 const Expr *Inside = E->IgnoreImpCasts();
3084 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3085 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3086
3087 switch (Inside->getStmtClass()) {
3088 case Stmt::ArraySubscriptExprClass:
3089 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003090 case Stmt::CharacterLiteralClass:
3091 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003092 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003093 case Stmt::FloatingLiteralClass:
3094 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003095 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003096 case Stmt::ObjCArrayLiteralClass:
3097 case Stmt::ObjCBoolLiteralExprClass:
3098 case Stmt::ObjCBoxedExprClass:
3099 case Stmt::ObjCDictionaryLiteralClass:
3100 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003101 case Stmt::ObjCIvarRefExprClass:
3102 case Stmt::ObjCMessageExprClass:
3103 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003104 case Stmt::ObjCStringLiteralClass:
3105 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003106 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003107 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003108 case Stmt::UnaryOperatorClass:
3109 return false;
3110 default:
3111 return true;
3112 }
3113}
3114
Richard Smith55ce3522012-06-25 20:30:08 +00003115bool
3116CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3117 const char *StartSpecifier,
3118 unsigned SpecifierLen,
3119 const Expr *E) {
3120 using namespace analyze_format_string;
3121 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003122 // Now type check the data expression that matches the
3123 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003124 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3125 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003126 if (!AT.isValid())
3127 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003128
Jordan Rose598ec092012-12-05 18:44:40 +00003129 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003130 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3131 ExprTy = TET->getUnderlyingExpr()->getType();
3132 }
3133
Jordan Rose598ec092012-12-05 18:44:40 +00003134 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003135 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003136
Jordan Rose22b74712012-09-05 22:56:19 +00003137 // Look through argument promotions for our error message's reported type.
3138 // This includes the integral and floating promotions, but excludes array
3139 // and function pointer decay; seeing that an argument intended to be a
3140 // string has type 'char [6]' is probably more confusing than 'char *'.
3141 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3142 if (ICE->getCastKind() == CK_IntegralCast ||
3143 ICE->getCastKind() == CK_FloatingCast) {
3144 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003145 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003146
3147 // Check if we didn't match because of an implicit cast from a 'char'
3148 // or 'short' to an 'int'. This is done because printf is a varargs
3149 // function.
3150 if (ICE->getType() == S.Context.IntTy ||
3151 ICE->getType() == S.Context.UnsignedIntTy) {
3152 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003153 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003154 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003155 }
Jordan Rose98709982012-06-04 22:48:57 +00003156 }
Jordan Rose598ec092012-12-05 18:44:40 +00003157 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3158 // Special case for 'a', which has type 'int' in C.
3159 // Note, however, that we do /not/ want to treat multibyte constants like
3160 // 'MooV' as characters! This form is deprecated but still exists.
3161 if (ExprTy == S.Context.IntTy)
3162 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3163 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003164 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003165
Jordan Rose0e5badd2012-12-05 18:44:49 +00003166 // %C in an Objective-C context prints a unichar, not a wchar_t.
3167 // If the argument is an integer of some kind, believe the %C and suggest
3168 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003169 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003170 if (ObjCContext &&
3171 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3172 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3173 !ExprTy->isCharType()) {
3174 // 'unichar' is defined as a typedef of unsigned short, but we should
3175 // prefer using the typedef if it is visible.
3176 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003177
3178 // While we are here, check if the value is an IntegerLiteral that happens
3179 // to be within the valid range.
3180 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3181 const llvm::APInt &V = IL->getValue();
3182 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3183 return true;
3184 }
3185
Jordan Rose0e5badd2012-12-05 18:44:49 +00003186 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3187 Sema::LookupOrdinaryName);
3188 if (S.LookupName(Result, S.getCurScope())) {
3189 NamedDecl *ND = Result.getFoundDecl();
3190 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3191 if (TD->getUnderlyingType() == IntendedTy)
3192 IntendedTy = S.Context.getTypedefType(TD);
3193 }
3194 }
3195 }
3196
3197 // Special-case some of Darwin's platform-independence types by suggesting
3198 // casts to primitive types that are known to be large enough.
3199 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003200 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003201 // Use a 'while' to peel off layers of typedefs.
3202 QualType TyTy = IntendedTy;
3203 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003204 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003205 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003206 .Case("NSInteger", S.Context.LongTy)
3207 .Case("NSUInteger", S.Context.UnsignedLongTy)
3208 .Case("SInt32", S.Context.IntTy)
3209 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003210 .Default(QualType());
3211
3212 if (!CastTy.isNull()) {
3213 ShouldNotPrintDirectly = true;
3214 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003215 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003216 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003217 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003218 }
3219 }
3220
Jordan Rose22b74712012-09-05 22:56:19 +00003221 // We may be able to offer a FixItHint if it is a supported type.
3222 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003223 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003224 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003225
Jordan Rose22b74712012-09-05 22:56:19 +00003226 if (success) {
3227 // Get the fix string from the fixed format specifier
3228 SmallString<16> buf;
3229 llvm::raw_svector_ostream os(buf);
3230 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003231
Jordan Roseaee34382012-09-05 22:56:26 +00003232 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3233
Jordan Rose0e5badd2012-12-05 18:44:49 +00003234 if (IntendedTy == ExprTy) {
3235 // In this case, the specifier is wrong and should be changed to match
3236 // the argument.
3237 EmitFormatDiagnostic(
3238 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3239 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3240 << E->getSourceRange(),
3241 E->getLocStart(),
3242 /*IsStringLocation*/false,
3243 SpecRange,
3244 FixItHint::CreateReplacement(SpecRange, os.str()));
3245
3246 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003247 // The canonical type for formatting this value is different from the
3248 // actual type of the expression. (This occurs, for example, with Darwin's
3249 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3250 // should be printed as 'long' for 64-bit compatibility.)
3251 // Rather than emitting a normal format/argument mismatch, we want to
3252 // add a cast to the recommended type (and correct the format string
3253 // if necessary).
3254 SmallString<16> CastBuf;
3255 llvm::raw_svector_ostream CastFix(CastBuf);
3256 CastFix << "(";
3257 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3258 CastFix << ")";
3259
3260 SmallVector<FixItHint,4> Hints;
3261 if (!AT.matchesType(S.Context, IntendedTy))
3262 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3263
3264 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3265 // If there's already a cast present, just replace it.
3266 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3267 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3268
3269 } else if (!requiresParensToAddCast(E)) {
3270 // If the expression has high enough precedence,
3271 // just write the C-style cast.
3272 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3273 CastFix.str()));
3274 } else {
3275 // Otherwise, add parens around the expression as well as the cast.
3276 CastFix << "(";
3277 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3278 CastFix.str()));
3279
3280 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3281 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3282 }
3283
Jordan Rose0e5badd2012-12-05 18:44:49 +00003284 if (ShouldNotPrintDirectly) {
3285 // The expression has a type that should not be printed directly.
3286 // We extract the name from the typedef because we don't want to show
3287 // the underlying type in the diagnostic.
3288 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003289
Jordan Rose0e5badd2012-12-05 18:44:49 +00003290 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3291 << Name << IntendedTy
3292 << E->getSourceRange(),
3293 E->getLocStart(), /*IsStringLocation=*/false,
3294 SpecRange, Hints);
3295 } else {
3296 // In this case, the expression could be printed using a different
3297 // specifier, but we've decided that the specifier is probably correct
3298 // and we should cast instead. Just use the normal warning message.
3299 EmitFormatDiagnostic(
3300 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3301 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3302 << E->getSourceRange(),
3303 E->getLocStart(), /*IsStringLocation*/false,
3304 SpecRange, Hints);
3305 }
Jordan Roseaee34382012-09-05 22:56:26 +00003306 }
Jordan Rose22b74712012-09-05 22:56:19 +00003307 } else {
3308 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3309 SpecifierLen);
3310 // Since the warning for passing non-POD types to variadic functions
3311 // was deferred until now, we emit a warning for non-POD
3312 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003313 switch (S.isValidVarArgType(ExprTy)) {
3314 case Sema::VAK_Valid:
3315 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003316 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003317 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3318 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3319 << CSR
3320 << E->getSourceRange(),
3321 E->getLocStart(), /*IsStringLocation*/false, CSR);
3322 break;
3323
3324 case Sema::VAK_Undefined:
3325 EmitFormatDiagnostic(
3326 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003327 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003328 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003329 << CallType
3330 << AT.getRepresentativeTypeName(S.Context)
3331 << CSR
3332 << E->getSourceRange(),
3333 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003334 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003335 break;
3336
3337 case Sema::VAK_Invalid:
3338 if (ExprTy->isObjCObjectType())
3339 EmitFormatDiagnostic(
3340 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3341 << S.getLangOpts().CPlusPlus11
3342 << ExprTy
3343 << CallType
3344 << AT.getRepresentativeTypeName(S.Context)
3345 << CSR
3346 << E->getSourceRange(),
3347 E->getLocStart(), /*IsStringLocation*/false, CSR);
3348 else
3349 // FIXME: If this is an initializer list, suggest removing the braces
3350 // or inserting a cast to the target type.
3351 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3352 << isa<InitListExpr>(E) << ExprTy << CallType
3353 << AT.getRepresentativeTypeName(S.Context)
3354 << E->getSourceRange();
3355 break;
3356 }
3357
3358 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3359 "format string specifier index out of range");
3360 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003361 }
3362
Ted Kremenekab278de2010-01-28 23:39:18 +00003363 return true;
3364}
3365
Ted Kremenek02087932010-07-16 02:11:22 +00003366//===--- CHECK: Scanf format string checking ------------------------------===//
3367
3368namespace {
3369class CheckScanfHandler : public CheckFormatHandler {
3370public:
3371 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3372 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003373 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003374 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003375 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003376 Sema::VariadicCallType CallType,
3377 llvm::SmallBitVector &CheckedVarArgs)
3378 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3379 numDataArgs, beg, hasVAListArg,
3380 Args, formatIdx, inFunctionCall, CallType,
3381 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003382 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003383
3384 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3385 const char *startSpecifier,
3386 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003387
3388 bool HandleInvalidScanfConversionSpecifier(
3389 const analyze_scanf::ScanfSpecifier &FS,
3390 const char *startSpecifier,
3391 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003392
3393 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003394};
Ted Kremenek019d2242010-01-29 01:50:07 +00003395}
Ted Kremenekab278de2010-01-28 23:39:18 +00003396
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003397void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3398 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003399 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3400 getLocationOfByte(end), /*IsStringLocation*/true,
3401 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003402}
3403
Ted Kremenekce815422010-07-19 21:25:57 +00003404bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3405 const analyze_scanf::ScanfSpecifier &FS,
3406 const char *startSpecifier,
3407 unsigned specifierLen) {
3408
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003409 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003410 FS.getConversionSpecifier();
3411
3412 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3413 getLocationOfByte(CS.getStart()),
3414 startSpecifier, specifierLen,
3415 CS.getStart(), CS.getLength());
3416}
3417
Ted Kremenek02087932010-07-16 02:11:22 +00003418bool CheckScanfHandler::HandleScanfSpecifier(
3419 const analyze_scanf::ScanfSpecifier &FS,
3420 const char *startSpecifier,
3421 unsigned specifierLen) {
3422
3423 using namespace analyze_scanf;
3424 using namespace analyze_format_string;
3425
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003426 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003427
Ted Kremenek6cd69422010-07-19 22:01:06 +00003428 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3429 // be used to decide if we are using positional arguments consistently.
3430 if (FS.consumesDataArgument()) {
3431 if (atFirstArg) {
3432 atFirstArg = false;
3433 usesPositionalArgs = FS.usesPositionalArg();
3434 }
3435 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003436 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3437 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003438 return false;
3439 }
Ted Kremenek02087932010-07-16 02:11:22 +00003440 }
3441
3442 // Check if the field with is non-zero.
3443 const OptionalAmount &Amt = FS.getFieldWidth();
3444 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3445 if (Amt.getConstantAmount() == 0) {
3446 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3447 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003448 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3449 getLocationOfByte(Amt.getStart()),
3450 /*IsStringLocation*/true, R,
3451 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003452 }
3453 }
3454
3455 if (!FS.consumesDataArgument()) {
3456 // FIXME: Technically specifying a precision or field width here
3457 // makes no sense. Worth issuing a warning at some point.
3458 return true;
3459 }
3460
3461 // Consume the argument.
3462 unsigned argIndex = FS.getArgIndex();
3463 if (argIndex < NumDataArgs) {
3464 // The check to see if the argIndex is valid will come later.
3465 // We set the bit here because we may exit early from this
3466 // function if we encounter some other error.
3467 CoveredArgs.set(argIndex);
3468 }
3469
Ted Kremenek4407ea42010-07-20 20:04:47 +00003470 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003471 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003472 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3473 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003474 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003475 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003476 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003477 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3478 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003479
Jordan Rose92303592012-09-08 04:00:03 +00003480 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3481 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3482
Ted Kremenek02087932010-07-16 02:11:22 +00003483 // The remaining checks depend on the data arguments.
3484 if (HasVAListArg)
3485 return true;
3486
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003487 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003488 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003489
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003490 // Check that the argument type matches the format specifier.
3491 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003492 if (!Ex)
3493 return true;
3494
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003495 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3496 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003497 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003498 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003499 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003500
3501 if (success) {
3502 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003503 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003504 llvm::raw_svector_ostream os(buf);
3505 fixedFS.toString(os);
3506
3507 EmitFormatDiagnostic(
3508 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003509 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003510 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003511 Ex->getLocStart(),
3512 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003513 getSpecifierRange(startSpecifier, specifierLen),
3514 FixItHint::CreateReplacement(
3515 getSpecifierRange(startSpecifier, specifierLen),
3516 os.str()));
3517 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003518 EmitFormatDiagnostic(
3519 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003520 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003521 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003522 Ex->getLocStart(),
3523 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003524 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003525 }
3526 }
3527
Ted Kremenek02087932010-07-16 02:11:22 +00003528 return true;
3529}
3530
3531void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003532 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003533 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003534 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003535 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003536 bool inFunctionCall, VariadicCallType CallType,
3537 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003538
Ted Kremenekab278de2010-01-28 23:39:18 +00003539 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003540 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003541 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003542 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003543 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3544 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003545 return;
3546 }
Ted Kremenek02087932010-07-16 02:11:22 +00003547
Ted Kremenekab278de2010-01-28 23:39:18 +00003548 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003549 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003550 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003551 // Account for cases where the string literal is truncated in a declaration.
3552 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3553 assert(T && "String literal not of constant array type!");
3554 size_t TypeSize = T->getSize().getZExtValue();
3555 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003556 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003557
3558 // Emit a warning if the string literal is truncated and does not contain an
3559 // embedded null character.
3560 if (TypeSize <= StrRef.size() &&
3561 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3562 CheckFormatHandler::EmitFormatDiagnostic(
3563 *this, inFunctionCall, Args[format_idx],
3564 PDiag(diag::warn_printf_format_string_not_null_terminated),
3565 FExpr->getLocStart(),
3566 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3567 return;
3568 }
3569
Ted Kremenekab278de2010-01-28 23:39:18 +00003570 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003571 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003572 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003573 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003574 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3575 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003576 return;
3577 }
Ted Kremenek02087932010-07-16 02:11:22 +00003578
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003579 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003580 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003581 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003582 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003583 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003584
Hans Wennborg23926bd2011-12-15 10:25:47 +00003585 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003586 getLangOpts(),
3587 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003588 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003589 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003590 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003591 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003592 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003593
Hans Wennborg23926bd2011-12-15 10:25:47 +00003594 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003595 getLangOpts(),
3596 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003597 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003598 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003599}
3600
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003601//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3602
3603// Returns the related absolute value function that is larger, of 0 if one
3604// does not exist.
3605static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3606 switch (AbsFunction) {
3607 default:
3608 return 0;
3609
3610 case Builtin::BI__builtin_abs:
3611 return Builtin::BI__builtin_labs;
3612 case Builtin::BI__builtin_labs:
3613 return Builtin::BI__builtin_llabs;
3614 case Builtin::BI__builtin_llabs:
3615 return 0;
3616
3617 case Builtin::BI__builtin_fabsf:
3618 return Builtin::BI__builtin_fabs;
3619 case Builtin::BI__builtin_fabs:
3620 return Builtin::BI__builtin_fabsl;
3621 case Builtin::BI__builtin_fabsl:
3622 return 0;
3623
3624 case Builtin::BI__builtin_cabsf:
3625 return Builtin::BI__builtin_cabs;
3626 case Builtin::BI__builtin_cabs:
3627 return Builtin::BI__builtin_cabsl;
3628 case Builtin::BI__builtin_cabsl:
3629 return 0;
3630
3631 case Builtin::BIabs:
3632 return Builtin::BIlabs;
3633 case Builtin::BIlabs:
3634 return Builtin::BIllabs;
3635 case Builtin::BIllabs:
3636 return 0;
3637
3638 case Builtin::BIfabsf:
3639 return Builtin::BIfabs;
3640 case Builtin::BIfabs:
3641 return Builtin::BIfabsl;
3642 case Builtin::BIfabsl:
3643 return 0;
3644
3645 case Builtin::BIcabsf:
3646 return Builtin::BIcabs;
3647 case Builtin::BIcabs:
3648 return Builtin::BIcabsl;
3649 case Builtin::BIcabsl:
3650 return 0;
3651 }
3652}
3653
3654// Returns the argument type of the absolute value function.
3655static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3656 unsigned AbsType) {
3657 if (AbsType == 0)
3658 return QualType();
3659
3660 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3661 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3662 if (Error != ASTContext::GE_None)
3663 return QualType();
3664
3665 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3666 if (!FT)
3667 return QualType();
3668
3669 if (FT->getNumParams() != 1)
3670 return QualType();
3671
3672 return FT->getParamType(0);
3673}
3674
3675// Returns the best absolute value function, or zero, based on type and
3676// current absolute value function.
3677static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3678 unsigned AbsFunctionKind) {
3679 unsigned BestKind = 0;
3680 uint64_t ArgSize = Context.getTypeSize(ArgType);
3681 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3682 Kind = getLargerAbsoluteValueFunction(Kind)) {
3683 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3684 if (Context.getTypeSize(ParamType) >= ArgSize) {
3685 if (BestKind == 0)
3686 BestKind = Kind;
3687 else if (Context.hasSameType(ParamType, ArgType)) {
3688 BestKind = Kind;
3689 break;
3690 }
3691 }
3692 }
3693 return BestKind;
3694}
3695
3696enum AbsoluteValueKind {
3697 AVK_Integer,
3698 AVK_Floating,
3699 AVK_Complex
3700};
3701
3702static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3703 if (T->isIntegralOrEnumerationType())
3704 return AVK_Integer;
3705 if (T->isRealFloatingType())
3706 return AVK_Floating;
3707 if (T->isAnyComplexType())
3708 return AVK_Complex;
3709
3710 llvm_unreachable("Type not integer, floating, or complex");
3711}
3712
3713// Changes the absolute value function to a different type. Preserves whether
3714// the function is a builtin.
3715static unsigned changeAbsFunction(unsigned AbsKind,
3716 AbsoluteValueKind ValueKind) {
3717 switch (ValueKind) {
3718 case AVK_Integer:
3719 switch (AbsKind) {
3720 default:
3721 return 0;
3722 case Builtin::BI__builtin_fabsf:
3723 case Builtin::BI__builtin_fabs:
3724 case Builtin::BI__builtin_fabsl:
3725 case Builtin::BI__builtin_cabsf:
3726 case Builtin::BI__builtin_cabs:
3727 case Builtin::BI__builtin_cabsl:
3728 return Builtin::BI__builtin_abs;
3729 case Builtin::BIfabsf:
3730 case Builtin::BIfabs:
3731 case Builtin::BIfabsl:
3732 case Builtin::BIcabsf:
3733 case Builtin::BIcabs:
3734 case Builtin::BIcabsl:
3735 return Builtin::BIabs;
3736 }
3737 case AVK_Floating:
3738 switch (AbsKind) {
3739 default:
3740 return 0;
3741 case Builtin::BI__builtin_abs:
3742 case Builtin::BI__builtin_labs:
3743 case Builtin::BI__builtin_llabs:
3744 case Builtin::BI__builtin_cabsf:
3745 case Builtin::BI__builtin_cabs:
3746 case Builtin::BI__builtin_cabsl:
3747 return Builtin::BI__builtin_fabsf;
3748 case Builtin::BIabs:
3749 case Builtin::BIlabs:
3750 case Builtin::BIllabs:
3751 case Builtin::BIcabsf:
3752 case Builtin::BIcabs:
3753 case Builtin::BIcabsl:
3754 return Builtin::BIfabsf;
3755 }
3756 case AVK_Complex:
3757 switch (AbsKind) {
3758 default:
3759 return 0;
3760 case Builtin::BI__builtin_abs:
3761 case Builtin::BI__builtin_labs:
3762 case Builtin::BI__builtin_llabs:
3763 case Builtin::BI__builtin_fabsf:
3764 case Builtin::BI__builtin_fabs:
3765 case Builtin::BI__builtin_fabsl:
3766 return Builtin::BI__builtin_cabsf;
3767 case Builtin::BIabs:
3768 case Builtin::BIlabs:
3769 case Builtin::BIllabs:
3770 case Builtin::BIfabsf:
3771 case Builtin::BIfabs:
3772 case Builtin::BIfabsl:
3773 return Builtin::BIcabsf;
3774 }
3775 }
3776 llvm_unreachable("Unable to convert function");
3777}
3778
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003779static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003780 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3781 if (!FnInfo)
3782 return 0;
3783
3784 switch (FDecl->getBuiltinID()) {
3785 default:
3786 return 0;
3787 case Builtin::BI__builtin_abs:
3788 case Builtin::BI__builtin_fabs:
3789 case Builtin::BI__builtin_fabsf:
3790 case Builtin::BI__builtin_fabsl:
3791 case Builtin::BI__builtin_labs:
3792 case Builtin::BI__builtin_llabs:
3793 case Builtin::BI__builtin_cabs:
3794 case Builtin::BI__builtin_cabsf:
3795 case Builtin::BI__builtin_cabsl:
3796 case Builtin::BIabs:
3797 case Builtin::BIlabs:
3798 case Builtin::BIllabs:
3799 case Builtin::BIfabs:
3800 case Builtin::BIfabsf:
3801 case Builtin::BIfabsl:
3802 case Builtin::BIcabs:
3803 case Builtin::BIcabsf:
3804 case Builtin::BIcabsl:
3805 return FDecl->getBuiltinID();
3806 }
3807 llvm_unreachable("Unknown Builtin type");
3808}
3809
3810// If the replacement is valid, emit a note with replacement function.
3811// Additionally, suggest including the proper header if not already included.
3812static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3813 unsigned AbsKind) {
3814 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3815
3816 // Look up absolute value function in TU scope.
3817 DeclarationName DN(&S.Context.Idents.get(AbsName));
3818 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
Richard Trieufe771c02014-03-06 02:25:04 +00003819 R.suppressDiagnostics();
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003820 S.LookupName(R, S.TUScope);
3821
3822 // Skip notes if multiple results found in lookup.
3823 if (!R.empty() && !R.isSingleResult())
3824 return;
3825
3826 FunctionDecl *FD = 0;
3827 bool FoundFunction = R.isSingleResult();
3828 // When one result is found, see if it is the correct function.
3829 if (R.isSingleResult()) {
3830 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3831 if (!FD || FD->getBuiltinID() != AbsKind)
3832 return;
3833 }
3834
3835 // Look for local name conflict, prepend "::" as necessary.
3836 R.clear();
3837 S.LookupName(R, S.getCurScope());
3838
3839 if (!FoundFunction) {
3840 if (!R.empty()) {
3841 AbsName = "::" + AbsName;
3842 }
3843 } else { // FoundFunction
3844 if (R.isSingleResult()) {
3845 if (R.getFoundDecl() != FD) {
3846 AbsName = "::" + AbsName;
3847 }
3848 } else if (!R.empty()) {
3849 AbsName = "::" + AbsName;
3850 }
3851 }
3852
3853 S.Diag(Loc, diag::note_replace_abs_function)
3854 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3855
3856 if (!FoundFunction) {
3857 S.Diag(Loc, diag::note_please_include_header)
3858 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3859 << S.Context.BuiltinInfo.GetName(AbsKind);
3860 }
3861}
3862
3863// Warn when using the wrong abs() function.
3864void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3865 const FunctionDecl *FDecl,
3866 IdentifierInfo *FnInfo) {
3867 if (Call->getNumArgs() != 1)
3868 return;
3869
3870 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3871 if (AbsKind == 0)
3872 return;
3873
3874 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3875 QualType ParamType = Call->getArg(0)->getType();
3876
3877 // Unsigned types can not be negative. Suggest to drop the absolute value
3878 // function.
3879 if (ArgType->isUnsignedIntegerType()) {
3880 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3881 Diag(Call->getExprLoc(), diag::note_remove_abs)
3882 << FDecl
3883 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3884 return;
3885 }
3886
3887 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3888 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3889
3890 // The argument and parameter are the same kind. Check if they are the right
3891 // size.
3892 if (ArgValueKind == ParamValueKind) {
3893 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3894 return;
3895
3896 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3897 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3898 << FDecl << ArgType << ParamType;
3899
3900 if (NewAbsKind == 0)
3901 return;
3902
3903 emitReplacement(*this, Call->getExprLoc(),
3904 Call->getCallee()->getSourceRange(), NewAbsKind);
3905 return;
3906 }
3907
3908 // ArgValueKind != ParamValueKind
3909 // The wrong type of absolute value function was used. Attempt to find the
3910 // proper one.
3911 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3912 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3913 if (NewAbsKind == 0)
3914 return;
3915
3916 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3917 << FDecl << ParamValueKind << ArgValueKind;
3918
3919 emitReplacement(*this, Call->getExprLoc(),
3920 Call->getCallee()->getSourceRange(), NewAbsKind);
3921 return;
3922}
3923
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003924//===--- CHECK: Standard memory functions ---------------------------------===//
3925
Nico Weber0e6daef2013-12-26 23:38:39 +00003926/// \brief Takes the expression passed to the size_t parameter of functions
3927/// such as memcmp, strncat, etc and warns if it's a comparison.
3928///
3929/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3930static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3931 IdentifierInfo *FnName,
3932 SourceLocation FnLoc,
3933 SourceLocation RParenLoc) {
3934 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3935 if (!Size)
3936 return false;
3937
3938 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3939 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3940 return false;
3941
3942 Preprocessor &PP = S.getPreprocessor();
3943 SourceRange SizeRange = Size->getSourceRange();
3944 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3945 << SizeRange << FnName;
3946 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3947 << FnName
3948 << FixItHint::CreateInsertion(
3949 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3950 ")")
3951 << FixItHint::CreateRemoval(RParenLoc);
3952 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3953 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3954 << FixItHint::CreateInsertion(
3955 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3956
3957 return true;
3958}
3959
Douglas Gregora74926b2011-05-03 20:05:22 +00003960/// \brief Determine whether the given type is a dynamic class type (e.g.,
3961/// whether it has a vtable).
3962static bool isDynamicClassType(QualType T) {
3963 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3964 if (CXXRecordDecl *Definition = Record->getDefinition())
3965 if (Definition->isDynamicClass())
3966 return true;
3967
3968 return false;
3969}
3970
Chandler Carruth889ed862011-06-21 23:04:20 +00003971/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003972/// otherwise returns NULL.
3973static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003974 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003975 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3976 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3977 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003978
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003979 return 0;
3980}
3981
Chandler Carruth889ed862011-06-21 23:04:20 +00003982/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003983static QualType getSizeOfArgType(const Expr* E) {
3984 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3985 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3986 if (SizeOf->getKind() == clang::UETT_SizeOf)
3987 return SizeOf->getTypeOfArgument();
3988
3989 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003990}
3991
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003992/// \brief Check for dangerous or invalid arguments to memset().
3993///
Chandler Carruthac687262011-06-03 06:23:57 +00003994/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003995/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3996/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003997///
3998/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003999void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004000 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004001 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004002 assert(BId != 0);
4003
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004004 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004005 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004006 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004007 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004008 return;
4009
Anna Zaks22122702012-01-17 00:37:07 +00004010 unsigned LastArg = (BId == Builtin::BImemset ||
4011 BId == Builtin::BIstrndup ? 1 : 2);
4012 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004013 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004014
Nico Weber0e6daef2013-12-26 23:38:39 +00004015 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4016 Call->getLocStart(), Call->getRParenLoc()))
4017 return;
4018
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004019 // We have special checking when the length is a sizeof expression.
4020 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4021 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4022 llvm::FoldingSetNodeID SizeOfArgID;
4023
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004024 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4025 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004026 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004027
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004028 QualType DestTy = Dest->getType();
4029 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4030 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004031
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004032 // Never warn about void type pointers. This can be used to suppress
4033 // false positives.
4034 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004035 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004036
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004037 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4038 // actually comparing the expressions for equality. Because computing the
4039 // expression IDs can be expensive, we only do this if the diagnostic is
4040 // enabled.
4041 if (SizeOfArg &&
4042 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4043 SizeOfArg->getExprLoc())) {
4044 // We only compute IDs for expressions if the warning is enabled, and
4045 // cache the sizeof arg's ID.
4046 if (SizeOfArgID == llvm::FoldingSetNodeID())
4047 SizeOfArg->Profile(SizeOfArgID, Context, true);
4048 llvm::FoldingSetNodeID DestID;
4049 Dest->Profile(DestID, Context, true);
4050 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004051 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4052 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004053 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004054 StringRef ReadableName = FnName->getName();
4055
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004056 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004057 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004058 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004059 if (!PointeeTy->isIncompleteType() &&
4060 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004061 ActionIdx = 2; // If the pointee's size is sizeof(char),
4062 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004063
4064 // If the function is defined as a builtin macro, do not show macro
4065 // expansion.
4066 SourceLocation SL = SizeOfArg->getExprLoc();
4067 SourceRange DSR = Dest->getSourceRange();
4068 SourceRange SSR = SizeOfArg->getSourceRange();
4069 SourceManager &SM = PP.getSourceManager();
4070
4071 if (SM.isMacroArgExpansion(SL)) {
4072 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4073 SL = SM.getSpellingLoc(SL);
4074 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4075 SM.getSpellingLoc(DSR.getEnd()));
4076 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4077 SM.getSpellingLoc(SSR.getEnd()));
4078 }
4079
Anna Zaksd08d9152012-05-30 23:14:52 +00004080 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004081 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004082 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004083 << PointeeTy
4084 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004085 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004086 << SSR);
4087 DiagRuntimeBehavior(SL, SizeOfArg,
4088 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4089 << ActionIdx
4090 << SSR);
4091
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004092 break;
4093 }
4094 }
4095
4096 // Also check for cases where the sizeof argument is the exact same
4097 // type as the memory argument, and where it points to a user-defined
4098 // record type.
4099 if (SizeOfArgTy != QualType()) {
4100 if (PointeeTy->isRecordType() &&
4101 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4102 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4103 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4104 << FnName << SizeOfArgTy << ArgIdx
4105 << PointeeTy << Dest->getSourceRange()
4106 << LenExpr->getSourceRange());
4107 break;
4108 }
Nico Weberc5e73862011-06-14 16:14:58 +00004109 }
4110
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004111 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004112 if (isDynamicClassType(PointeeTy)) {
4113
4114 unsigned OperationType = 0;
4115 // "overwritten" if we're warning about the destination for any call
4116 // but memcmp; otherwise a verb appropriate to the call.
4117 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4118 if (BId == Builtin::BImemcpy)
4119 OperationType = 1;
4120 else if(BId == Builtin::BImemmove)
4121 OperationType = 2;
4122 else if (BId == Builtin::BImemcmp)
4123 OperationType = 3;
4124 }
4125
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004126 DiagRuntimeBehavior(
4127 Dest->getExprLoc(), Dest,
4128 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004129 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004130 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004131 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004132 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004133 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4134 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004135 DiagRuntimeBehavior(
4136 Dest->getExprLoc(), Dest,
4137 PDiag(diag::warn_arc_object_memaccess)
4138 << ArgIdx << FnName << PointeeTy
4139 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004140 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004141 continue;
John McCall31168b02011-06-15 23:02:42 +00004142
4143 DiagRuntimeBehavior(
4144 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004145 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004146 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4147 break;
4148 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004149 }
4150}
4151
Ted Kremenek6865f772011-08-18 20:55:45 +00004152// A little helper routine: ignore addition and subtraction of integer literals.
4153// This intentionally does not ignore all integer constant expressions because
4154// we don't want to remove sizeof().
4155static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4156 Ex = Ex->IgnoreParenCasts();
4157
4158 for (;;) {
4159 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4160 if (!BO || !BO->isAdditiveOp())
4161 break;
4162
4163 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4164 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4165
4166 if (isa<IntegerLiteral>(RHS))
4167 Ex = LHS;
4168 else if (isa<IntegerLiteral>(LHS))
4169 Ex = RHS;
4170 else
4171 break;
4172 }
4173
4174 return Ex;
4175}
4176
Anna Zaks13b08572012-08-08 21:42:23 +00004177static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4178 ASTContext &Context) {
4179 // Only handle constant-sized or VLAs, but not flexible members.
4180 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4181 // Only issue the FIXIT for arrays of size > 1.
4182 if (CAT->getSize().getSExtValue() <= 1)
4183 return false;
4184 } else if (!Ty->isVariableArrayType()) {
4185 return false;
4186 }
4187 return true;
4188}
4189
Ted Kremenek6865f772011-08-18 20:55:45 +00004190// Warn if the user has made the 'size' argument to strlcpy or strlcat
4191// be the size of the source, instead of the destination.
4192void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4193 IdentifierInfo *FnName) {
4194
4195 // Don't crash if the user has the wrong number of arguments
4196 if (Call->getNumArgs() != 3)
4197 return;
4198
4199 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4200 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4201 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004202
4203 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4204 Call->getLocStart(), Call->getRParenLoc()))
4205 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004206
4207 // Look for 'strlcpy(dst, x, sizeof(x))'
4208 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4209 CompareWithSrc = Ex;
4210 else {
4211 // Look for 'strlcpy(dst, x, strlen(x))'
4212 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004213 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4214 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004215 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4216 }
4217 }
4218
4219 if (!CompareWithSrc)
4220 return;
4221
4222 // Determine if the argument to sizeof/strlen is equal to the source
4223 // argument. In principle there's all kinds of things you could do
4224 // here, for instance creating an == expression and evaluating it with
4225 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4226 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4227 if (!SrcArgDRE)
4228 return;
4229
4230 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4231 if (!CompareWithSrcDRE ||
4232 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4233 return;
4234
4235 const Expr *OriginalSizeArg = Call->getArg(2);
4236 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4237 << OriginalSizeArg->getSourceRange() << FnName;
4238
4239 // Output a FIXIT hint if the destination is an array (rather than a
4240 // pointer to an array). This could be enhanced to handle some
4241 // pointers if we know the actual size, like if DstArg is 'array+2'
4242 // we could say 'sizeof(array)-2'.
4243 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004244 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004245 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004246
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004247 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004248 llvm::raw_svector_ostream OS(sizeString);
4249 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004250 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004251 OS << ")";
4252
4253 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4254 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4255 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004256}
4257
Anna Zaks314cd092012-02-01 19:08:57 +00004258/// Check if two expressions refer to the same declaration.
4259static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4260 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4261 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4262 return D1->getDecl() == D2->getDecl();
4263 return false;
4264}
4265
4266static const Expr *getStrlenExprArg(const Expr *E) {
4267 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4268 const FunctionDecl *FD = CE->getDirectCallee();
4269 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4270 return 0;
4271 return CE->getArg(0)->IgnoreParenCasts();
4272 }
4273 return 0;
4274}
4275
4276// Warn on anti-patterns as the 'size' argument to strncat.
4277// The correct size argument should look like following:
4278// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4279void Sema::CheckStrncatArguments(const CallExpr *CE,
4280 IdentifierInfo *FnName) {
4281 // Don't crash if the user has the wrong number of arguments.
4282 if (CE->getNumArgs() < 3)
4283 return;
4284 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4285 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4286 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4287
Nico Weber0e6daef2013-12-26 23:38:39 +00004288 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4289 CE->getRParenLoc()))
4290 return;
4291
Anna Zaks314cd092012-02-01 19:08:57 +00004292 // Identify common expressions, which are wrongly used as the size argument
4293 // to strncat and may lead to buffer overflows.
4294 unsigned PatternType = 0;
4295 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4296 // - sizeof(dst)
4297 if (referToTheSameDecl(SizeOfArg, DstArg))
4298 PatternType = 1;
4299 // - sizeof(src)
4300 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4301 PatternType = 2;
4302 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4303 if (BE->getOpcode() == BO_Sub) {
4304 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4305 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4306 // - sizeof(dst) - strlen(dst)
4307 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4308 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4309 PatternType = 1;
4310 // - sizeof(src) - (anything)
4311 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4312 PatternType = 2;
4313 }
4314 }
4315
4316 if (PatternType == 0)
4317 return;
4318
Anna Zaks5069aa32012-02-03 01:27:37 +00004319 // Generate the diagnostic.
4320 SourceLocation SL = LenArg->getLocStart();
4321 SourceRange SR = LenArg->getSourceRange();
4322 SourceManager &SM = PP.getSourceManager();
4323
4324 // If the function is defined as a builtin macro, do not show macro expansion.
4325 if (SM.isMacroArgExpansion(SL)) {
4326 SL = SM.getSpellingLoc(SL);
4327 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4328 SM.getSpellingLoc(SR.getEnd()));
4329 }
4330
Anna Zaks13b08572012-08-08 21:42:23 +00004331 // Check if the destination is an array (rather than a pointer to an array).
4332 QualType DstTy = DstArg->getType();
4333 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4334 Context);
4335 if (!isKnownSizeArray) {
4336 if (PatternType == 1)
4337 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4338 else
4339 Diag(SL, diag::warn_strncat_src_size) << SR;
4340 return;
4341 }
4342
Anna Zaks314cd092012-02-01 19:08:57 +00004343 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004344 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004345 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004346 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004347
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004348 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004349 llvm::raw_svector_ostream OS(sizeString);
4350 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004351 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004352 OS << ") - ";
4353 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004354 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004355 OS << ") - 1";
4356
Anna Zaks5069aa32012-02-03 01:27:37 +00004357 Diag(SL, diag::note_strncat_wrong_size)
4358 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004359}
4360
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004361//===--- CHECK: Return Address of Stack Variable --------------------------===//
4362
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004363static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4364 Decl *ParentDecl);
4365static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4366 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004367
4368/// CheckReturnStackAddr - Check if a return statement returns the address
4369/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004370static void
4371CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4372 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004373
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004374 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004375 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004376
4377 // Perform checking for returned stack addresses, local blocks,
4378 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004379 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004380 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004381 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004382 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004383 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004384 }
4385
4386 if (stackE == 0)
4387 return; // Nothing suspicious was found.
4388
4389 SourceLocation diagLoc;
4390 SourceRange diagRange;
4391 if (refVars.empty()) {
4392 diagLoc = stackE->getLocStart();
4393 diagRange = stackE->getSourceRange();
4394 } else {
4395 // We followed through a reference variable. 'stackE' contains the
4396 // problematic expression but we will warn at the return statement pointing
4397 // at the reference variable. We will later display the "trail" of
4398 // reference variables using notes.
4399 diagLoc = refVars[0]->getLocStart();
4400 diagRange = refVars[0]->getSourceRange();
4401 }
4402
4403 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004404 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004405 : diag::warn_ret_stack_addr)
4406 << DR->getDecl()->getDeclName() << diagRange;
4407 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004408 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004409 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004410 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004411 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004412 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4413 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004414 << diagRange;
4415 }
4416
4417 // Display the "trail" of reference variables that we followed until we
4418 // found the problematic expression using notes.
4419 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4420 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4421 // If this var binds to another reference var, show the range of the next
4422 // var, otherwise the var binds to the problematic expression, in which case
4423 // show the range of the expression.
4424 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4425 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004426 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4427 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004428 }
4429}
4430
4431/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4432/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004433/// to a location on the stack, a local block, an address of a label, or a
4434/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004435/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004436/// encounter a subexpression that (1) clearly does not lead to one of the
4437/// above problematic expressions (2) is something we cannot determine leads to
4438/// a problematic expression based on such local checking.
4439///
4440/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4441/// the expression that they point to. Such variables are added to the
4442/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004443///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004444/// EvalAddr processes expressions that are pointers that are used as
4445/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004446/// At the base case of the recursion is a check for the above problematic
4447/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004448///
4449/// This implementation handles:
4450///
4451/// * pointer-to-pointer casts
4452/// * implicit conversions from array references to pointers
4453/// * taking the address of fields
4454/// * arbitrary interplay between "&" and "*" operators
4455/// * pointer arithmetic from an address of a stack variable
4456/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004457static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4458 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004459 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004460 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004461
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004462 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004463 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004464 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004465 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004466 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004467
Peter Collingbourne91147592011-04-15 00:35:48 +00004468 E = E->IgnoreParens();
4469
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004470 // Our "symbolic interpreter" is just a dispatch off the currently
4471 // viewed AST node. We then recursively traverse the AST by calling
4472 // EvalAddr and EvalVal appropriately.
4473 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004474 case Stmt::DeclRefExprClass: {
4475 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4476
Richard Smith40f08eb2014-01-30 22:05:38 +00004477 // If we leave the immediate function, the lifetime isn't about to end.
4478 if (DR->refersToEnclosingLocal())
4479 return 0;
4480
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004481 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4482 // If this is a reference variable, follow through to the expression that
4483 // it points to.
4484 if (V->hasLocalStorage() &&
4485 V->getType()->isReferenceType() && V->hasInit()) {
4486 // Add the reference variable to the "trail".
4487 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004488 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004489 }
4490
4491 return NULL;
4492 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004493
Chris Lattner934edb22007-12-28 05:31:15 +00004494 case Stmt::UnaryOperatorClass: {
4495 // The only unary operator that make sense to handle here
4496 // is AddrOf. All others don't make sense as pointers.
4497 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004498
John McCalle3027922010-08-25 11:45:40 +00004499 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004500 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004501 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004502 return NULL;
4503 }
Mike Stump11289f42009-09-09 15:08:12 +00004504
Chris Lattner934edb22007-12-28 05:31:15 +00004505 case Stmt::BinaryOperatorClass: {
4506 // Handle pointer arithmetic. All other binary operators are not valid
4507 // in this context.
4508 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004509 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004510
John McCalle3027922010-08-25 11:45:40 +00004511 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004512 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004513
Chris Lattner934edb22007-12-28 05:31:15 +00004514 Expr *Base = B->getLHS();
4515
4516 // Determine which argument is the real pointer base. It could be
4517 // the RHS argument instead of the LHS.
4518 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004519
Chris Lattner934edb22007-12-28 05:31:15 +00004520 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004521 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004522 }
Steve Naroff2752a172008-09-10 19:17:48 +00004523
Chris Lattner934edb22007-12-28 05:31:15 +00004524 // For conditional operators we need to see if either the LHS or RHS are
4525 // valid DeclRefExpr*s. If one of them is valid, we return it.
4526 case Stmt::ConditionalOperatorClass: {
4527 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004528
Chris Lattner934edb22007-12-28 05:31:15 +00004529 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004530 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4531 if (Expr *LHSExpr = C->getLHS()) {
4532 // In C++, we can have a throw-expression, which has 'void' type.
4533 if (!LHSExpr->getType()->isVoidType())
4534 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004535 return LHS;
4536 }
Chris Lattner934edb22007-12-28 05:31:15 +00004537
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004538 // In C++, we can have a throw-expression, which has 'void' type.
4539 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004540 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004541
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004542 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004543 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004544
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004545 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004546 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004547 return E; // local block.
4548 return NULL;
4549
4550 case Stmt::AddrLabelExprClass:
4551 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004552
John McCall28fc7092011-11-10 05:35:25 +00004553 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004554 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4555 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004556
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004557 // For casts, we need to handle conversions from arrays to
4558 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004559 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004560 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004561 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004562 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004563 case Stmt::CXXStaticCastExprClass:
4564 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004565 case Stmt::CXXConstCastExprClass:
4566 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004567 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4568 switch (cast<CastExpr>(E)->getCastKind()) {
4569 case CK_BitCast:
4570 case CK_LValueToRValue:
4571 case CK_NoOp:
4572 case CK_BaseToDerived:
4573 case CK_DerivedToBase:
4574 case CK_UncheckedDerivedToBase:
4575 case CK_Dynamic:
4576 case CK_CPointerToObjCPointerCast:
4577 case CK_BlockPointerToObjCPointerCast:
4578 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004579 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004580
4581 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004582 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004583
4584 default:
4585 return 0;
4586 }
Chris Lattner934edb22007-12-28 05:31:15 +00004587 }
Mike Stump11289f42009-09-09 15:08:12 +00004588
Douglas Gregorfe314812011-06-21 17:03:29 +00004589 case Stmt::MaterializeTemporaryExprClass:
4590 if (Expr *Result = EvalAddr(
4591 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004592 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004593 return Result;
4594
4595 return E;
4596
Chris Lattner934edb22007-12-28 05:31:15 +00004597 // Everything else: we simply don't reason about them.
4598 default:
4599 return NULL;
4600 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004601}
Mike Stump11289f42009-09-09 15:08:12 +00004602
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004603
4604/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4605/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004606static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4607 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004608do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004609 // We should only be called for evaluating non-pointer expressions, or
4610 // expressions with a pointer type that are not used as references but instead
4611 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004612
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004613 // Our "symbolic interpreter" is just a dispatch off the currently
4614 // viewed AST node. We then recursively traverse the AST by calling
4615 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004616
4617 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004618 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004619 case Stmt::ImplicitCastExprClass: {
4620 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004621 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004622 E = IE->getSubExpr();
4623 continue;
4624 }
4625 return NULL;
4626 }
4627
John McCall28fc7092011-11-10 05:35:25 +00004628 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004629 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004630
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004631 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004632 // When we hit a DeclRefExpr we are looking at code that refers to a
4633 // variable's name. If it's not a reference variable we check if it has
4634 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004635 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004636
Richard Smith40f08eb2014-01-30 22:05:38 +00004637 // If we leave the immediate function, the lifetime isn't about to end.
4638 if (DR->refersToEnclosingLocal())
4639 return 0;
4640
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004641 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4642 // Check if it refers to itself, e.g. "int& i = i;".
4643 if (V == ParentDecl)
4644 return DR;
4645
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004646 if (V->hasLocalStorage()) {
4647 if (!V->getType()->isReferenceType())
4648 return DR;
4649
4650 // Reference variable, follow through to the expression that
4651 // it points to.
4652 if (V->hasInit()) {
4653 // Add the reference variable to the "trail".
4654 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004655 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004656 }
4657 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004658 }
Mike Stump11289f42009-09-09 15:08:12 +00004659
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004660 return NULL;
4661 }
Mike Stump11289f42009-09-09 15:08:12 +00004662
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004663 case Stmt::UnaryOperatorClass: {
4664 // The only unary operator that make sense to handle here
4665 // is Deref. All others don't resolve to a "name." This includes
4666 // handling all sorts of rvalues passed to a unary operator.
4667 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004668
John McCalle3027922010-08-25 11:45:40 +00004669 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004670 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004671
4672 return NULL;
4673 }
Mike Stump11289f42009-09-09 15:08:12 +00004674
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004675 case Stmt::ArraySubscriptExprClass: {
4676 // Array subscripts are potential references to data on the stack. We
4677 // retrieve the DeclRefExpr* for the array variable if it indeed
4678 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004679 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004680 }
Mike Stump11289f42009-09-09 15:08:12 +00004681
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004682 case Stmt::ConditionalOperatorClass: {
4683 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004684 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004685 ConditionalOperator *C = cast<ConditionalOperator>(E);
4686
Anders Carlsson801c5c72007-11-30 19:04:31 +00004687 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004688 if (Expr *LHSExpr = C->getLHS()) {
4689 // In C++, we can have a throw-expression, which has 'void' type.
4690 if (!LHSExpr->getType()->isVoidType())
4691 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4692 return LHS;
4693 }
4694
4695 // In C++, we can have a throw-expression, which has 'void' type.
4696 if (C->getRHS()->getType()->isVoidType())
4697 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004698
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004699 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004700 }
Mike Stump11289f42009-09-09 15:08:12 +00004701
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004702 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004703 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004704 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004705
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004706 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004707 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004708 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004709
4710 // Check whether the member type is itself a reference, in which case
4711 // we're not going to refer to the member, but to what the member refers to.
4712 if (M->getMemberDecl()->getType()->isReferenceType())
4713 return NULL;
4714
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004715 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
Douglas Gregorfe314812011-06-21 17:03:29 +00004718 case Stmt::MaterializeTemporaryExprClass:
4719 if (Expr *Result = EvalVal(
4720 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004721 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004722 return Result;
4723
4724 return E;
4725
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004726 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004727 // Check that we don't return or take the address of a reference to a
4728 // temporary. This is only useful in C++.
4729 if (!E->isTypeDependent() && E->isRValue())
4730 return E;
4731
4732 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004733 return NULL;
4734 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004735} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004736}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004737
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004738void
4739Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4740 SourceLocation ReturnLoc,
4741 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004742 const AttrVec *Attrs,
4743 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004744 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4745
4746 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004747 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4748 CheckNonNullExpr(*this, RetValExp))
4749 Diag(ReturnLoc, diag::warn_null_ret)
4750 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004751
4752 // C++11 [basic.stc.dynamic.allocation]p4:
4753 // If an allocation function declared with a non-throwing
4754 // exception-specification fails to allocate storage, it shall return
4755 // a null pointer. Any other allocation function that fails to allocate
4756 // storage shall indicate failure only by throwing an exception [...]
4757 if (FD) {
4758 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4759 if (Op == OO_New || Op == OO_Array_New) {
4760 const FunctionProtoType *Proto
4761 = FD->getType()->castAs<FunctionProtoType>();
4762 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4763 CheckNonNullExpr(*this, RetValExp))
4764 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4765 << FD << getLangOpts().CPlusPlus11;
4766 }
4767 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004768}
4769
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004770//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4771
4772/// Check for comparisons of floating point operands using != and ==.
4773/// Issue a warning if these are no self-comparisons, as they are not likely
4774/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004775void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004776 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4777 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004778
4779 // Special case: check for x == x (which is OK).
4780 // Do not emit warnings for such cases.
4781 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4782 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4783 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004784 return;
Mike Stump11289f42009-09-09 15:08:12 +00004785
4786
Ted Kremenekeda40e22007-11-29 00:59:04 +00004787 // Special case: check for comparisons against literals that can be exactly
4788 // represented by APFloat. In such cases, do not emit a warning. This
4789 // is a heuristic: often comparison against such literals are used to
4790 // detect if a value in a variable has not changed. This clearly can
4791 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004792 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4793 if (FLL->isExact())
4794 return;
4795 } else
4796 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4797 if (FLR->isExact())
4798 return;
Mike Stump11289f42009-09-09 15:08:12 +00004799
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004800 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004801 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004802 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004803 return;
Mike Stump11289f42009-09-09 15:08:12 +00004804
David Blaikie1f4ff152012-07-16 20:47:22 +00004805 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004806 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004807 return;
Mike Stump11289f42009-09-09 15:08:12 +00004808
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004809 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004810 Diag(Loc, diag::warn_floatingpoint_eq)
4811 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004812}
John McCallca01b222010-01-04 23:21:16 +00004813
John McCall70aa5392010-01-06 05:24:50 +00004814//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4815//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004816
John McCall70aa5392010-01-06 05:24:50 +00004817namespace {
John McCallca01b222010-01-04 23:21:16 +00004818
John McCall70aa5392010-01-06 05:24:50 +00004819/// Structure recording the 'active' range of an integer-valued
4820/// expression.
4821struct IntRange {
4822 /// The number of bits active in the int.
4823 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004824
John McCall70aa5392010-01-06 05:24:50 +00004825 /// True if the int is known not to have negative values.
4826 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004827
John McCall70aa5392010-01-06 05:24:50 +00004828 IntRange(unsigned Width, bool NonNegative)
4829 : Width(Width), NonNegative(NonNegative)
4830 {}
John McCallca01b222010-01-04 23:21:16 +00004831
John McCall817d4af2010-11-10 23:38:19 +00004832 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004833 static IntRange forBoolType() {
4834 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004835 }
4836
John McCall817d4af2010-11-10 23:38:19 +00004837 /// Returns the range of an opaque value of the given integral type.
4838 static IntRange forValueOfType(ASTContext &C, QualType T) {
4839 return forValueOfCanonicalType(C,
4840 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004841 }
4842
John McCall817d4af2010-11-10 23:38:19 +00004843 /// Returns the range of an opaque value of a canonical integral type.
4844 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004845 assert(T->isCanonicalUnqualified());
4846
4847 if (const VectorType *VT = dyn_cast<VectorType>(T))
4848 T = VT->getElementType().getTypePtr();
4849 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4850 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004851
David Majnemer6a426652013-06-07 22:07:20 +00004852 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004853 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004854 EnumDecl *Enum = ET->getDecl();
4855 if (!Enum->isCompleteDefinition())
4856 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004857
David Majnemer6a426652013-06-07 22:07:20 +00004858 unsigned NumPositive = Enum->getNumPositiveBits();
4859 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004860
David Majnemer6a426652013-06-07 22:07:20 +00004861 if (NumNegative == 0)
4862 return IntRange(NumPositive, true/*NonNegative*/);
4863 else
4864 return IntRange(std::max(NumPositive + 1, NumNegative),
4865 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004866 }
John McCall70aa5392010-01-06 05:24:50 +00004867
4868 const BuiltinType *BT = cast<BuiltinType>(T);
4869 assert(BT->isInteger());
4870
4871 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4872 }
4873
John McCall817d4af2010-11-10 23:38:19 +00004874 /// Returns the "target" range of a canonical integral type, i.e.
4875 /// the range of values expressible in the type.
4876 ///
4877 /// This matches forValueOfCanonicalType except that enums have the
4878 /// full range of their type, not the range of their enumerators.
4879 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4880 assert(T->isCanonicalUnqualified());
4881
4882 if (const VectorType *VT = dyn_cast<VectorType>(T))
4883 T = VT->getElementType().getTypePtr();
4884 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4885 T = CT->getElementType().getTypePtr();
4886 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004887 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004888
4889 const BuiltinType *BT = cast<BuiltinType>(T);
4890 assert(BT->isInteger());
4891
4892 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4893 }
4894
4895 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004896 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004897 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004898 L.NonNegative && R.NonNegative);
4899 }
4900
John McCall817d4af2010-11-10 23:38:19 +00004901 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004902 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004903 return IntRange(std::min(L.Width, R.Width),
4904 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004905 }
4906};
4907
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004908static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4909 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004910 if (value.isSigned() && value.isNegative())
4911 return IntRange(value.getMinSignedBits(), false);
4912
4913 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004914 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004915
4916 // isNonNegative() just checks the sign bit without considering
4917 // signedness.
4918 return IntRange(value.getActiveBits(), true);
4919}
4920
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004921static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4922 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004923 if (result.isInt())
4924 return GetValueRange(C, result.getInt(), MaxWidth);
4925
4926 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004927 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4928 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4929 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4930 R = IntRange::join(R, El);
4931 }
John McCall70aa5392010-01-06 05:24:50 +00004932 return R;
4933 }
4934
4935 if (result.isComplexInt()) {
4936 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4937 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4938 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004939 }
4940
4941 // This can happen with lossless casts to intptr_t of "based" lvalues.
4942 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004943 // FIXME: The only reason we need to pass the type in here is to get
4944 // the sign right on this one case. It would be nice if APValue
4945 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004946 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004947 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004948}
John McCall70aa5392010-01-06 05:24:50 +00004949
Eli Friedmane6d33952013-07-08 20:20:06 +00004950static QualType GetExprType(Expr *E) {
4951 QualType Ty = E->getType();
4952 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4953 Ty = AtomicRHS->getValueType();
4954 return Ty;
4955}
4956
John McCall70aa5392010-01-06 05:24:50 +00004957/// Pseudo-evaluate the given integer expression, estimating the
4958/// range of values it might take.
4959///
4960/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004961static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004962 E = E->IgnoreParens();
4963
4964 // Try a full evaluation first.
4965 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004966 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004967 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004968
4969 // I think we only want to look through implicit casts here; if the
4970 // user has an explicit widening cast, we should treat the value as
4971 // being of the new, wider type.
4972 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004973 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004974 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4975
Eli Friedmane6d33952013-07-08 20:20:06 +00004976 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004977
John McCalle3027922010-08-25 11:45:40 +00004978 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004979
John McCall70aa5392010-01-06 05:24:50 +00004980 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004981 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004982 return OutputTypeRange;
4983
4984 IntRange SubRange
4985 = GetExprRange(C, CE->getSubExpr(),
4986 std::min(MaxWidth, OutputTypeRange.Width));
4987
4988 // Bail out if the subexpr's range is as wide as the cast type.
4989 if (SubRange.Width >= OutputTypeRange.Width)
4990 return OutputTypeRange;
4991
4992 // Otherwise, we take the smaller width, and we're non-negative if
4993 // either the output type or the subexpr is.
4994 return IntRange(SubRange.Width,
4995 SubRange.NonNegative || OutputTypeRange.NonNegative);
4996 }
4997
4998 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4999 // If we can fold the condition, just take that operand.
5000 bool CondResult;
5001 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5002 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5003 : CO->getFalseExpr(),
5004 MaxWidth);
5005
5006 // Otherwise, conservatively merge.
5007 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5008 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5009 return IntRange::join(L, R);
5010 }
5011
5012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5013 switch (BO->getOpcode()) {
5014
5015 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005016 case BO_LAnd:
5017 case BO_LOr:
5018 case BO_LT:
5019 case BO_GT:
5020 case BO_LE:
5021 case BO_GE:
5022 case BO_EQ:
5023 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005024 return IntRange::forBoolType();
5025
John McCallc3688382011-07-13 06:35:24 +00005026 // The type of the assignments is the type of the LHS, so the RHS
5027 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005028 case BO_MulAssign:
5029 case BO_DivAssign:
5030 case BO_RemAssign:
5031 case BO_AddAssign:
5032 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005033 case BO_XorAssign:
5034 case BO_OrAssign:
5035 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005036 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005037
John McCallc3688382011-07-13 06:35:24 +00005038 // Simple assignments just pass through the RHS, which will have
5039 // been coerced to the LHS type.
5040 case BO_Assign:
5041 // TODO: bitfields?
5042 return GetExprRange(C, BO->getRHS(), MaxWidth);
5043
John McCall70aa5392010-01-06 05:24:50 +00005044 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005045 case BO_PtrMemD:
5046 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005047 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005048
John McCall2ce81ad2010-01-06 22:07:33 +00005049 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005050 case BO_And:
5051 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005052 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5053 GetExprRange(C, BO->getRHS(), MaxWidth));
5054
John McCall70aa5392010-01-06 05:24:50 +00005055 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005056 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005057 // ...except that we want to treat '1 << (blah)' as logically
5058 // positive. It's an important idiom.
5059 if (IntegerLiteral *I
5060 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5061 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005062 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005063 return IntRange(R.Width, /*NonNegative*/ true);
5064 }
5065 }
5066 // fallthrough
5067
John McCalle3027922010-08-25 11:45:40 +00005068 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005069 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005070
John McCall2ce81ad2010-01-06 22:07:33 +00005071 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005072 case BO_Shr:
5073 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005074 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5075
5076 // If the shift amount is a positive constant, drop the width by
5077 // that much.
5078 llvm::APSInt shift;
5079 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5080 shift.isNonNegative()) {
5081 unsigned zext = shift.getZExtValue();
5082 if (zext >= L.Width)
5083 L.Width = (L.NonNegative ? 0 : 1);
5084 else
5085 L.Width -= zext;
5086 }
5087
5088 return L;
5089 }
5090
5091 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005092 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005093 return GetExprRange(C, BO->getRHS(), MaxWidth);
5094
John McCall2ce81ad2010-01-06 22:07:33 +00005095 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005096 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005097 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005098 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005099 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005100
John McCall51431812011-07-14 22:39:48 +00005101 // The width of a division result is mostly determined by the size
5102 // of the LHS.
5103 case BO_Div: {
5104 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005105 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005106 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5107
5108 // If the divisor is constant, use that.
5109 llvm::APSInt divisor;
5110 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5111 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5112 if (log2 >= L.Width)
5113 L.Width = (L.NonNegative ? 0 : 1);
5114 else
5115 L.Width = std::min(L.Width - log2, MaxWidth);
5116 return L;
5117 }
5118
5119 // Otherwise, just use the LHS's width.
5120 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5121 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5122 }
5123
5124 // The result of a remainder can't be larger than the result of
5125 // either side.
5126 case BO_Rem: {
5127 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005128 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005129 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5130 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5131
5132 IntRange meet = IntRange::meet(L, R);
5133 meet.Width = std::min(meet.Width, MaxWidth);
5134 return meet;
5135 }
5136
5137 // The default behavior is okay for these.
5138 case BO_Mul:
5139 case BO_Add:
5140 case BO_Xor:
5141 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005142 break;
5143 }
5144
John McCall51431812011-07-14 22:39:48 +00005145 // The default case is to treat the operation as if it were closed
5146 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005147 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5148 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5149 return IntRange::join(L, R);
5150 }
5151
5152 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5153 switch (UO->getOpcode()) {
5154 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005155 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005156 return IntRange::forBoolType();
5157
5158 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005159 case UO_Deref:
5160 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005161 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005162
5163 default:
5164 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5165 }
5166 }
5167
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005168 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5169 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5170
John McCalld25db7e2013-05-06 21:39:12 +00005171 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005172 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005173 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005174
Eli Friedmane6d33952013-07-08 20:20:06 +00005175 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005176}
John McCall263a48b2010-01-04 23:31:57 +00005177
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005178static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005179 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005180}
5181
John McCall263a48b2010-01-04 23:31:57 +00005182/// Checks whether the given value, which currently has the given
5183/// source semantics, has the same value when coerced through the
5184/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005185static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5186 const llvm::fltSemantics &Src,
5187 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005188 llvm::APFloat truncated = value;
5189
5190 bool ignored;
5191 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5192 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5193
5194 return truncated.bitwiseIsEqual(value);
5195}
5196
5197/// Checks whether the given value, which currently has the given
5198/// source semantics, has the same value when coerced through the
5199/// target semantics.
5200///
5201/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005202static bool IsSameFloatAfterCast(const APValue &value,
5203 const llvm::fltSemantics &Src,
5204 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005205 if (value.isFloat())
5206 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5207
5208 if (value.isVector()) {
5209 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5210 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5211 return false;
5212 return true;
5213 }
5214
5215 assert(value.isComplexFloat());
5216 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5217 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5218}
5219
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005220static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005221
Ted Kremenek6274be42010-09-23 21:43:44 +00005222static bool IsZero(Sema &S, Expr *E) {
5223 // Suppress cases where we are comparing against an enum constant.
5224 if (const DeclRefExpr *DR =
5225 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5226 if (isa<EnumConstantDecl>(DR->getDecl()))
5227 return false;
5228
5229 // Suppress cases where the '0' value is expanded from a macro.
5230 if (E->getLocStart().isMacroID())
5231 return false;
5232
John McCallcc7e5bf2010-05-06 08:58:33 +00005233 llvm::APSInt Value;
5234 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5235}
5236
John McCall2551c1b2010-10-06 00:25:24 +00005237static bool HasEnumType(Expr *E) {
5238 // Strip off implicit integral promotions.
5239 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005240 if (ICE->getCastKind() != CK_IntegralCast &&
5241 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005242 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005243 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005244 }
5245
5246 return E->getType()->isEnumeralType();
5247}
5248
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005249static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005250 // Disable warning in template instantiations.
5251 if (!S.ActiveTemplateInstantiations.empty())
5252 return;
5253
John McCalle3027922010-08-25 11:45:40 +00005254 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005255 if (E->isValueDependent())
5256 return;
5257
John McCalle3027922010-08-25 11:45:40 +00005258 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005259 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005260 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005261 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005262 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005263 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005264 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005265 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005266 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005267 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005268 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005269 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005270 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005271 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005272 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005273 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5274 }
5275}
5276
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005277static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005278 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005279 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005280 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005281 // Disable warning in template instantiations.
5282 if (!S.ActiveTemplateInstantiations.empty())
5283 return;
5284
Richard Trieu560910c2012-11-14 22:50:24 +00005285 // 0 values are handled later by CheckTrivialUnsignedComparison().
5286 if (Value == 0)
5287 return;
5288
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005289 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005290 QualType OtherT = Other->getType();
5291 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005292 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005293 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005294 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005295 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005296 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00005297
5298 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00005299 bool CommonSigned = CommonT->isSignedIntegerType();
5300
5301 bool EqualityOnly = false;
5302
5303 // TODO: Investigate using GetExprRange() to get tighter bounds on
5304 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005305 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00005306 unsigned OtherWidth = OtherRange.Width;
5307
5308 if (CommonSigned) {
5309 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00005310 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005311 // Check that the constant is representable in type OtherT.
5312 if (ConstantSigned) {
5313 if (OtherWidth >= Value.getMinSignedBits())
5314 return;
5315 } else { // !ConstantSigned
5316 if (OtherWidth >= Value.getActiveBits() + 1)
5317 return;
5318 }
5319 } else { // !OtherSigned
5320 // Check that the constant is representable in type OtherT.
5321 // Negative values are out of range.
5322 if (ConstantSigned) {
5323 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5324 return;
5325 } else { // !ConstantSigned
5326 if (OtherWidth >= Value.getActiveBits())
5327 return;
5328 }
5329 }
5330 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00005331 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005332 if (OtherWidth >= Value.getActiveBits())
5333 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00005334 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00005335 // Check to see if the constant is representable in OtherT.
5336 if (OtherWidth > Value.getActiveBits())
5337 return;
5338 // Check to see if the constant is equivalent to a negative value
5339 // cast to CommonT.
5340 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005341 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005342 return;
5343 // The constant value rests between values that OtherT can represent after
5344 // conversion. Relational comparison still works, but equality
5345 // comparisons will be tautological.
5346 EqualityOnly = true;
5347 } else { // OtherSigned && ConstantSigned
5348 assert(0 && "Two signed types converted to unsigned types.");
5349 }
5350 }
5351
5352 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5353
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005354 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005355 if (op == BO_EQ || op == BO_NE) {
5356 IsTrue = op == BO_NE;
5357 } else if (EqualityOnly) {
5358 return;
5359 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005360 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005361 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005362 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005363 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005364 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005365 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005366 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005367 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005368 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005369 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005370
5371 // If this is a comparison to an enum constant, include that
5372 // constant in the diagnostic.
5373 const EnumConstantDecl *ED = 0;
5374 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5375 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5376
5377 SmallString<64> PrettySourceValue;
5378 llvm::raw_svector_ostream OS(PrettySourceValue);
5379 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005380 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005381 else
5382 OS << Value;
5383
Richard Trieuc38786b2014-01-10 04:38:09 +00005384 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5385 S.PDiag(diag::warn_out_of_range_compare)
5386 << OS.str() << OtherT << IsTrue
5387 << E->getLHS()->getSourceRange()
5388 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005389}
5390
John McCallcc7e5bf2010-05-06 08:58:33 +00005391/// Analyze the operands of the given comparison. Implements the
5392/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005393static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005394 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5395 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005396}
John McCall263a48b2010-01-04 23:31:57 +00005397
John McCallca01b222010-01-04 23:21:16 +00005398/// \brief Implements -Wsign-compare.
5399///
Richard Trieu82402a02011-09-15 21:56:47 +00005400/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005401static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005402 // The type the comparison is being performed in.
5403 QualType T = E->getLHS()->getType();
5404 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5405 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005406 if (E->isValueDependent())
5407 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005408
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005409 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5410 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005411
5412 bool IsComparisonConstant = false;
5413
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005414 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005415 // of 'true' or 'false'.
5416 if (T->isIntegralType(S.Context)) {
5417 llvm::APSInt RHSValue;
5418 bool IsRHSIntegralLiteral =
5419 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5420 llvm::APSInt LHSValue;
5421 bool IsLHSIntegralLiteral =
5422 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5423 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5424 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5425 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5426 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5427 else
5428 IsComparisonConstant =
5429 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005430 } else if (!T->hasUnsignedIntegerRepresentation())
5431 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005432
John McCallcc7e5bf2010-05-06 08:58:33 +00005433 // We don't do anything special if this isn't an unsigned integral
5434 // comparison: we're only interested in integral comparisons, and
5435 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005436 //
5437 // We also don't care about value-dependent expressions or expressions
5438 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005439 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005440 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005441
John McCallcc7e5bf2010-05-06 08:58:33 +00005442 // Check to see if one of the (unmodified) operands is of different
5443 // signedness.
5444 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005445 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5446 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005447 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005448 signedOperand = LHS;
5449 unsignedOperand = RHS;
5450 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5451 signedOperand = RHS;
5452 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005453 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005454 CheckTrivialUnsignedComparison(S, E);
5455 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005456 }
5457
John McCallcc7e5bf2010-05-06 08:58:33 +00005458 // Otherwise, calculate the effective range of the signed operand.
5459 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005460
John McCallcc7e5bf2010-05-06 08:58:33 +00005461 // Go ahead and analyze implicit conversions in the operands. Note
5462 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005463 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5464 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005465
John McCallcc7e5bf2010-05-06 08:58:33 +00005466 // If the signed range is non-negative, -Wsign-compare won't fire,
5467 // but we should still check for comparisons which are always true
5468 // or false.
5469 if (signedRange.NonNegative)
5470 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005471
5472 // For (in)equality comparisons, if the unsigned operand is a
5473 // constant which cannot collide with a overflowed signed operand,
5474 // then reinterpreting the signed operand as unsigned will not
5475 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005476 if (E->isEqualityOp()) {
5477 unsigned comparisonWidth = S.Context.getIntWidth(T);
5478 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005479
John McCallcc7e5bf2010-05-06 08:58:33 +00005480 // We should never be unable to prove that the unsigned operand is
5481 // non-negative.
5482 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5483
5484 if (unsignedRange.Width < comparisonWidth)
5485 return;
5486 }
5487
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005488 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5489 S.PDiag(diag::warn_mixed_sign_comparison)
5490 << LHS->getType() << RHS->getType()
5491 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005492}
5493
John McCall1f425642010-11-11 03:21:53 +00005494/// Analyzes an attempt to assign the given value to a bitfield.
5495///
5496/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005497static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5498 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005499 assert(Bitfield->isBitField());
5500 if (Bitfield->isInvalidDecl())
5501 return false;
5502
John McCalldeebbcf2010-11-11 05:33:51 +00005503 // White-list bool bitfields.
5504 if (Bitfield->getType()->isBooleanType())
5505 return false;
5506
Douglas Gregor789adec2011-02-04 13:09:01 +00005507 // Ignore value- or type-dependent expressions.
5508 if (Bitfield->getBitWidth()->isValueDependent() ||
5509 Bitfield->getBitWidth()->isTypeDependent() ||
5510 Init->isValueDependent() ||
5511 Init->isTypeDependent())
5512 return false;
5513
John McCall1f425642010-11-11 03:21:53 +00005514 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5515
Richard Smith5fab0c92011-12-28 19:48:30 +00005516 llvm::APSInt Value;
5517 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005518 return false;
5519
John McCall1f425642010-11-11 03:21:53 +00005520 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005521 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005522
5523 if (OriginalWidth <= FieldWidth)
5524 return false;
5525
Eli Friedmanc267a322012-01-26 23:11:39 +00005526 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005527 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005528 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005529
Eli Friedmanc267a322012-01-26 23:11:39 +00005530 // Check whether the stored value is equal to the original value.
5531 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005532 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005533 return false;
5534
Eli Friedmanc267a322012-01-26 23:11:39 +00005535 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005536 // therefore don't strictly fit into a signed bitfield of width 1.
5537 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005538 return false;
5539
John McCall1f425642010-11-11 03:21:53 +00005540 std::string PrettyValue = Value.toString(10);
5541 std::string PrettyTrunc = TruncatedValue.toString(10);
5542
5543 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5544 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5545 << Init->getSourceRange();
5546
5547 return true;
5548}
5549
John McCalld2a53122010-11-09 23:24:47 +00005550/// Analyze the given simple or compound assignment for warning-worthy
5551/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005552static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005553 // Just recurse on the LHS.
5554 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5555
5556 // We want to recurse on the RHS as normal unless we're assigning to
5557 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005558 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005559 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005560 E->getOperatorLoc())) {
5561 // Recurse, ignoring any implicit conversions on the RHS.
5562 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5563 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005564 }
5565 }
5566
5567 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5568}
5569
John McCall263a48b2010-01-04 23:31:57 +00005570/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005571static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005572 SourceLocation CContext, unsigned diag,
5573 bool pruneControlFlow = false) {
5574 if (pruneControlFlow) {
5575 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5576 S.PDiag(diag)
5577 << SourceType << T << E->getSourceRange()
5578 << SourceRange(CContext));
5579 return;
5580 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005581 S.Diag(E->getExprLoc(), diag)
5582 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5583}
5584
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005585/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005586static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005587 SourceLocation CContext, unsigned diag,
5588 bool pruneControlFlow = false) {
5589 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005590}
5591
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005592/// Diagnose an implicit cast from a literal expression. Does not warn when the
5593/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005594void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5595 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005596 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005597 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005598 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005599 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5600 T->hasUnsignedIntegerRepresentation());
5601 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005602 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005603 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005604 return;
5605
Eli Friedman07185912013-08-29 23:44:43 +00005606 // FIXME: Force the precision of the source value down so we don't print
5607 // digits which are usually useless (we don't really care here if we
5608 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5609 // would automatically print the shortest representation, but it's a bit
5610 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005611 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005612 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5613 precision = (precision * 59 + 195) / 196;
5614 Value.toString(PrettySourceValue, precision);
5615
David Blaikie9b88cc02012-05-15 17:18:27 +00005616 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005617 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5618 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5619 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005620 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005621
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005622 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005623 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5624 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005625}
5626
John McCall18a2c2c2010-11-09 22:22:12 +00005627std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5628 if (!Range.Width) return "0";
5629
5630 llvm::APSInt ValueInRange = Value;
5631 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005632 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005633 return ValueInRange.toString(10);
5634}
5635
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005636static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5637 if (!isa<ImplicitCastExpr>(Ex))
5638 return false;
5639
5640 Expr *InnerE = Ex->IgnoreParenImpCasts();
5641 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5642 const Type *Source =
5643 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5644 if (Target->isDependentType())
5645 return false;
5646
5647 const BuiltinType *FloatCandidateBT =
5648 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5649 const Type *BoolCandidateType = ToBool ? Target : Source;
5650
5651 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5652 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5653}
5654
5655void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5656 SourceLocation CC) {
5657 unsigned NumArgs = TheCall->getNumArgs();
5658 for (unsigned i = 0; i < NumArgs; ++i) {
5659 Expr *CurrA = TheCall->getArg(i);
5660 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5661 continue;
5662
5663 bool IsSwapped = ((i > 0) &&
5664 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5665 IsSwapped |= ((i < (NumArgs - 1)) &&
5666 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5667 if (IsSwapped) {
5668 // Warn on this floating-point to bool conversion.
5669 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5670 CurrA->getType(), CC,
5671 diag::warn_impcast_floating_point_to_bool);
5672 }
5673 }
5674}
5675
John McCallcc7e5bf2010-05-06 08:58:33 +00005676void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005677 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005678 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005679
John McCallcc7e5bf2010-05-06 08:58:33 +00005680 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5681 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5682 if (Source == Target) return;
5683 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005684
Chandler Carruthc22845a2011-07-26 05:40:03 +00005685 // If the conversion context location is invalid don't complain. We also
5686 // don't want to emit a warning if the issue occurs from the expansion of
5687 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5688 // delay this check as long as possible. Once we detect we are in that
5689 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005690 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005691 return;
5692
Richard Trieu021baa32011-09-23 20:10:00 +00005693 // Diagnose implicit casts to bool.
5694 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5695 if (isa<StringLiteral>(E))
5696 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005697 // and expressions, for instance, assert(0 && "error here"), are
5698 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005699 return DiagnoseImpCast(S, E, T, CC,
5700 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005701 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5702 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5703 // This covers the literal expressions that evaluate to Objective-C
5704 // objects.
5705 return DiagnoseImpCast(S, E, T, CC,
5706 diag::warn_impcast_objective_c_literal_to_bool);
5707 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005708 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5709 // Warn on pointer to bool conversion that is always true.
5710 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5711 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005712 }
Richard Trieu021baa32011-09-23 20:10:00 +00005713 }
John McCall263a48b2010-01-04 23:31:57 +00005714
5715 // Strip vector types.
5716 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005717 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005718 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005719 return;
John McCallacf0ee52010-10-08 02:01:28 +00005720 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005721 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005722
5723 // If the vector cast is cast between two vectors of the same size, it is
5724 // a bitcast, not a conversion.
5725 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5726 return;
John McCall263a48b2010-01-04 23:31:57 +00005727
5728 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5729 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5730 }
5731
5732 // Strip complex types.
5733 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005734 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005735 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005736 return;
5737
John McCallacf0ee52010-10-08 02:01:28 +00005738 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005739 }
John McCall263a48b2010-01-04 23:31:57 +00005740
5741 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5742 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5743 }
5744
5745 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5746 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5747
5748 // If the source is floating point...
5749 if (SourceBT && SourceBT->isFloatingPoint()) {
5750 // ...and the target is floating point...
5751 if (TargetBT && TargetBT->isFloatingPoint()) {
5752 // ...then warn if we're dropping FP rank.
5753
5754 // Builtin FP kinds are ordered by increasing FP rank.
5755 if (SourceBT->getKind() > TargetBT->getKind()) {
5756 // Don't warn about float constants that are precisely
5757 // representable in the target type.
5758 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005759 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005760 // Value might be a float, a float vector, or a float complex.
5761 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005762 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5763 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005764 return;
5765 }
5766
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005767 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005768 return;
5769
John McCallacf0ee52010-10-08 02:01:28 +00005770 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005771 }
5772 return;
5773 }
5774
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005775 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005776 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005777 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005778 return;
5779
Chandler Carruth22c7a792011-02-17 11:05:49 +00005780 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005781 // We also want to warn on, e.g., "int i = -1.234"
5782 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5783 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5784 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5785
Chandler Carruth016ef402011-04-10 08:36:24 +00005786 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5787 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005788 } else {
5789 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5790 }
5791 }
John McCall263a48b2010-01-04 23:31:57 +00005792
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005793 // If the target is bool, warn if expr is a function or method call.
5794 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5795 isa<CallExpr>(E)) {
5796 // Check last argument of function call to see if it is an
5797 // implicit cast from a type matching the type the result
5798 // is being cast to.
5799 CallExpr *CEx = cast<CallExpr>(E);
5800 unsigned NumArgs = CEx->getNumArgs();
5801 if (NumArgs > 0) {
5802 Expr *LastA = CEx->getArg(NumArgs - 1);
5803 Expr *InnerE = LastA->IgnoreParenImpCasts();
5804 const Type *InnerType =
5805 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5806 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5807 // Warn on this floating-point to bool conversion
5808 DiagnoseImpCast(S, E, T, CC,
5809 diag::warn_impcast_floating_point_to_bool);
5810 }
5811 }
5812 }
John McCall263a48b2010-01-04 23:31:57 +00005813 return;
5814 }
5815
Richard Trieubeaf3452011-05-29 19:59:02 +00005816 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005817 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005818 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005819 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005820 SourceLocation Loc = E->getSourceRange().getBegin();
5821 if (Loc.isMacroID())
5822 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005823 if (!Loc.isMacroID() || CC.isMacroID())
5824 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5825 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005826 << FixItHint::CreateReplacement(Loc,
5827 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005828 }
5829
David Blaikie9366d2b2012-06-19 21:19:06 +00005830 if (!Source->isIntegerType() || !Target->isIntegerType())
5831 return;
5832
David Blaikie7555b6a2012-05-15 16:56:36 +00005833 // TODO: remove this early return once the false positives for constant->bool
5834 // in templates, macros, etc, are reduced or removed.
5835 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5836 return;
5837
John McCallcc7e5bf2010-05-06 08:58:33 +00005838 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005839 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005840
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005841 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005842 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005843 // TODO: this should happen for bitfield stores, too.
5844 llvm::APSInt Value(32);
5845 if (E->isIntegerConstantExpr(Value, S.Context)) {
5846 if (S.SourceMgr.isInSystemMacro(CC))
5847 return;
5848
John McCall18a2c2c2010-11-09 22:22:12 +00005849 std::string PrettySourceValue = Value.toString(10);
5850 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005851
Ted Kremenek33ba9952011-10-22 02:37:33 +00005852 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5853 S.PDiag(diag::warn_impcast_integer_precision_constant)
5854 << PrettySourceValue << PrettyTargetValue
5855 << E->getType() << T << E->getSourceRange()
5856 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005857 return;
5858 }
5859
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005860 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5861 if (S.SourceMgr.isInSystemMacro(CC))
5862 return;
5863
David Blaikie9455da02012-04-12 22:40:54 +00005864 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005865 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5866 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005867 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005868 }
5869
5870 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5871 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5872 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005873
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 McCallcc7e5bf2010-05-06 08:58:33 +00005877 unsigned DiagID = diag::warn_impcast_integer_sign;
5878
5879 // Traditionally, gcc has warned about this under -Wsign-compare.
5880 // We also want to warn about it in -Wconversion.
5881 // So if -Wconversion is off, use a completely identical diagnostic
5882 // in the sign-compare group.
5883 // The conditional-checking code will
5884 if (ICContext) {
5885 DiagID = diag::warn_impcast_integer_sign_conditional;
5886 *ICContext = true;
5887 }
5888
John McCallacf0ee52010-10-08 02:01:28 +00005889 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005890 }
5891
Douglas Gregora78f1932011-02-22 02:45:07 +00005892 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005893 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5894 // type, to give us better diagnostics.
5895 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005896 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005897 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5898 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5899 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5900 SourceType = S.Context.getTypeDeclType(Enum);
5901 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5902 }
5903 }
5904
Douglas Gregora78f1932011-02-22 02:45:07 +00005905 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5906 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005907 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5908 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005909 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005910 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005911 return;
5912
Douglas Gregor364f7db2011-03-12 00:14:31 +00005913 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005914 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005915 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005916
John McCall263a48b2010-01-04 23:31:57 +00005917 return;
5918}
5919
David Blaikie18e9ac72012-05-15 21:57:38 +00005920void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5921 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005922
5923void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005924 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005925 E = E->IgnoreParenImpCasts();
5926
5927 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005928 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005929
John McCallacf0ee52010-10-08 02:01:28 +00005930 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005931 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005932 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005933 return;
5934}
5935
David Blaikie18e9ac72012-05-15 21:57:38 +00005936void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5937 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005938 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005939
5940 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005941 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5942 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005943
5944 // If -Wconversion would have warned about either of the candidates
5945 // for a signedness conversion to the context type...
5946 if (!Suspicious) return;
5947
5948 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005949 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5950 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005951 return;
5952
John McCallcc7e5bf2010-05-06 08:58:33 +00005953 // ...then check whether it would have warned about either of the
5954 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005955 if (E->getType() == T) return;
5956
5957 Suspicious = false;
5958 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5959 E->getType(), CC, &Suspicious);
5960 if (!Suspicious)
5961 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005962 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005963}
5964
5965/// AnalyzeImplicitConversions - Find and report any interesting
5966/// implicit conversions in the given expression. There are a couple
5967/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005968void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005969 QualType T = OrigE->getType();
5970 Expr *E = OrigE->IgnoreParenImpCasts();
5971
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005972 if (E->isTypeDependent() || E->isValueDependent())
5973 return;
5974
John McCallcc7e5bf2010-05-06 08:58:33 +00005975 // For conditional operators, we analyze the arguments as if they
5976 // were being fed directly into the output.
5977 if (isa<ConditionalOperator>(E)) {
5978 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005979 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005980 return;
5981 }
5982
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005983 // Check implicit argument conversions for function calls.
5984 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5985 CheckImplicitArgumentConversions(S, Call, CC);
5986
John McCallcc7e5bf2010-05-06 08:58:33 +00005987 // Go ahead and check any implicit conversions we might have skipped.
5988 // The non-canonical typecheck is just an optimization;
5989 // CheckImplicitConversion will filter out dead implicit conversions.
5990 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005991 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005992
5993 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005994
5995 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005996 if (POE->getResultExpr())
5997 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005998 }
5999
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006000 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6001 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6002
John McCallcc7e5bf2010-05-06 08:58:33 +00006003 // Skip past explicit casts.
6004 if (isa<ExplicitCastExpr>(E)) {
6005 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006006 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006007 }
6008
John McCalld2a53122010-11-09 23:24:47 +00006009 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6010 // Do a somewhat different check with comparison operators.
6011 if (BO->isComparisonOp())
6012 return AnalyzeComparison(S, BO);
6013
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006014 // And with simple assignments.
6015 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006016 return AnalyzeAssignment(S, BO);
6017 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006018
6019 // These break the otherwise-useful invariant below. Fortunately,
6020 // we don't really need to recurse into them, because any internal
6021 // expressions should have been analyzed already when they were
6022 // built into statements.
6023 if (isa<StmtExpr>(E)) return;
6024
6025 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006026 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006027
6028 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006029 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006030 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006031 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006032 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006033 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006034 if (!ChildExpr)
6035 continue;
6036
Richard Trieu955231d2014-01-25 01:10:35 +00006037 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006038 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006039 // Ignore checking string literals that are in logical and operators.
6040 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006041 continue;
6042 AnalyzeImplicitConversions(S, ChildExpr, CC);
6043 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006044}
6045
6046} // end anonymous namespace
6047
Richard Trieu3bb8b562014-02-26 02:36:06 +00006048enum {
6049 AddressOf,
6050 FunctionPointer,
6051 ArrayPointer
6052};
6053
6054/// \brief Diagnose pointers that are always non-null.
6055/// \param E the expression containing the pointer
6056/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6057/// compared to a null pointer
6058/// \param IsEqual True when the comparison is equal to a null pointer
6059/// \param Range Extra SourceRange to highlight in the diagnostic
6060void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6061 Expr::NullPointerConstantKind NullKind,
6062 bool IsEqual, SourceRange Range) {
6063
6064 // Don't warn inside macros.
6065 if (E->getExprLoc().isMacroID())
6066 return;
6067 E = E->IgnoreImpCasts();
6068
6069 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6070
6071 bool IsAddressOf = false;
6072
6073 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6074 if (UO->getOpcode() != UO_AddrOf)
6075 return;
6076 IsAddressOf = true;
6077 E = UO->getSubExpr();
6078 }
6079
6080 // Expect to find a single Decl. Skip anything more complicated.
6081 ValueDecl *D = 0;
6082 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6083 D = R->getDecl();
6084 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6085 D = M->getMemberDecl();
6086 }
6087
6088 // Weak Decls can be null.
6089 if (!D || D->isWeak())
6090 return;
6091
6092 QualType T = D->getType();
6093 const bool IsArray = T->isArrayType();
6094 const bool IsFunction = T->isFunctionType();
6095
6096 if (IsAddressOf) {
6097 // Address of function is used to silence the function warning.
6098 if (IsFunction)
6099 return;
6100 // Address of reference can be null.
6101 if (T->isReferenceType())
6102 return;
6103 }
6104
6105 // Found nothing.
6106 if (!IsAddressOf && !IsFunction && !IsArray)
6107 return;
6108
6109 // Pretty print the expression for the diagnostic.
6110 std::string Str;
6111 llvm::raw_string_ostream S(Str);
6112 E->printPretty(S, 0, getPrintingPolicy());
6113
6114 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6115 : diag::warn_impcast_pointer_to_bool;
6116 unsigned DiagType;
6117 if (IsAddressOf)
6118 DiagType = AddressOf;
6119 else if (IsFunction)
6120 DiagType = FunctionPointer;
6121 else if (IsArray)
6122 DiagType = ArrayPointer;
6123 else
6124 llvm_unreachable("Could not determine diagnostic.");
6125 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6126 << Range << IsEqual;
6127
6128 if (!IsFunction)
6129 return;
6130
6131 // Suggest '&' to silence the function warning.
6132 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6133 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6134
6135 // Check to see if '()' fixit should be emitted.
6136 QualType ReturnType;
6137 UnresolvedSet<4> NonTemplateOverloads;
6138 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6139 if (ReturnType.isNull())
6140 return;
6141
6142 if (IsCompare) {
6143 // There are two cases here. If there is null constant, the only suggest
6144 // for a pointer return type. If the null is 0, then suggest if the return
6145 // type is a pointer or an integer type.
6146 if (!ReturnType->isPointerType()) {
6147 if (NullKind == Expr::NPCK_ZeroExpression ||
6148 NullKind == Expr::NPCK_ZeroLiteral) {
6149 if (!ReturnType->isIntegerType())
6150 return;
6151 } else {
6152 return;
6153 }
6154 }
6155 } else { // !IsCompare
6156 // For function to bool, only suggest if the function pointer has bool
6157 // return type.
6158 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6159 return;
6160 }
6161 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6162 << FixItHint::CreateInsertion(
6163 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6164}
6165
6166
John McCallcc7e5bf2010-05-06 08:58:33 +00006167/// Diagnoses "dangerous" implicit conversions within the given
6168/// expression (which is a full expression). Implements -Wconversion
6169/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006170///
6171/// \param CC the "context" location of the implicit conversion, i.e.
6172/// the most location of the syntactic entity requiring the implicit
6173/// conversion
6174void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006175 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006176 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006177 return;
6178
6179 // Don't diagnose for value- or type-dependent expressions.
6180 if (E->isTypeDependent() || E->isValueDependent())
6181 return;
6182
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006183 // Check for array bounds violations in cases where the check isn't triggered
6184 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6185 // ArraySubscriptExpr is on the RHS of a variable initialization.
6186 CheckArrayAccess(E);
6187
John McCallacf0ee52010-10-08 02:01:28 +00006188 // This is not the right CC for (e.g.) a variable initialization.
6189 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006190}
6191
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006192/// Diagnose when expression is an integer constant expression and its evaluation
6193/// results in integer overflow
6194void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006195 if (isa<BinaryOperator>(E->IgnoreParens()))
6196 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006197}
6198
Richard Smithc406cb72013-01-17 01:17:56 +00006199namespace {
6200/// \brief Visitor for expressions which looks for unsequenced operations on the
6201/// same object.
6202class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006203 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6204
Richard Smithc406cb72013-01-17 01:17:56 +00006205 /// \brief A tree of sequenced regions within an expression. Two regions are
6206 /// unsequenced if one is an ancestor or a descendent of the other. When we
6207 /// finish processing an expression with sequencing, such as a comma
6208 /// expression, we fold its tree nodes into its parent, since they are
6209 /// unsequenced with respect to nodes we will visit later.
6210 class SequenceTree {
6211 struct Value {
6212 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6213 unsigned Parent : 31;
6214 bool Merged : 1;
6215 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006216 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006217
6218 public:
6219 /// \brief A region within an expression which may be sequenced with respect
6220 /// to some other region.
6221 class Seq {
6222 explicit Seq(unsigned N) : Index(N) {}
6223 unsigned Index;
6224 friend class SequenceTree;
6225 public:
6226 Seq() : Index(0) {}
6227 };
6228
6229 SequenceTree() { Values.push_back(Value(0)); }
6230 Seq root() const { return Seq(0); }
6231
6232 /// \brief Create a new sequence of operations, which is an unsequenced
6233 /// subset of \p Parent. This sequence of operations is sequenced with
6234 /// respect to other children of \p Parent.
6235 Seq allocate(Seq Parent) {
6236 Values.push_back(Value(Parent.Index));
6237 return Seq(Values.size() - 1);
6238 }
6239
6240 /// \brief Merge a sequence of operations into its parent.
6241 void merge(Seq S) {
6242 Values[S.Index].Merged = true;
6243 }
6244
6245 /// \brief Determine whether two operations are unsequenced. This operation
6246 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6247 /// should have been merged into its parent as appropriate.
6248 bool isUnsequenced(Seq Cur, Seq Old) {
6249 unsigned C = representative(Cur.Index);
6250 unsigned Target = representative(Old.Index);
6251 while (C >= Target) {
6252 if (C == Target)
6253 return true;
6254 C = Values[C].Parent;
6255 }
6256 return false;
6257 }
6258
6259 private:
6260 /// \brief Pick a representative for a sequence.
6261 unsigned representative(unsigned K) {
6262 if (Values[K].Merged)
6263 // Perform path compression as we go.
6264 return Values[K].Parent = representative(Values[K].Parent);
6265 return K;
6266 }
6267 };
6268
6269 /// An object for which we can track unsequenced uses.
6270 typedef NamedDecl *Object;
6271
6272 /// Different flavors of object usage which we track. We only track the
6273 /// least-sequenced usage of each kind.
6274 enum UsageKind {
6275 /// A read of an object. Multiple unsequenced reads are OK.
6276 UK_Use,
6277 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006278 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006279 UK_ModAsValue,
6280 /// A modification of an object which is not sequenced before the value
6281 /// computation of the expression, such as n++.
6282 UK_ModAsSideEffect,
6283
6284 UK_Count = UK_ModAsSideEffect + 1
6285 };
6286
6287 struct Usage {
6288 Usage() : Use(0), Seq() {}
6289 Expr *Use;
6290 SequenceTree::Seq Seq;
6291 };
6292
6293 struct UsageInfo {
6294 UsageInfo() : Diagnosed(false) {}
6295 Usage Uses[UK_Count];
6296 /// Have we issued a diagnostic for this variable already?
6297 bool Diagnosed;
6298 };
6299 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6300
6301 Sema &SemaRef;
6302 /// Sequenced regions within the expression.
6303 SequenceTree Tree;
6304 /// Declaration modifications and references which we have seen.
6305 UsageInfoMap UsageMap;
6306 /// The region we are currently within.
6307 SequenceTree::Seq Region;
6308 /// Filled in with declarations which were modified as a side-effect
6309 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006310 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006311 /// Expressions to check later. We defer checking these to reduce
6312 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006313 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006314
6315 /// RAII object wrapping the visitation of a sequenced subexpression of an
6316 /// expression. At the end of this process, the side-effects of the evaluation
6317 /// become sequenced with respect to the value computation of the result, so
6318 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6319 /// UK_ModAsValue.
6320 struct SequencedSubexpression {
6321 SequencedSubexpression(SequenceChecker &Self)
6322 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6323 Self.ModAsSideEffect = &ModAsSideEffect;
6324 }
6325 ~SequencedSubexpression() {
6326 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6327 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6328 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6329 Self.addUsage(U, ModAsSideEffect[I].first,
6330 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6331 }
6332 Self.ModAsSideEffect = OldModAsSideEffect;
6333 }
6334
6335 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006336 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6337 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006338 };
6339
Richard Smith40238f02013-06-20 22:21:56 +00006340 /// RAII object wrapping the visitation of a subexpression which we might
6341 /// choose to evaluate as a constant. If any subexpression is evaluated and
6342 /// found to be non-constant, this allows us to suppress the evaluation of
6343 /// the outer expression.
6344 class EvaluationTracker {
6345 public:
6346 EvaluationTracker(SequenceChecker &Self)
6347 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6348 Self.EvalTracker = this;
6349 }
6350 ~EvaluationTracker() {
6351 Self.EvalTracker = Prev;
6352 if (Prev)
6353 Prev->EvalOK &= EvalOK;
6354 }
6355
6356 bool evaluate(const Expr *E, bool &Result) {
6357 if (!EvalOK || E->isValueDependent())
6358 return false;
6359 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6360 return EvalOK;
6361 }
6362
6363 private:
6364 SequenceChecker &Self;
6365 EvaluationTracker *Prev;
6366 bool EvalOK;
6367 } *EvalTracker;
6368
Richard Smithc406cb72013-01-17 01:17:56 +00006369 /// \brief Find the object which is produced by the specified expression,
6370 /// if any.
6371 Object getObject(Expr *E, bool Mod) const {
6372 E = E->IgnoreParenCasts();
6373 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6374 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6375 return getObject(UO->getSubExpr(), Mod);
6376 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6377 if (BO->getOpcode() == BO_Comma)
6378 return getObject(BO->getRHS(), Mod);
6379 if (Mod && BO->isAssignmentOp())
6380 return getObject(BO->getLHS(), Mod);
6381 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6382 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6383 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6384 return ME->getMemberDecl();
6385 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6386 // FIXME: If this is a reference, map through to its value.
6387 return DRE->getDecl();
6388 return 0;
6389 }
6390
6391 /// \brief Note that an object was modified or used by an expression.
6392 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6393 Usage &U = UI.Uses[UK];
6394 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6395 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6396 ModAsSideEffect->push_back(std::make_pair(O, U));
6397 U.Use = Ref;
6398 U.Seq = Region;
6399 }
6400 }
6401 /// \brief Check whether a modification or use conflicts with a prior usage.
6402 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6403 bool IsModMod) {
6404 if (UI.Diagnosed)
6405 return;
6406
6407 const Usage &U = UI.Uses[OtherKind];
6408 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6409 return;
6410
6411 Expr *Mod = U.Use;
6412 Expr *ModOrUse = Ref;
6413 if (OtherKind == UK_Use)
6414 std::swap(Mod, ModOrUse);
6415
6416 SemaRef.Diag(Mod->getExprLoc(),
6417 IsModMod ? diag::warn_unsequenced_mod_mod
6418 : diag::warn_unsequenced_mod_use)
6419 << O << SourceRange(ModOrUse->getExprLoc());
6420 UI.Diagnosed = true;
6421 }
6422
6423 void notePreUse(Object O, Expr *Use) {
6424 UsageInfo &U = UsageMap[O];
6425 // Uses conflict with other modifications.
6426 checkUsage(O, U, Use, UK_ModAsValue, false);
6427 }
6428 void notePostUse(Object O, Expr *Use) {
6429 UsageInfo &U = UsageMap[O];
6430 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6431 addUsage(U, O, Use, UK_Use);
6432 }
6433
6434 void notePreMod(Object O, Expr *Mod) {
6435 UsageInfo &U = UsageMap[O];
6436 // Modifications conflict with other modifications and with uses.
6437 checkUsage(O, U, Mod, UK_ModAsValue, true);
6438 checkUsage(O, U, Mod, UK_Use, false);
6439 }
6440 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6441 UsageInfo &U = UsageMap[O];
6442 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6443 addUsage(U, O, Use, UK);
6444 }
6445
6446public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006447 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6448 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6449 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006450 Visit(E);
6451 }
6452
6453 void VisitStmt(Stmt *S) {
6454 // Skip all statements which aren't expressions for now.
6455 }
6456
6457 void VisitExpr(Expr *E) {
6458 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006459 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006460 }
6461
6462 void VisitCastExpr(CastExpr *E) {
6463 Object O = Object();
6464 if (E->getCastKind() == CK_LValueToRValue)
6465 O = getObject(E->getSubExpr(), false);
6466
6467 if (O)
6468 notePreUse(O, E);
6469 VisitExpr(E);
6470 if (O)
6471 notePostUse(O, E);
6472 }
6473
6474 void VisitBinComma(BinaryOperator *BO) {
6475 // C++11 [expr.comma]p1:
6476 // Every value computation and side effect associated with the left
6477 // expression is sequenced before every value computation and side
6478 // effect associated with the right expression.
6479 SequenceTree::Seq LHS = Tree.allocate(Region);
6480 SequenceTree::Seq RHS = Tree.allocate(Region);
6481 SequenceTree::Seq OldRegion = Region;
6482
6483 {
6484 SequencedSubexpression SeqLHS(*this);
6485 Region = LHS;
6486 Visit(BO->getLHS());
6487 }
6488
6489 Region = RHS;
6490 Visit(BO->getRHS());
6491
6492 Region = OldRegion;
6493
6494 // Forget that LHS and RHS are sequenced. They are both unsequenced
6495 // with respect to other stuff.
6496 Tree.merge(LHS);
6497 Tree.merge(RHS);
6498 }
6499
6500 void VisitBinAssign(BinaryOperator *BO) {
6501 // The modification is sequenced after the value computation of the LHS
6502 // and RHS, so check it before inspecting the operands and update the
6503 // map afterwards.
6504 Object O = getObject(BO->getLHS(), true);
6505 if (!O)
6506 return VisitExpr(BO);
6507
6508 notePreMod(O, BO);
6509
6510 // C++11 [expr.ass]p7:
6511 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6512 // only once.
6513 //
6514 // Therefore, for a compound assignment operator, O is considered used
6515 // everywhere except within the evaluation of E1 itself.
6516 if (isa<CompoundAssignOperator>(BO))
6517 notePreUse(O, BO);
6518
6519 Visit(BO->getLHS());
6520
6521 if (isa<CompoundAssignOperator>(BO))
6522 notePostUse(O, BO);
6523
6524 Visit(BO->getRHS());
6525
Richard Smith83e37bee2013-06-26 23:16:51 +00006526 // C++11 [expr.ass]p1:
6527 // the assignment is sequenced [...] before the value computation of the
6528 // assignment expression.
6529 // C11 6.5.16/3 has no such rule.
6530 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6531 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006532 }
6533 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6534 VisitBinAssign(CAO);
6535 }
6536
6537 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6538 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6539 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6540 Object O = getObject(UO->getSubExpr(), true);
6541 if (!O)
6542 return VisitExpr(UO);
6543
6544 notePreMod(O, UO);
6545 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006546 // C++11 [expr.pre.incr]p1:
6547 // the expression ++x is equivalent to x+=1
6548 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6549 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006550 }
6551
6552 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6553 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6554 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6555 Object O = getObject(UO->getSubExpr(), true);
6556 if (!O)
6557 return VisitExpr(UO);
6558
6559 notePreMod(O, UO);
6560 Visit(UO->getSubExpr());
6561 notePostMod(O, UO, UK_ModAsSideEffect);
6562 }
6563
6564 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6565 void VisitBinLOr(BinaryOperator *BO) {
6566 // The side-effects of the LHS of an '&&' are sequenced before the
6567 // value computation of the RHS, and hence before the value computation
6568 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6569 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006570 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006571 {
6572 SequencedSubexpression Sequenced(*this);
6573 Visit(BO->getLHS());
6574 }
6575
6576 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006577 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006578 if (!Result)
6579 Visit(BO->getRHS());
6580 } else {
6581 // Check for unsequenced operations in the RHS, treating it as an
6582 // entirely separate evaluation.
6583 //
6584 // FIXME: If there are operations in the RHS which are unsequenced
6585 // with respect to operations outside the RHS, and those operations
6586 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006587 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006588 }
Richard Smithc406cb72013-01-17 01:17:56 +00006589 }
6590 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006591 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006592 {
6593 SequencedSubexpression Sequenced(*this);
6594 Visit(BO->getLHS());
6595 }
6596
6597 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006598 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006599 if (Result)
6600 Visit(BO->getRHS());
6601 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006602 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006603 }
Richard Smithc406cb72013-01-17 01:17:56 +00006604 }
6605
6606 // Only visit the condition, unless we can be sure which subexpression will
6607 // be chosen.
6608 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006609 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006610 {
6611 SequencedSubexpression Sequenced(*this);
6612 Visit(CO->getCond());
6613 }
Richard Smithc406cb72013-01-17 01:17:56 +00006614
6615 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006616 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006617 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006618 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006619 WorkList.push_back(CO->getTrueExpr());
6620 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006621 }
Richard Smithc406cb72013-01-17 01:17:56 +00006622 }
6623
Richard Smithe3dbfe02013-06-30 10:40:20 +00006624 void VisitCallExpr(CallExpr *CE) {
6625 // C++11 [intro.execution]p15:
6626 // When calling a function [...], every value computation and side effect
6627 // associated with any argument expression, or with the postfix expression
6628 // designating the called function, is sequenced before execution of every
6629 // expression or statement in the body of the function [and thus before
6630 // the value computation of its result].
6631 SequencedSubexpression Sequenced(*this);
6632 Base::VisitCallExpr(CE);
6633
6634 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6635 }
6636
Richard Smithc406cb72013-01-17 01:17:56 +00006637 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006638 // This is a call, so all subexpressions are sequenced before the result.
6639 SequencedSubexpression Sequenced(*this);
6640
Richard Smithc406cb72013-01-17 01:17:56 +00006641 if (!CCE->isListInitialization())
6642 return VisitExpr(CCE);
6643
6644 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006645 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006646 SequenceTree::Seq Parent = Region;
6647 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6648 E = CCE->arg_end();
6649 I != E; ++I) {
6650 Region = Tree.allocate(Parent);
6651 Elts.push_back(Region);
6652 Visit(*I);
6653 }
6654
6655 // Forget that the initializers are sequenced.
6656 Region = Parent;
6657 for (unsigned I = 0; I < Elts.size(); ++I)
6658 Tree.merge(Elts[I]);
6659 }
6660
6661 void VisitInitListExpr(InitListExpr *ILE) {
6662 if (!SemaRef.getLangOpts().CPlusPlus11)
6663 return VisitExpr(ILE);
6664
6665 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006666 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006667 SequenceTree::Seq Parent = Region;
6668 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6669 Expr *E = ILE->getInit(I);
6670 if (!E) continue;
6671 Region = Tree.allocate(Parent);
6672 Elts.push_back(Region);
6673 Visit(E);
6674 }
6675
6676 // Forget that the initializers are sequenced.
6677 Region = Parent;
6678 for (unsigned I = 0; I < Elts.size(); ++I)
6679 Tree.merge(Elts[I]);
6680 }
6681};
6682}
6683
6684void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006685 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006686 WorkList.push_back(E);
6687 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006688 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006689 SequenceChecker(*this, Item, WorkList);
6690 }
Richard Smithc406cb72013-01-17 01:17:56 +00006691}
6692
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006693void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6694 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006695 CheckImplicitConversions(E, CheckLoc);
6696 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006697 if (!IsConstexpr && !E->isValueDependent())
6698 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006699}
6700
John McCall1f425642010-11-11 03:21:53 +00006701void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6702 FieldDecl *BitField,
6703 Expr *Init) {
6704 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6705}
6706
Mike Stump0c2ec772010-01-21 03:59:47 +00006707/// CheckParmsForFunctionDef - Check that the parameters of the given
6708/// function are appropriate for the definition of a function. This
6709/// takes care of any checks that cannot be performed on the
6710/// declaration itself, e.g., that the types of each of the function
6711/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006712bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6713 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006714 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006715 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006716 for (; P != PEnd; ++P) {
6717 ParmVarDecl *Param = *P;
6718
Mike Stump0c2ec772010-01-21 03:59:47 +00006719 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6720 // function declarator that is part of a function definition of
6721 // that function shall not have incomplete type.
6722 //
6723 // This is also C++ [dcl.fct]p6.
6724 if (!Param->isInvalidDecl() &&
6725 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006726 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006727 Param->setInvalidDecl();
6728 HasInvalidParm = true;
6729 }
6730
6731 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6732 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006733 if (CheckParameterNames &&
6734 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006735 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006736 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006737 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006738
6739 // C99 6.7.5.3p12:
6740 // If the function declarator is not part of a definition of that
6741 // function, parameters may have incomplete type and may use the [*]
6742 // notation in their sequences of declarator specifiers to specify
6743 // variable length array types.
6744 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006745 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006746 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006747 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006748 // information is added for it.
6749 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006750 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006751 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006752 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006753 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006754
6755 // MSVC destroys objects passed by value in the callee. Therefore a
6756 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006757 // object's destructor. However, we don't perform any direct access check
6758 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006759 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6760 .getCXXABI()
6761 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006762 if (!Param->isInvalidDecl()) {
6763 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6764 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6765 if (!ClassDecl->isInvalidDecl() &&
6766 !ClassDecl->hasIrrelevantDestructor() &&
6767 !ClassDecl->isDependentContext()) {
6768 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6769 MarkFunctionReferenced(Param->getLocation(), Destructor);
6770 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6771 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006772 }
6773 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006774 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006775 }
6776
6777 return HasInvalidParm;
6778}
John McCall2b5c1b22010-08-12 21:44:57 +00006779
6780/// CheckCastAlign - Implements -Wcast-align, which warns when a
6781/// pointer cast increases the alignment requirements.
6782void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6783 // This is actually a lot of work to potentially be doing on every
6784 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006785 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6786 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006787 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006788 return;
6789
6790 // Ignore dependent types.
6791 if (T->isDependentType() || Op->getType()->isDependentType())
6792 return;
6793
6794 // Require that the destination be a pointer type.
6795 const PointerType *DestPtr = T->getAs<PointerType>();
6796 if (!DestPtr) return;
6797
6798 // If the destination has alignment 1, we're done.
6799 QualType DestPointee = DestPtr->getPointeeType();
6800 if (DestPointee->isIncompleteType()) return;
6801 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6802 if (DestAlign.isOne()) return;
6803
6804 // Require that the source be a pointer type.
6805 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6806 if (!SrcPtr) return;
6807 QualType SrcPointee = SrcPtr->getPointeeType();
6808
6809 // Whitelist casts from cv void*. We already implicitly
6810 // whitelisted casts to cv void*, since they have alignment 1.
6811 // Also whitelist casts involving incomplete types, which implicitly
6812 // includes 'void'.
6813 if (SrcPointee->isIncompleteType()) return;
6814
6815 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6816 if (SrcAlign >= DestAlign) return;
6817
6818 Diag(TRange.getBegin(), diag::warn_cast_align)
6819 << Op->getType() << T
6820 << static_cast<unsigned>(SrcAlign.getQuantity())
6821 << static_cast<unsigned>(DestAlign.getQuantity())
6822 << TRange << Op->getSourceRange();
6823}
6824
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006825static const Type* getElementType(const Expr *BaseExpr) {
6826 const Type* EltType = BaseExpr->getType().getTypePtr();
6827 if (EltType->isAnyPointerType())
6828 return EltType->getPointeeType().getTypePtr();
6829 else if (EltType->isArrayType())
6830 return EltType->getBaseElementTypeUnsafe();
6831 return EltType;
6832}
6833
Chandler Carruth28389f02011-08-05 09:10:50 +00006834/// \brief Check whether this array fits the idiom of a size-one tail padded
6835/// array member of a struct.
6836///
6837/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6838/// commonly used to emulate flexible arrays in C89 code.
6839static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6840 const NamedDecl *ND) {
6841 if (Size != 1 || !ND) return false;
6842
6843 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6844 if (!FD) return false;
6845
6846 // Don't consider sizes resulting from macro expansions or template argument
6847 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006848
6849 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006850 while (TInfo) {
6851 TypeLoc TL = TInfo->getTypeLoc();
6852 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006853 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6854 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006855 TInfo = TDL->getTypeSourceInfo();
6856 continue;
6857 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006858 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6859 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006860 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6861 return false;
6862 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006863 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006864 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006865
6866 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006867 if (!RD) return false;
6868 if (RD->isUnion()) return false;
6869 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6870 if (!CRD->isStandardLayout()) return false;
6871 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006872
Benjamin Kramer8c543672011-08-06 03:04:42 +00006873 // See if this is the last field decl in the record.
6874 const Decl *D = FD;
6875 while ((D = D->getNextDeclInContext()))
6876 if (isa<FieldDecl>(D))
6877 return false;
6878 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006879}
6880
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006881void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006882 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006883 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006884 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006885 if (IndexExpr->isValueDependent())
6886 return;
6887
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006888 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006889 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006890 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006891 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006892 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006893 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006894
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006895 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006896 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006897 return;
Richard Smith13f67182011-12-16 19:31:14 +00006898 if (IndexNegated)
6899 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006900
Chandler Carruth126b1552011-08-05 08:07:29 +00006901 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006902 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6903 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006904 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006905 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006906
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006907 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006908 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006909 if (!size.isStrictlyPositive())
6910 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006911
6912 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006913 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006914 // Make sure we're comparing apples to apples when comparing index to size
6915 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6916 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006917 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006918 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006919 if (ptrarith_typesize != array_typesize) {
6920 // There's a cast to a different size type involved
6921 uint64_t ratio = array_typesize / ptrarith_typesize;
6922 // TODO: Be smarter about handling cases where array_typesize is not a
6923 // multiple of ptrarith_typesize
6924 if (ptrarith_typesize * ratio == array_typesize)
6925 size *= llvm::APInt(size.getBitWidth(), ratio);
6926 }
6927 }
6928
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006929 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006930 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006931 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006932 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006933
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006934 // For array subscripting the index must be less than size, but for pointer
6935 // arithmetic also allow the index (offset) to be equal to size since
6936 // computing the next address after the end of the array is legal and
6937 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006938 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006939 return;
6940
6941 // Also don't warn for arrays of size 1 which are members of some
6942 // structure. These are often used to approximate flexible arrays in C89
6943 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006944 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006945 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006946
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006947 // Suppress the warning if the subscript expression (as identified by the
6948 // ']' location) and the index expression are both from macro expansions
6949 // within a system header.
6950 if (ASE) {
6951 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6952 ASE->getRBracketLoc());
6953 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6954 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6955 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006956 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006957 return;
6958 }
6959 }
6960
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006961 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006962 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006963 DiagID = diag::warn_array_index_exceeds_bounds;
6964
6965 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6966 PDiag(DiagID) << index.toString(10, true)
6967 << size.toString(10, true)
6968 << (unsigned)size.getLimitedValue(~0U)
6969 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006970 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006971 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006972 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006973 DiagID = diag::warn_ptr_arith_precedes_bounds;
6974 if (index.isNegative()) index = -index;
6975 }
6976
6977 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6978 PDiag(DiagID) << index.toString(10, true)
6979 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006980 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006981
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006982 if (!ND) {
6983 // Try harder to find a NamedDecl to point at in the note.
6984 while (const ArraySubscriptExpr *ASE =
6985 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6986 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6987 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6988 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6989 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6990 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6991 }
6992
Chandler Carruth1af88f12011-02-17 21:10:52 +00006993 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006994 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6995 PDiag(diag::note_array_index_out_of_bounds)
6996 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006997}
6998
Ted Kremenekdf26df72011-03-01 18:41:00 +00006999void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007000 int AllowOnePastEnd = 0;
7001 while (expr) {
7002 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007003 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007004 case Stmt::ArraySubscriptExprClass: {
7005 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007006 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007007 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007008 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007009 }
7010 case Stmt::UnaryOperatorClass: {
7011 // Only unwrap the * and & unary operators
7012 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7013 expr = UO->getSubExpr();
7014 switch (UO->getOpcode()) {
7015 case UO_AddrOf:
7016 AllowOnePastEnd++;
7017 break;
7018 case UO_Deref:
7019 AllowOnePastEnd--;
7020 break;
7021 default:
7022 return;
7023 }
7024 break;
7025 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007026 case Stmt::ConditionalOperatorClass: {
7027 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7028 if (const Expr *lhs = cond->getLHS())
7029 CheckArrayAccess(lhs);
7030 if (const Expr *rhs = cond->getRHS())
7031 CheckArrayAccess(rhs);
7032 return;
7033 }
7034 default:
7035 return;
7036 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007037 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007038}
John McCall31168b02011-06-15 23:02:42 +00007039
7040//===--- CHECK: Objective-C retain cycles ----------------------------------//
7041
7042namespace {
7043 struct RetainCycleOwner {
7044 RetainCycleOwner() : Variable(0), Indirect(false) {}
7045 VarDecl *Variable;
7046 SourceRange Range;
7047 SourceLocation Loc;
7048 bool Indirect;
7049
7050 void setLocsFrom(Expr *e) {
7051 Loc = e->getExprLoc();
7052 Range = e->getSourceRange();
7053 }
7054 };
7055}
7056
7057/// Consider whether capturing the given variable can possibly lead to
7058/// a retain cycle.
7059static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007060 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007061 // lifetime. In MRR, it's captured strongly if the variable is
7062 // __block and has an appropriate type.
7063 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7064 return false;
7065
7066 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007067 if (ref)
7068 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007069 return true;
7070}
7071
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007072static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007073 while (true) {
7074 e = e->IgnoreParens();
7075 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7076 switch (cast->getCastKind()) {
7077 case CK_BitCast:
7078 case CK_LValueBitCast:
7079 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007080 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007081 e = cast->getSubExpr();
7082 continue;
7083
John McCall31168b02011-06-15 23:02:42 +00007084 default:
7085 return false;
7086 }
7087 }
7088
7089 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7090 ObjCIvarDecl *ivar = ref->getDecl();
7091 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7092 return false;
7093
7094 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007095 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007096 return false;
7097
7098 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7099 owner.Indirect = true;
7100 return true;
7101 }
7102
7103 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7104 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7105 if (!var) return false;
7106 return considerVariable(var, ref, owner);
7107 }
7108
John McCall31168b02011-06-15 23:02:42 +00007109 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7110 if (member->isArrow()) return false;
7111
7112 // Don't count this as an indirect ownership.
7113 e = member->getBase();
7114 continue;
7115 }
7116
John McCallfe96e0b2011-11-06 09:01:30 +00007117 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7118 // Only pay attention to pseudo-objects on property references.
7119 ObjCPropertyRefExpr *pre
7120 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7121 ->IgnoreParens());
7122 if (!pre) return false;
7123 if (pre->isImplicitProperty()) return false;
7124 ObjCPropertyDecl *property = pre->getExplicitProperty();
7125 if (!property->isRetaining() &&
7126 !(property->getPropertyIvarDecl() &&
7127 property->getPropertyIvarDecl()->getType()
7128 .getObjCLifetime() == Qualifiers::OCL_Strong))
7129 return false;
7130
7131 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007132 if (pre->isSuperReceiver()) {
7133 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7134 if (!owner.Variable)
7135 return false;
7136 owner.Loc = pre->getLocation();
7137 owner.Range = pre->getSourceRange();
7138 return true;
7139 }
John McCallfe96e0b2011-11-06 09:01:30 +00007140 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7141 ->getSourceExpr());
7142 continue;
7143 }
7144
John McCall31168b02011-06-15 23:02:42 +00007145 // Array ivars?
7146
7147 return false;
7148 }
7149}
7150
7151namespace {
7152 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7153 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7154 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7155 Variable(variable), Capturer(0) {}
7156
7157 VarDecl *Variable;
7158 Expr *Capturer;
7159
7160 void VisitDeclRefExpr(DeclRefExpr *ref) {
7161 if (ref->getDecl() == Variable && !Capturer)
7162 Capturer = ref;
7163 }
7164
John McCall31168b02011-06-15 23:02:42 +00007165 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7166 if (Capturer) return;
7167 Visit(ref->getBase());
7168 if (Capturer && ref->isFreeIvar())
7169 Capturer = ref;
7170 }
7171
7172 void VisitBlockExpr(BlockExpr *block) {
7173 // Look inside nested blocks
7174 if (block->getBlockDecl()->capturesVariable(Variable))
7175 Visit(block->getBlockDecl()->getBody());
7176 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007177
7178 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7179 if (Capturer) return;
7180 if (OVE->getSourceExpr())
7181 Visit(OVE->getSourceExpr());
7182 }
John McCall31168b02011-06-15 23:02:42 +00007183 };
7184}
7185
7186/// Check whether the given argument is a block which captures a
7187/// variable.
7188static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7189 assert(owner.Variable && owner.Loc.isValid());
7190
7191 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007192
7193 // Look through [^{...} copy] and Block_copy(^{...}).
7194 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7195 Selector Cmd = ME->getSelector();
7196 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7197 e = ME->getInstanceReceiver();
7198 if (!e)
7199 return 0;
7200 e = e->IgnoreParenCasts();
7201 }
7202 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7203 if (CE->getNumArgs() == 1) {
7204 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007205 if (Fn) {
7206 const IdentifierInfo *FnI = Fn->getIdentifier();
7207 if (FnI && FnI->isStr("_Block_copy")) {
7208 e = CE->getArg(0)->IgnoreParenCasts();
7209 }
7210 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007211 }
7212 }
7213
John McCall31168b02011-06-15 23:02:42 +00007214 BlockExpr *block = dyn_cast<BlockExpr>(e);
7215 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7216 return 0;
7217
7218 FindCaptureVisitor visitor(S.Context, owner.Variable);
7219 visitor.Visit(block->getBlockDecl()->getBody());
7220 return visitor.Capturer;
7221}
7222
7223static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7224 RetainCycleOwner &owner) {
7225 assert(capturer);
7226 assert(owner.Variable && owner.Loc.isValid());
7227
7228 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7229 << owner.Variable << capturer->getSourceRange();
7230 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7231 << owner.Indirect << owner.Range;
7232}
7233
7234/// Check for a keyword selector that starts with the word 'add' or
7235/// 'set'.
7236static bool isSetterLikeSelector(Selector sel) {
7237 if (sel.isUnarySelector()) return false;
7238
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007239 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007240 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007241 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007242 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007243 else if (str.startswith("add")) {
7244 // Specially whitelist 'addOperationWithBlock:'.
7245 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7246 return false;
7247 str = str.substr(3);
7248 }
John McCall31168b02011-06-15 23:02:42 +00007249 else
7250 return false;
7251
7252 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007253 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007254}
7255
7256/// Check a message send to see if it's likely to cause a retain cycle.
7257void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7258 // Only check instance methods whose selector looks like a setter.
7259 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7260 return;
7261
7262 // Try to find a variable that the receiver is strongly owned by.
7263 RetainCycleOwner owner;
7264 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007265 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007266 return;
7267 } else {
7268 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7269 owner.Variable = getCurMethodDecl()->getSelfDecl();
7270 owner.Loc = msg->getSuperLoc();
7271 owner.Range = msg->getSuperLoc();
7272 }
7273
7274 // Check whether the receiver is captured by any of the arguments.
7275 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7276 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7277 return diagnoseRetainCycle(*this, capturer, owner);
7278}
7279
7280/// Check a property assign to see if it's likely to cause a retain cycle.
7281void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7282 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007283 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007284 return;
7285
7286 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7287 diagnoseRetainCycle(*this, capturer, owner);
7288}
7289
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007290void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7291 RetainCycleOwner Owner;
7292 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7293 return;
7294
7295 // Because we don't have an expression for the variable, we have to set the
7296 // location explicitly here.
7297 Owner.Loc = Var->getLocation();
7298 Owner.Range = Var->getSourceRange();
7299
7300 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7301 diagnoseRetainCycle(*this, Capturer, Owner);
7302}
7303
Ted Kremenek9304da92012-12-21 08:04:28 +00007304static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7305 Expr *RHS, bool isProperty) {
7306 // Check if RHS is an Objective-C object literal, which also can get
7307 // immediately zapped in a weak reference. Note that we explicitly
7308 // allow ObjCStringLiterals, since those are designed to never really die.
7309 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007310
Ted Kremenek64873352012-12-21 22:46:35 +00007311 // This enum needs to match with the 'select' in
7312 // warn_objc_arc_literal_assign (off-by-1).
7313 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7314 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7315 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007316
7317 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007318 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007319 << (isProperty ? 0 : 1)
7320 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007321
7322 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007323}
7324
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007325static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7326 Qualifiers::ObjCLifetime LT,
7327 Expr *RHS, bool isProperty) {
7328 // Strip off any implicit cast added to get to the one ARC-specific.
7329 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7330 if (cast->getCastKind() == CK_ARCConsumeObject) {
7331 S.Diag(Loc, diag::warn_arc_retained_assign)
7332 << (LT == Qualifiers::OCL_ExplicitNone)
7333 << (isProperty ? 0 : 1)
7334 << RHS->getSourceRange();
7335 return true;
7336 }
7337 RHS = cast->getSubExpr();
7338 }
7339
7340 if (LT == Qualifiers::OCL_Weak &&
7341 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7342 return true;
7343
7344 return false;
7345}
7346
Ted Kremenekb36234d2012-12-21 08:04:20 +00007347bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7348 QualType LHS, Expr *RHS) {
7349 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7350
7351 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7352 return false;
7353
7354 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7355 return true;
7356
7357 return false;
7358}
7359
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007360void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7361 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007362 QualType LHSType;
7363 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007364 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007365 ObjCPropertyRefExpr *PRE
7366 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7367 if (PRE && !PRE->isImplicitProperty()) {
7368 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7369 if (PD)
7370 LHSType = PD->getType();
7371 }
7372
7373 if (LHSType.isNull())
7374 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007375
7376 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7377
7378 if (LT == Qualifiers::OCL_Weak) {
7379 DiagnosticsEngine::Level Level =
7380 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7381 if (Level != DiagnosticsEngine::Ignored)
7382 getCurFunction()->markSafeWeakUse(LHS);
7383 }
7384
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007385 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7386 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007387
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007388 // FIXME. Check for other life times.
7389 if (LT != Qualifiers::OCL_None)
7390 return;
7391
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007392 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007393 if (PRE->isImplicitProperty())
7394 return;
7395 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7396 if (!PD)
7397 return;
7398
Bill Wendling44426052012-12-20 19:22:21 +00007399 unsigned Attributes = PD->getPropertyAttributes();
7400 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007401 // when 'assign' attribute was not explicitly specified
7402 // by user, ignore it and rely on property type itself
7403 // for lifetime info.
7404 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7405 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7406 LHSType->isObjCRetainableType())
7407 return;
7408
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007409 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007410 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007411 Diag(Loc, diag::warn_arc_retained_property_assign)
7412 << RHS->getSourceRange();
7413 return;
7414 }
7415 RHS = cast->getSubExpr();
7416 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007417 }
Bill Wendling44426052012-12-20 19:22:21 +00007418 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007419 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7420 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007421 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007422 }
7423}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007424
7425//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7426
7427namespace {
7428bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7429 SourceLocation StmtLoc,
7430 const NullStmt *Body) {
7431 // Do not warn if the body is a macro that expands to nothing, e.g:
7432 //
7433 // #define CALL(x)
7434 // if (condition)
7435 // CALL(0);
7436 //
7437 if (Body->hasLeadingEmptyMacro())
7438 return false;
7439
7440 // Get line numbers of statement and body.
7441 bool StmtLineInvalid;
7442 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7443 &StmtLineInvalid);
7444 if (StmtLineInvalid)
7445 return false;
7446
7447 bool BodyLineInvalid;
7448 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7449 &BodyLineInvalid);
7450 if (BodyLineInvalid)
7451 return false;
7452
7453 // Warn if null statement and body are on the same line.
7454 if (StmtLine != BodyLine)
7455 return false;
7456
7457 return true;
7458}
7459} // Unnamed namespace
7460
7461void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7462 const Stmt *Body,
7463 unsigned DiagID) {
7464 // Since this is a syntactic check, don't emit diagnostic for template
7465 // instantiations, this just adds noise.
7466 if (CurrentInstantiationScope)
7467 return;
7468
7469 // The body should be a null statement.
7470 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7471 if (!NBody)
7472 return;
7473
7474 // Do the usual checks.
7475 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7476 return;
7477
7478 Diag(NBody->getSemiLoc(), DiagID);
7479 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7480}
7481
7482void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7483 const Stmt *PossibleBody) {
7484 assert(!CurrentInstantiationScope); // Ensured by caller
7485
7486 SourceLocation StmtLoc;
7487 const Stmt *Body;
7488 unsigned DiagID;
7489 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7490 StmtLoc = FS->getRParenLoc();
7491 Body = FS->getBody();
7492 DiagID = diag::warn_empty_for_body;
7493 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7494 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7495 Body = WS->getBody();
7496 DiagID = diag::warn_empty_while_body;
7497 } else
7498 return; // Neither `for' nor `while'.
7499
7500 // The body should be a null statement.
7501 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7502 if (!NBody)
7503 return;
7504
7505 // Skip expensive checks if diagnostic is disabled.
7506 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7507 DiagnosticsEngine::Ignored)
7508 return;
7509
7510 // Do the usual checks.
7511 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7512 return;
7513
7514 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7515 // noise level low, emit diagnostics only if for/while is followed by a
7516 // CompoundStmt, e.g.:
7517 // for (int i = 0; i < n; i++);
7518 // {
7519 // a(i);
7520 // }
7521 // or if for/while is followed by a statement with more indentation
7522 // than for/while itself:
7523 // for (int i = 0; i < n; i++);
7524 // a(i);
7525 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7526 if (!ProbableTypo) {
7527 bool BodyColInvalid;
7528 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7529 PossibleBody->getLocStart(),
7530 &BodyColInvalid);
7531 if (BodyColInvalid)
7532 return;
7533
7534 bool StmtColInvalid;
7535 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7536 S->getLocStart(),
7537 &StmtColInvalid);
7538 if (StmtColInvalid)
7539 return;
7540
7541 if (BodyCol > StmtCol)
7542 ProbableTypo = true;
7543 }
7544
7545 if (ProbableTypo) {
7546 Diag(NBody->getSemiLoc(), DiagID);
7547 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7548 }
7549}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007550
7551//===--- Layout compatibility ----------------------------------------------//
7552
7553namespace {
7554
7555bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7556
7557/// \brief Check if two enumeration types are layout-compatible.
7558bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7559 // C++11 [dcl.enum] p8:
7560 // Two enumeration types are layout-compatible if they have the same
7561 // underlying type.
7562 return ED1->isComplete() && ED2->isComplete() &&
7563 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7564}
7565
7566/// \brief Check if two fields are layout-compatible.
7567bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7568 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7569 return false;
7570
7571 if (Field1->isBitField() != Field2->isBitField())
7572 return false;
7573
7574 if (Field1->isBitField()) {
7575 // Make sure that the bit-fields are the same length.
7576 unsigned Bits1 = Field1->getBitWidthValue(C);
7577 unsigned Bits2 = Field2->getBitWidthValue(C);
7578
7579 if (Bits1 != Bits2)
7580 return false;
7581 }
7582
7583 return true;
7584}
7585
7586/// \brief Check if two standard-layout structs are layout-compatible.
7587/// (C++11 [class.mem] p17)
7588bool isLayoutCompatibleStruct(ASTContext &C,
7589 RecordDecl *RD1,
7590 RecordDecl *RD2) {
7591 // If both records are C++ classes, check that base classes match.
7592 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7593 // If one of records is a CXXRecordDecl we are in C++ mode,
7594 // thus the other one is a CXXRecordDecl, too.
7595 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7596 // Check number of base classes.
7597 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7598 return false;
7599
7600 // Check the base classes.
7601 for (CXXRecordDecl::base_class_const_iterator
7602 Base1 = D1CXX->bases_begin(),
7603 BaseEnd1 = D1CXX->bases_end(),
7604 Base2 = D2CXX->bases_begin();
7605 Base1 != BaseEnd1;
7606 ++Base1, ++Base2) {
7607 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7608 return false;
7609 }
7610 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7611 // If only RD2 is a C++ class, it should have zero base classes.
7612 if (D2CXX->getNumBases() > 0)
7613 return false;
7614 }
7615
7616 // Check the fields.
7617 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7618 Field2End = RD2->field_end(),
7619 Field1 = RD1->field_begin(),
7620 Field1End = RD1->field_end();
7621 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7622 if (!isLayoutCompatible(C, *Field1, *Field2))
7623 return false;
7624 }
7625 if (Field1 != Field1End || Field2 != Field2End)
7626 return false;
7627
7628 return true;
7629}
7630
7631/// \brief Check if two standard-layout unions are layout-compatible.
7632/// (C++11 [class.mem] p18)
7633bool isLayoutCompatibleUnion(ASTContext &C,
7634 RecordDecl *RD1,
7635 RecordDecl *RD2) {
7636 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007637 for (auto *Field2 : RD2->fields())
7638 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007639
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007640 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007641 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7642 I = UnmatchedFields.begin(),
7643 E = UnmatchedFields.end();
7644
7645 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007646 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007647 bool Result = UnmatchedFields.erase(*I);
7648 (void) Result;
7649 assert(Result);
7650 break;
7651 }
7652 }
7653 if (I == E)
7654 return false;
7655 }
7656
7657 return UnmatchedFields.empty();
7658}
7659
7660bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7661 if (RD1->isUnion() != RD2->isUnion())
7662 return false;
7663
7664 if (RD1->isUnion())
7665 return isLayoutCompatibleUnion(C, RD1, RD2);
7666 else
7667 return isLayoutCompatibleStruct(C, RD1, RD2);
7668}
7669
7670/// \brief Check if two types are layout-compatible in C++11 sense.
7671bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7672 if (T1.isNull() || T2.isNull())
7673 return false;
7674
7675 // C++11 [basic.types] p11:
7676 // If two types T1 and T2 are the same type, then T1 and T2 are
7677 // layout-compatible types.
7678 if (C.hasSameType(T1, T2))
7679 return true;
7680
7681 T1 = T1.getCanonicalType().getUnqualifiedType();
7682 T2 = T2.getCanonicalType().getUnqualifiedType();
7683
7684 const Type::TypeClass TC1 = T1->getTypeClass();
7685 const Type::TypeClass TC2 = T2->getTypeClass();
7686
7687 if (TC1 != TC2)
7688 return false;
7689
7690 if (TC1 == Type::Enum) {
7691 return isLayoutCompatible(C,
7692 cast<EnumType>(T1)->getDecl(),
7693 cast<EnumType>(T2)->getDecl());
7694 } else if (TC1 == Type::Record) {
7695 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7696 return false;
7697
7698 return isLayoutCompatible(C,
7699 cast<RecordType>(T1)->getDecl(),
7700 cast<RecordType>(T2)->getDecl());
7701 }
7702
7703 return false;
7704}
7705}
7706
7707//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7708
7709namespace {
7710/// \brief Given a type tag expression find the type tag itself.
7711///
7712/// \param TypeExpr Type tag expression, as it appears in user's code.
7713///
7714/// \param VD Declaration of an identifier that appears in a type tag.
7715///
7716/// \param MagicValue Type tag magic value.
7717bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7718 const ValueDecl **VD, uint64_t *MagicValue) {
7719 while(true) {
7720 if (!TypeExpr)
7721 return false;
7722
7723 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7724
7725 switch (TypeExpr->getStmtClass()) {
7726 case Stmt::UnaryOperatorClass: {
7727 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7728 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7729 TypeExpr = UO->getSubExpr();
7730 continue;
7731 }
7732 return false;
7733 }
7734
7735 case Stmt::DeclRefExprClass: {
7736 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7737 *VD = DRE->getDecl();
7738 return true;
7739 }
7740
7741 case Stmt::IntegerLiteralClass: {
7742 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7743 llvm::APInt MagicValueAPInt = IL->getValue();
7744 if (MagicValueAPInt.getActiveBits() <= 64) {
7745 *MagicValue = MagicValueAPInt.getZExtValue();
7746 return true;
7747 } else
7748 return false;
7749 }
7750
7751 case Stmt::BinaryConditionalOperatorClass:
7752 case Stmt::ConditionalOperatorClass: {
7753 const AbstractConditionalOperator *ACO =
7754 cast<AbstractConditionalOperator>(TypeExpr);
7755 bool Result;
7756 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7757 if (Result)
7758 TypeExpr = ACO->getTrueExpr();
7759 else
7760 TypeExpr = ACO->getFalseExpr();
7761 continue;
7762 }
7763 return false;
7764 }
7765
7766 case Stmt::BinaryOperatorClass: {
7767 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7768 if (BO->getOpcode() == BO_Comma) {
7769 TypeExpr = BO->getRHS();
7770 continue;
7771 }
7772 return false;
7773 }
7774
7775 default:
7776 return false;
7777 }
7778 }
7779}
7780
7781/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7782///
7783/// \param TypeExpr Expression that specifies a type tag.
7784///
7785/// \param MagicValues Registered magic values.
7786///
7787/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7788/// kind.
7789///
7790/// \param TypeInfo Information about the corresponding C type.
7791///
7792/// \returns true if the corresponding C type was found.
7793bool GetMatchingCType(
7794 const IdentifierInfo *ArgumentKind,
7795 const Expr *TypeExpr, const ASTContext &Ctx,
7796 const llvm::DenseMap<Sema::TypeTagMagicValue,
7797 Sema::TypeTagData> *MagicValues,
7798 bool &FoundWrongKind,
7799 Sema::TypeTagData &TypeInfo) {
7800 FoundWrongKind = false;
7801
7802 // Variable declaration that has type_tag_for_datatype attribute.
7803 const ValueDecl *VD = NULL;
7804
7805 uint64_t MagicValue;
7806
7807 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7808 return false;
7809
7810 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007811 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007812 if (I->getArgumentKind() != ArgumentKind) {
7813 FoundWrongKind = true;
7814 return false;
7815 }
7816 TypeInfo.Type = I->getMatchingCType();
7817 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7818 TypeInfo.MustBeNull = I->getMustBeNull();
7819 return true;
7820 }
7821 return false;
7822 }
7823
7824 if (!MagicValues)
7825 return false;
7826
7827 llvm::DenseMap<Sema::TypeTagMagicValue,
7828 Sema::TypeTagData>::const_iterator I =
7829 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7830 if (I == MagicValues->end())
7831 return false;
7832
7833 TypeInfo = I->second;
7834 return true;
7835}
7836} // unnamed namespace
7837
7838void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7839 uint64_t MagicValue, QualType Type,
7840 bool LayoutCompatible,
7841 bool MustBeNull) {
7842 if (!TypeTagForDatatypeMagicValues)
7843 TypeTagForDatatypeMagicValues.reset(
7844 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7845
7846 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7847 (*TypeTagForDatatypeMagicValues)[Magic] =
7848 TypeTagData(Type, LayoutCompatible, MustBeNull);
7849}
7850
7851namespace {
7852bool IsSameCharType(QualType T1, QualType T2) {
7853 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7854 if (!BT1)
7855 return false;
7856
7857 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7858 if (!BT2)
7859 return false;
7860
7861 BuiltinType::Kind T1Kind = BT1->getKind();
7862 BuiltinType::Kind T2Kind = BT2->getKind();
7863
7864 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7865 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7866 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7867 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7868}
7869} // unnamed namespace
7870
7871void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7872 const Expr * const *ExprArgs) {
7873 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7874 bool IsPointerAttr = Attr->getIsPointer();
7875
7876 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7877 bool FoundWrongKind;
7878 TypeTagData TypeInfo;
7879 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7880 TypeTagForDatatypeMagicValues.get(),
7881 FoundWrongKind, TypeInfo)) {
7882 if (FoundWrongKind)
7883 Diag(TypeTagExpr->getExprLoc(),
7884 diag::warn_type_tag_for_datatype_wrong_kind)
7885 << TypeTagExpr->getSourceRange();
7886 return;
7887 }
7888
7889 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7890 if (IsPointerAttr) {
7891 // Skip implicit cast of pointer to `void *' (as a function argument).
7892 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007893 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007894 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007895 ArgumentExpr = ICE->getSubExpr();
7896 }
7897 QualType ArgumentType = ArgumentExpr->getType();
7898
7899 // Passing a `void*' pointer shouldn't trigger a warning.
7900 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7901 return;
7902
7903 if (TypeInfo.MustBeNull) {
7904 // Type tag with matching void type requires a null pointer.
7905 if (!ArgumentExpr->isNullPointerConstant(Context,
7906 Expr::NPC_ValueDependentIsNotNull)) {
7907 Diag(ArgumentExpr->getExprLoc(),
7908 diag::warn_type_safety_null_pointer_required)
7909 << ArgumentKind->getName()
7910 << ArgumentExpr->getSourceRange()
7911 << TypeTagExpr->getSourceRange();
7912 }
7913 return;
7914 }
7915
7916 QualType RequiredType = TypeInfo.Type;
7917 if (IsPointerAttr)
7918 RequiredType = Context.getPointerType(RequiredType);
7919
7920 bool mismatch = false;
7921 if (!TypeInfo.LayoutCompatible) {
7922 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7923
7924 // C++11 [basic.fundamental] p1:
7925 // Plain char, signed char, and unsigned char are three distinct types.
7926 //
7927 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7928 // char' depending on the current char signedness mode.
7929 if (mismatch)
7930 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7931 RequiredType->getPointeeType())) ||
7932 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7933 mismatch = false;
7934 } else
7935 if (IsPointerAttr)
7936 mismatch = !isLayoutCompatible(Context,
7937 ArgumentType->getPointeeType(),
7938 RequiredType->getPointeeType());
7939 else
7940 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7941
7942 if (mismatch)
7943 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007944 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007945 << TypeInfo.LayoutCompatible << RequiredType
7946 << ArgumentExpr->getSourceRange()
7947 << TypeTagExpr->getSourceRange();
7948}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007949