blob: 74ca197b8de3b4599a35180b9cbcba08a1573d64 [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
Bob Wilsond836d3d2014-03-09 23:02:27 +0000604 // For NEON intrinsics which take an immediate value as part of the
Nate Begemand773fe62010-06-13 04:47:52 +0000605 // 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.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000733 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000734 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
735 e = NonNull->args_end();
736 i != e; ++i) {
737 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000738 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000739 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000740
741 // Check the attributes on the parameters.
742 ArrayRef<ParmVarDecl*> parms;
743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
744 parms = FD->parameters();
745 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
746 parms = MD->parameters();
747
748 unsigned argIndex = 0;
749 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
750 I != E; ++I, ++argIndex) {
751 const ParmVarDecl *PVD = *I;
752 if (PVD->hasAttr<NonNullAttr>())
753 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
754 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000755}
756
Richard Smith55ce3522012-06-25 20:30:08 +0000757/// Handles the checks for format strings, non-POD arguments to vararg
758/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000759void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
760 unsigned NumParams, bool IsMemberFunction,
761 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000762 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000763 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000764 if (CurContext->isDependentContext())
765 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000766
Ted Kremenekb8176da2010-09-09 04:33:05 +0000767 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000768 llvm::SmallBitVector CheckedVarArgs;
769 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000770 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000771 // Only create vector if there are format attributes.
772 CheckedVarArgs.resize(Args.size());
773
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000774 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000775 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000776 }
Richard Smithd7293d72013-08-05 18:49:43 +0000777 }
Richard Smith55ce3522012-06-25 20:30:08 +0000778
779 // Refuse POD arguments that weren't caught by the format string
780 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000781 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000782 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000783 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000784 if (const Expr *Arg = Args[ArgIdx]) {
785 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
786 checkVariadicArgument(Arg, CallType);
787 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000788 }
Richard Smithd7293d72013-08-05 18:49:43 +0000789 }
Mike Stump11289f42009-09-09 15:08:12 +0000790
Richard Trieu41bc0992013-06-22 00:20:41 +0000791 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000792 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000793
Richard Trieu41bc0992013-06-22 00:20:41 +0000794 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +0000795 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
796 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000797 }
Richard Smith55ce3522012-06-25 20:30:08 +0000798}
799
800/// CheckConstructorCall - Check a constructor call for correctness and safety
801/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000802void Sema::CheckConstructorCall(FunctionDecl *FDecl,
803 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000804 const FunctionProtoType *Proto,
805 SourceLocation Loc) {
806 VariadicCallType CallType =
807 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000808 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000809 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
810}
811
812/// CheckFunctionCall - Check a direct function call for various correctness
813/// and safety properties not strictly enforced by the C type system.
814bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
815 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000816 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
817 isa<CXXMethodDecl>(FDecl);
818 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
819 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000820 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
821 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000822 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000823 Expr** Args = TheCall->getArgs();
824 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000825 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000826 // If this is a call to a member operator, hide the first argument
827 // from checkCall.
828 // FIXME: Our choice of AST representation here is less than ideal.
829 ++Args;
830 --NumArgs;
831 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000832 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000833 IsMemberFunction, TheCall->getRParenLoc(),
834 TheCall->getCallee()->getSourceRange(), CallType);
835
836 IdentifierInfo *FnInfo = FDecl->getIdentifier();
837 // None of the checks below are needed for functions that don't have
838 // simple names (e.g., C++ conversion functions).
839 if (!FnInfo)
840 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000841
Richard Trieu7eb0b2c2014-02-26 01:17:28 +0000842 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
843
Anna Zaks22122702012-01-17 00:37:07 +0000844 unsigned CMId = FDecl->getMemoryFunctionKind();
845 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000846 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000847
Anna Zaks201d4892012-01-13 21:52:01 +0000848 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000849 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000850 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000851 else if (CMId == Builtin::BIstrncat)
852 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000853 else
Anna Zaks22122702012-01-17 00:37:07 +0000854 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000855
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000856 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000857}
858
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000859bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000860 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000861 VariadicCallType CallType =
862 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000863
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000864 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000865 /*IsMemberFunction=*/false,
866 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000867
868 return false;
869}
870
Richard Trieu664c4c62013-06-20 21:03:13 +0000871bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
872 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000873 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
874 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000875 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000876
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000877 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000878 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000879 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000880
Richard Trieu664c4c62013-06-20 21:03:13 +0000881 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000882 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000883 CallType = VariadicDoesNotApply;
884 } else if (Ty->isBlockPointerType()) {
885 CallType = VariadicBlock;
886 } else { // Ty->isFunctionPointerType()
887 CallType = VariadicFunction;
888 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000889 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000890
Alp Toker9cacbab2014-01-20 20:26:09 +0000891 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
892 TheCall->getNumArgs()),
893 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000894 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000895
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000896 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000897}
898
Richard Trieu41bc0992013-06-22 00:20:41 +0000899/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
900/// such as function pointers returned from functions.
901bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
902 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
903 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000904 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000905
Alp Toker9cacbab2014-01-20 20:26:09 +0000906 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
907 TheCall->getArgs(), TheCall->getNumArgs()),
908 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000909 TheCall->getCallee()->getSourceRange(), CallType);
910
911 return false;
912}
913
Tim Northovere94a34c2014-03-11 10:49:14 +0000914static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
915 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
916 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
917 return false;
918
919 switch (Op) {
920 case AtomicExpr::AO__c11_atomic_init:
921 llvm_unreachable("There is no ordering argument for an init");
922
923 case AtomicExpr::AO__c11_atomic_load:
924 case AtomicExpr::AO__atomic_load_n:
925 case AtomicExpr::AO__atomic_load:
926 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
927 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
928
929 case AtomicExpr::AO__c11_atomic_store:
930 case AtomicExpr::AO__atomic_store:
931 case AtomicExpr::AO__atomic_store_n:
932 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
933 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
934 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
935
936 default:
937 return true;
938 }
939}
940
Richard Smithfeea8832012-04-12 05:08:17 +0000941ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
942 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000943 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
944 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000945
Richard Smithfeea8832012-04-12 05:08:17 +0000946 // All these operations take one of the following forms:
947 enum {
948 // C __c11_atomic_init(A *, C)
949 Init,
950 // C __c11_atomic_load(A *, int)
951 Load,
952 // void __atomic_load(A *, CP, int)
953 Copy,
954 // C __c11_atomic_add(A *, M, int)
955 Arithmetic,
956 // C __atomic_exchange_n(A *, CP, int)
957 Xchg,
958 // void __atomic_exchange(A *, C *, CP, int)
959 GNUXchg,
960 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
961 C11CmpXchg,
962 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
963 GNUCmpXchg
964 } Form = Init;
965 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
966 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
967 // where:
968 // C is an appropriate type,
969 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
970 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
971 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
972 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000973
Richard Smithfeea8832012-04-12 05:08:17 +0000974 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
975 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
976 && "need to update code for modified C11 atomics");
977 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
978 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
979 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
980 Op == AtomicExpr::AO__atomic_store_n ||
981 Op == AtomicExpr::AO__atomic_exchange_n ||
982 Op == AtomicExpr::AO__atomic_compare_exchange_n;
983 bool IsAddSub = false;
984
985 switch (Op) {
986 case AtomicExpr::AO__c11_atomic_init:
987 Form = Init;
988 break;
989
990 case AtomicExpr::AO__c11_atomic_load:
991 case AtomicExpr::AO__atomic_load_n:
992 Form = Load;
993 break;
994
995 case AtomicExpr::AO__c11_atomic_store:
996 case AtomicExpr::AO__atomic_load:
997 case AtomicExpr::AO__atomic_store:
998 case AtomicExpr::AO__atomic_store_n:
999 Form = Copy;
1000 break;
1001
1002 case AtomicExpr::AO__c11_atomic_fetch_add:
1003 case AtomicExpr::AO__c11_atomic_fetch_sub:
1004 case AtomicExpr::AO__atomic_fetch_add:
1005 case AtomicExpr::AO__atomic_fetch_sub:
1006 case AtomicExpr::AO__atomic_add_fetch:
1007 case AtomicExpr::AO__atomic_sub_fetch:
1008 IsAddSub = true;
1009 // Fall through.
1010 case AtomicExpr::AO__c11_atomic_fetch_and:
1011 case AtomicExpr::AO__c11_atomic_fetch_or:
1012 case AtomicExpr::AO__c11_atomic_fetch_xor:
1013 case AtomicExpr::AO__atomic_fetch_and:
1014 case AtomicExpr::AO__atomic_fetch_or:
1015 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001016 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001017 case AtomicExpr::AO__atomic_and_fetch:
1018 case AtomicExpr::AO__atomic_or_fetch:
1019 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001020 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001021 Form = Arithmetic;
1022 break;
1023
1024 case AtomicExpr::AO__c11_atomic_exchange:
1025 case AtomicExpr::AO__atomic_exchange_n:
1026 Form = Xchg;
1027 break;
1028
1029 case AtomicExpr::AO__atomic_exchange:
1030 Form = GNUXchg;
1031 break;
1032
1033 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1034 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1035 Form = C11CmpXchg;
1036 break;
1037
1038 case AtomicExpr::AO__atomic_compare_exchange:
1039 case AtomicExpr::AO__atomic_compare_exchange_n:
1040 Form = GNUCmpXchg;
1041 break;
1042 }
1043
1044 // Check we have the right number of arguments.
1045 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001046 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001047 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001048 << TheCall->getCallee()->getSourceRange();
1049 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001050 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1051 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001052 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001053 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001054 << TheCall->getCallee()->getSourceRange();
1055 return ExprError();
1056 }
1057
Richard Smithfeea8832012-04-12 05:08:17 +00001058 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001059 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001060 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1061 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1062 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001063 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001064 << Ptr->getType() << Ptr->getSourceRange();
1065 return ExprError();
1066 }
1067
Richard Smithfeea8832012-04-12 05:08:17 +00001068 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1069 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1070 QualType ValType = AtomTy; // 'C'
1071 if (IsC11) {
1072 if (!AtomTy->isAtomicType()) {
1073 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1074 << Ptr->getType() << Ptr->getSourceRange();
1075 return ExprError();
1076 }
Richard Smithe00921a2012-09-15 06:09:58 +00001077 if (AtomTy.isConstQualified()) {
1078 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1079 << Ptr->getType() << Ptr->getSourceRange();
1080 return ExprError();
1081 }
Richard Smithfeea8832012-04-12 05:08:17 +00001082 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001083 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001084
Richard Smithfeea8832012-04-12 05:08:17 +00001085 // For an arithmetic operation, the implied arithmetic must be well-formed.
1086 if (Form == Arithmetic) {
1087 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1088 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1089 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1090 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1091 return ExprError();
1092 }
1093 if (!IsAddSub && !ValType->isIntegerType()) {
1094 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1095 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1096 return ExprError();
1097 }
1098 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1099 // For __atomic_*_n operations, the value type must be a scalar integral or
1100 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001101 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001102 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1103 return ExprError();
1104 }
1105
Eli Friedmanaa769812013-09-11 03:49:34 +00001106 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1107 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001108 // For GNU atomics, require a trivially-copyable type. This is not part of
1109 // the GNU atomics specification, but we enforce it for sanity.
1110 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001111 << Ptr->getType() << Ptr->getSourceRange();
1112 return ExprError();
1113 }
1114
Richard Smithfeea8832012-04-12 05:08:17 +00001115 // FIXME: For any builtin other than a load, the ValType must not be
1116 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001117
1118 switch (ValType.getObjCLifetime()) {
1119 case Qualifiers::OCL_None:
1120 case Qualifiers::OCL_ExplicitNone:
1121 // okay
1122 break;
1123
1124 case Qualifiers::OCL_Weak:
1125 case Qualifiers::OCL_Strong:
1126 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001127 // FIXME: Can this happen? By this point, ValType should be known
1128 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001129 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1130 << ValType << Ptr->getSourceRange();
1131 return ExprError();
1132 }
1133
1134 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001135 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001136 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001137 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001138 ResultType = Context.BoolTy;
1139
Richard Smithfeea8832012-04-12 05:08:17 +00001140 // The type of a parameter passed 'by value'. In the GNU atomics, such
1141 // arguments are actually passed as pointers.
1142 QualType ByValType = ValType; // 'CP'
1143 if (!IsC11 && !IsN)
1144 ByValType = Ptr->getType();
1145
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001146 // The first argument --- the pointer --- has a fixed type; we
1147 // deduce the types of the rest of the arguments accordingly. Walk
1148 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001149 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001150 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001151 if (i < NumVals[Form] + 1) {
1152 switch (i) {
1153 case 1:
1154 // The second argument is the non-atomic operand. For arithmetic, this
1155 // is always passed by value, and for a compare_exchange it is always
1156 // passed by address. For the rest, GNU uses by-address and C11 uses
1157 // by-value.
1158 assert(Form != Load);
1159 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1160 Ty = ValType;
1161 else if (Form == Copy || Form == Xchg)
1162 Ty = ByValType;
1163 else if (Form == Arithmetic)
1164 Ty = Context.getPointerDiffType();
1165 else
1166 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1167 break;
1168 case 2:
1169 // The third argument to compare_exchange / GNU exchange is a
1170 // (pointer to a) desired value.
1171 Ty = ByValType;
1172 break;
1173 case 3:
1174 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1175 Ty = Context.BoolTy;
1176 break;
1177 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001178 } else {
1179 // The order(s) are always converted to int.
1180 Ty = Context.IntTy;
1181 }
Richard Smithfeea8832012-04-12 05:08:17 +00001182
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001183 InitializedEntity Entity =
1184 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001185 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001186 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1187 if (Arg.isInvalid())
1188 return true;
1189 TheCall->setArg(i, Arg.get());
1190 }
1191
Richard Smithfeea8832012-04-12 05:08:17 +00001192 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001193 SmallVector<Expr*, 5> SubExprs;
1194 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001195 switch (Form) {
1196 case Init:
1197 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001198 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001199 break;
1200 case Load:
1201 SubExprs.push_back(TheCall->getArg(1)); // Order
1202 break;
1203 case Copy:
1204 case Arithmetic:
1205 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001206 SubExprs.push_back(TheCall->getArg(2)); // Order
1207 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001208 break;
1209 case GNUXchg:
1210 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1211 SubExprs.push_back(TheCall->getArg(3)); // Order
1212 SubExprs.push_back(TheCall->getArg(1)); // Val1
1213 SubExprs.push_back(TheCall->getArg(2)); // Val2
1214 break;
1215 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001216 SubExprs.push_back(TheCall->getArg(3)); // Order
1217 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001218 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001219 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001220 break;
1221 case GNUCmpXchg:
1222 SubExprs.push_back(TheCall->getArg(4)); // Order
1223 SubExprs.push_back(TheCall->getArg(1)); // Val1
1224 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1225 SubExprs.push_back(TheCall->getArg(2)); // Val2
1226 SubExprs.push_back(TheCall->getArg(3)); // Weak
1227 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001228 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001229
1230 if (SubExprs.size() >= 2 && Form != Init) {
1231 llvm::APSInt Result(32);
1232 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1233 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001234 Diag(SubExprs[1]->getLocStart(),
1235 diag::warn_atomic_op_has_invalid_memory_order)
1236 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001237 }
1238
Fariborz Jahanian615de762013-05-28 17:37:39 +00001239 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1240 SubExprs, ResultType, Op,
1241 TheCall->getRParenLoc());
1242
1243 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1244 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1245 Context.AtomicUsesUnsupportedLibcall(AE))
1246 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1247 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001248
Fariborz Jahanian615de762013-05-28 17:37:39 +00001249 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001250}
1251
1252
John McCall29ad95b2011-08-27 01:09:30 +00001253/// checkBuiltinArgument - Given a call to a builtin function, perform
1254/// normal type-checking on the given argument, updating the call in
1255/// place. This is useful when a builtin function requires custom
1256/// type-checking for some of its arguments but not necessarily all of
1257/// them.
1258///
1259/// Returns true on error.
1260static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1261 FunctionDecl *Fn = E->getDirectCallee();
1262 assert(Fn && "builtin call without direct callee!");
1263
1264 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1265 InitializedEntity Entity =
1266 InitializedEntity::InitializeParameter(S.Context, Param);
1267
1268 ExprResult Arg = E->getArg(0);
1269 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1270 if (Arg.isInvalid())
1271 return true;
1272
1273 E->setArg(ArgIndex, Arg.take());
1274 return false;
1275}
1276
Chris Lattnerdc046542009-05-08 06:58:22 +00001277/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1278/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1279/// type of its first argument. The main ActOnCallExpr routines have already
1280/// promoted the types of arguments because all of these calls are prototyped as
1281/// void(...).
1282///
1283/// This function goes through and does final semantic checking for these
1284/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001285ExprResult
1286Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001287 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001288 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1289 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1290
1291 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001292 if (TheCall->getNumArgs() < 1) {
1293 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1294 << 0 << 1 << TheCall->getNumArgs()
1295 << TheCall->getCallee()->getSourceRange();
1296 return ExprError();
1297 }
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattnerdc046542009-05-08 06:58:22 +00001299 // Inspect the first argument of the atomic builtin. This should always be
1300 // a pointer type, whose element is an integral scalar or pointer type.
1301 // Because it is a pointer type, we don't have to worry about any implicit
1302 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001303 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001304 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001305 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1306 if (FirstArgResult.isInvalid())
1307 return ExprError();
1308 FirstArg = FirstArgResult.take();
1309 TheCall->setArg(0, FirstArg);
1310
John McCall31168b02011-06-15 23:02:42 +00001311 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1312 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001313 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1314 << FirstArg->getType() << FirstArg->getSourceRange();
1315 return ExprError();
1316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
John McCall31168b02011-06-15 23:02:42 +00001318 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001319 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001320 !ValType->isBlockPointerType()) {
1321 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1322 << FirstArg->getType() << FirstArg->getSourceRange();
1323 return ExprError();
1324 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001325
John McCall31168b02011-06-15 23:02:42 +00001326 switch (ValType.getObjCLifetime()) {
1327 case Qualifiers::OCL_None:
1328 case Qualifiers::OCL_ExplicitNone:
1329 // okay
1330 break;
1331
1332 case Qualifiers::OCL_Weak:
1333 case Qualifiers::OCL_Strong:
1334 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001335 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001336 << ValType << FirstArg->getSourceRange();
1337 return ExprError();
1338 }
1339
John McCallb50451a2011-10-05 07:41:44 +00001340 // Strip any qualifiers off ValType.
1341 ValType = ValType.getUnqualifiedType();
1342
Chandler Carruth3973af72010-07-18 20:54:12 +00001343 // The majority of builtins return a value, but a few have special return
1344 // types, so allow them to override appropriately below.
1345 QualType ResultType = ValType;
1346
Chris Lattnerdc046542009-05-08 06:58:22 +00001347 // We need to figure out which concrete builtin this maps onto. For example,
1348 // __sync_fetch_and_add with a 2 byte object turns into
1349 // __sync_fetch_and_add_2.
1350#define BUILTIN_ROW(x) \
1351 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1352 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001353
Chris Lattnerdc046542009-05-08 06:58:22 +00001354 static const unsigned BuiltinIndices[][5] = {
1355 BUILTIN_ROW(__sync_fetch_and_add),
1356 BUILTIN_ROW(__sync_fetch_and_sub),
1357 BUILTIN_ROW(__sync_fetch_and_or),
1358 BUILTIN_ROW(__sync_fetch_and_and),
1359 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001360
Chris Lattnerdc046542009-05-08 06:58:22 +00001361 BUILTIN_ROW(__sync_add_and_fetch),
1362 BUILTIN_ROW(__sync_sub_and_fetch),
1363 BUILTIN_ROW(__sync_and_and_fetch),
1364 BUILTIN_ROW(__sync_or_and_fetch),
1365 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001366
Chris Lattnerdc046542009-05-08 06:58:22 +00001367 BUILTIN_ROW(__sync_val_compare_and_swap),
1368 BUILTIN_ROW(__sync_bool_compare_and_swap),
1369 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001370 BUILTIN_ROW(__sync_lock_release),
1371 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001372 };
Mike Stump11289f42009-09-09 15:08:12 +00001373#undef BUILTIN_ROW
1374
Chris Lattnerdc046542009-05-08 06:58:22 +00001375 // Determine the index of the size.
1376 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001377 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001378 case 1: SizeIndex = 0; break;
1379 case 2: SizeIndex = 1; break;
1380 case 4: SizeIndex = 2; break;
1381 case 8: SizeIndex = 3; break;
1382 case 16: SizeIndex = 4; break;
1383 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001384 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1385 << FirstArg->getType() << FirstArg->getSourceRange();
1386 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001387 }
Mike Stump11289f42009-09-09 15:08:12 +00001388
Chris Lattnerdc046542009-05-08 06:58:22 +00001389 // Each of these builtins has one pointer argument, followed by some number of
1390 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1391 // that we ignore. Find out which row of BuiltinIndices to read from as well
1392 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001393 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001394 unsigned BuiltinIndex, NumFixed = 1;
1395 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001396 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001397 case Builtin::BI__sync_fetch_and_add:
1398 case Builtin::BI__sync_fetch_and_add_1:
1399 case Builtin::BI__sync_fetch_and_add_2:
1400 case Builtin::BI__sync_fetch_and_add_4:
1401 case Builtin::BI__sync_fetch_and_add_8:
1402 case Builtin::BI__sync_fetch_and_add_16:
1403 BuiltinIndex = 0;
1404 break;
1405
1406 case Builtin::BI__sync_fetch_and_sub:
1407 case Builtin::BI__sync_fetch_and_sub_1:
1408 case Builtin::BI__sync_fetch_and_sub_2:
1409 case Builtin::BI__sync_fetch_and_sub_4:
1410 case Builtin::BI__sync_fetch_and_sub_8:
1411 case Builtin::BI__sync_fetch_and_sub_16:
1412 BuiltinIndex = 1;
1413 break;
1414
1415 case Builtin::BI__sync_fetch_and_or:
1416 case Builtin::BI__sync_fetch_and_or_1:
1417 case Builtin::BI__sync_fetch_and_or_2:
1418 case Builtin::BI__sync_fetch_and_or_4:
1419 case Builtin::BI__sync_fetch_and_or_8:
1420 case Builtin::BI__sync_fetch_and_or_16:
1421 BuiltinIndex = 2;
1422 break;
1423
1424 case Builtin::BI__sync_fetch_and_and:
1425 case Builtin::BI__sync_fetch_and_and_1:
1426 case Builtin::BI__sync_fetch_and_and_2:
1427 case Builtin::BI__sync_fetch_and_and_4:
1428 case Builtin::BI__sync_fetch_and_and_8:
1429 case Builtin::BI__sync_fetch_and_and_16:
1430 BuiltinIndex = 3;
1431 break;
Mike Stump11289f42009-09-09 15:08:12 +00001432
Douglas Gregor73722482011-11-28 16:30:08 +00001433 case Builtin::BI__sync_fetch_and_xor:
1434 case Builtin::BI__sync_fetch_and_xor_1:
1435 case Builtin::BI__sync_fetch_and_xor_2:
1436 case Builtin::BI__sync_fetch_and_xor_4:
1437 case Builtin::BI__sync_fetch_and_xor_8:
1438 case Builtin::BI__sync_fetch_and_xor_16:
1439 BuiltinIndex = 4;
1440 break;
1441
1442 case Builtin::BI__sync_add_and_fetch:
1443 case Builtin::BI__sync_add_and_fetch_1:
1444 case Builtin::BI__sync_add_and_fetch_2:
1445 case Builtin::BI__sync_add_and_fetch_4:
1446 case Builtin::BI__sync_add_and_fetch_8:
1447 case Builtin::BI__sync_add_and_fetch_16:
1448 BuiltinIndex = 5;
1449 break;
1450
1451 case Builtin::BI__sync_sub_and_fetch:
1452 case Builtin::BI__sync_sub_and_fetch_1:
1453 case Builtin::BI__sync_sub_and_fetch_2:
1454 case Builtin::BI__sync_sub_and_fetch_4:
1455 case Builtin::BI__sync_sub_and_fetch_8:
1456 case Builtin::BI__sync_sub_and_fetch_16:
1457 BuiltinIndex = 6;
1458 break;
1459
1460 case Builtin::BI__sync_and_and_fetch:
1461 case Builtin::BI__sync_and_and_fetch_1:
1462 case Builtin::BI__sync_and_and_fetch_2:
1463 case Builtin::BI__sync_and_and_fetch_4:
1464 case Builtin::BI__sync_and_and_fetch_8:
1465 case Builtin::BI__sync_and_and_fetch_16:
1466 BuiltinIndex = 7;
1467 break;
1468
1469 case Builtin::BI__sync_or_and_fetch:
1470 case Builtin::BI__sync_or_and_fetch_1:
1471 case Builtin::BI__sync_or_and_fetch_2:
1472 case Builtin::BI__sync_or_and_fetch_4:
1473 case Builtin::BI__sync_or_and_fetch_8:
1474 case Builtin::BI__sync_or_and_fetch_16:
1475 BuiltinIndex = 8;
1476 break;
1477
1478 case Builtin::BI__sync_xor_and_fetch:
1479 case Builtin::BI__sync_xor_and_fetch_1:
1480 case Builtin::BI__sync_xor_and_fetch_2:
1481 case Builtin::BI__sync_xor_and_fetch_4:
1482 case Builtin::BI__sync_xor_and_fetch_8:
1483 case Builtin::BI__sync_xor_and_fetch_16:
1484 BuiltinIndex = 9;
1485 break;
Mike Stump11289f42009-09-09 15:08:12 +00001486
Chris Lattnerdc046542009-05-08 06:58:22 +00001487 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001488 case Builtin::BI__sync_val_compare_and_swap_1:
1489 case Builtin::BI__sync_val_compare_and_swap_2:
1490 case Builtin::BI__sync_val_compare_and_swap_4:
1491 case Builtin::BI__sync_val_compare_and_swap_8:
1492 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001493 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001494 NumFixed = 2;
1495 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001496
Chris Lattnerdc046542009-05-08 06:58:22 +00001497 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001498 case Builtin::BI__sync_bool_compare_and_swap_1:
1499 case Builtin::BI__sync_bool_compare_and_swap_2:
1500 case Builtin::BI__sync_bool_compare_and_swap_4:
1501 case Builtin::BI__sync_bool_compare_and_swap_8:
1502 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001503 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001504 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001505 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001506 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001507
1508 case Builtin::BI__sync_lock_test_and_set:
1509 case Builtin::BI__sync_lock_test_and_set_1:
1510 case Builtin::BI__sync_lock_test_and_set_2:
1511 case Builtin::BI__sync_lock_test_and_set_4:
1512 case Builtin::BI__sync_lock_test_and_set_8:
1513 case Builtin::BI__sync_lock_test_and_set_16:
1514 BuiltinIndex = 12;
1515 break;
1516
Chris Lattnerdc046542009-05-08 06:58:22 +00001517 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001518 case Builtin::BI__sync_lock_release_1:
1519 case Builtin::BI__sync_lock_release_2:
1520 case Builtin::BI__sync_lock_release_4:
1521 case Builtin::BI__sync_lock_release_8:
1522 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001523 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001524 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001525 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001526 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001527
1528 case Builtin::BI__sync_swap:
1529 case Builtin::BI__sync_swap_1:
1530 case Builtin::BI__sync_swap_2:
1531 case Builtin::BI__sync_swap_4:
1532 case Builtin::BI__sync_swap_8:
1533 case Builtin::BI__sync_swap_16:
1534 BuiltinIndex = 14;
1535 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattnerdc046542009-05-08 06:58:22 +00001538 // Now that we know how many fixed arguments we expect, first check that we
1539 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001540 if (TheCall->getNumArgs() < 1+NumFixed) {
1541 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1542 << 0 << 1+NumFixed << TheCall->getNumArgs()
1543 << TheCall->getCallee()->getSourceRange();
1544 return ExprError();
1545 }
Mike Stump11289f42009-09-09 15:08:12 +00001546
Chris Lattner5b9241b2009-05-08 15:36:58 +00001547 // Get the decl for the concrete builtin from this, we can tell what the
1548 // concrete integer type we should convert to is.
1549 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1550 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001551 FunctionDecl *NewBuiltinDecl;
1552 if (NewBuiltinID == BuiltinID)
1553 NewBuiltinDecl = FDecl;
1554 else {
1555 // Perform builtin lookup to avoid redeclaring it.
1556 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1557 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1558 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1559 assert(Res.getFoundDecl());
1560 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1561 if (NewBuiltinDecl == 0)
1562 return ExprError();
1563 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001564
John McCallcf142162010-08-07 06:22:56 +00001565 // The first argument --- the pointer --- has a fixed type; we
1566 // deduce the types of the rest of the arguments accordingly. Walk
1567 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001568 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001569 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001570
Chris Lattnerdc046542009-05-08 06:58:22 +00001571 // GCC does an implicit conversion to the pointer or integer ValType. This
1572 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001573 // Initialize the argument.
1574 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1575 ValType, /*consume*/ false);
1576 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001577 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001578 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001579
Chris Lattnerdc046542009-05-08 06:58:22 +00001580 // Okay, we have something that *can* be converted to the right type. Check
1581 // to see if there is a potentially weird extension going on here. This can
1582 // happen when you do an atomic operation on something like an char* and
1583 // pass in 42. The 42 gets converted to char. This is even more strange
1584 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001585 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001586 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001587 }
Mike Stump11289f42009-09-09 15:08:12 +00001588
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001589 ASTContext& Context = this->getASTContext();
1590
1591 // Create a new DeclRefExpr to refer to the new decl.
1592 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1593 Context,
1594 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001595 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001596 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001597 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001598 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001599 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001600 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001601
Chris Lattnerdc046542009-05-08 06:58:22 +00001602 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001603 // FIXME: This loses syntactic information.
1604 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1605 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1606 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001607 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001608
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001609 // Change the result type of the call to match the original value type. This
1610 // is arbitrary, but the codegen for these builtins ins design to handle it
1611 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001612 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001613
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001614 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001615}
1616
Chris Lattner6436fb62009-02-18 06:01:06 +00001617/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001618/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001619/// Note: It might also make sense to do the UTF-16 conversion here (would
1620/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001621bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001622 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001623 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1624
Douglas Gregorfb65e592011-07-27 05:40:30 +00001625 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001626 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1627 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001628 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001629 }
Mike Stump11289f42009-09-09 15:08:12 +00001630
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001631 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001632 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001633 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001634 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001635 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001636 UTF16 *ToPtr = &ToBuf[0];
1637
1638 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1639 &ToPtr, ToPtr + NumBytes,
1640 strictConversion);
1641 // Check for conversion failure.
1642 if (Result != conversionOK)
1643 Diag(Arg->getLocStart(),
1644 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1645 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001646 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001647}
1648
Chris Lattnere202e6a2007-12-20 00:05:45 +00001649/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1650/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001651bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1652 Expr *Fn = TheCall->getCallee();
1653 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001654 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001655 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001656 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1657 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001658 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001659 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001660 return true;
1661 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001662
1663 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001664 return Diag(TheCall->getLocEnd(),
1665 diag::err_typecheck_call_too_few_args_at_least)
1666 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001667 }
1668
John McCall29ad95b2011-08-27 01:09:30 +00001669 // Type-check the first argument normally.
1670 if (checkBuiltinArgument(*this, TheCall, 0))
1671 return true;
1672
Chris Lattnere202e6a2007-12-20 00:05:45 +00001673 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001674 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001675 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001676 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001677 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001678 else if (FunctionDecl *FD = getCurFunctionDecl())
1679 isVariadic = FD->isVariadic();
1680 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001681 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001682
Chris Lattnere202e6a2007-12-20 00:05:45 +00001683 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001684 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1685 return true;
1686 }
Mike Stump11289f42009-09-09 15:08:12 +00001687
Chris Lattner43be2e62007-12-19 23:59:04 +00001688 // Verify that the second argument to the builtin is the last argument of the
1689 // current function or method.
1690 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001691 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001692
Nico Weber9eea7642013-05-24 23:31:57 +00001693 // These are valid if SecondArgIsLastNamedArgument is false after the next
1694 // block.
1695 QualType Type;
1696 SourceLocation ParamLoc;
1697
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001698 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1699 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001700 // FIXME: This isn't correct for methods (results in bogus warning).
1701 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001702 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001703 if (CurBlock)
1704 LastArg = *(CurBlock->TheDecl->param_end()-1);
1705 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001706 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001707 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001708 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001709 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001710
1711 Type = PV->getType();
1712 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001713 }
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Chris Lattner43be2e62007-12-19 23:59:04 +00001716 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001717 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001718 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001719 else if (Type->isReferenceType()) {
1720 Diag(Arg->getLocStart(),
1721 diag::warn_va_start_of_reference_type_is_undefined);
1722 Diag(ParamLoc, diag::note_parameter_type) << Type;
1723 }
1724
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001725 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001726 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001727}
Chris Lattner43be2e62007-12-19 23:59:04 +00001728
Chris Lattner2da14fb2007-12-20 00:26:33 +00001729/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1730/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001731bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1732 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001733 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001734 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001735 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001736 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001737 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001738 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001739 << SourceRange(TheCall->getArg(2)->getLocStart(),
1740 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001741
John Wiegley01296292011-04-08 18:41:53 +00001742 ExprResult OrigArg0 = TheCall->getArg(0);
1743 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001744
Chris Lattner2da14fb2007-12-20 00:26:33 +00001745 // Do standard promotions between the two arguments, returning their common
1746 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001747 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001748 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1749 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001750
1751 // Make sure any conversions are pushed back into the call; this is
1752 // type safe since unordered compare builtins are declared as "_Bool
1753 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001754 TheCall->setArg(0, OrigArg0.get());
1755 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001756
John Wiegley01296292011-04-08 18:41:53 +00001757 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001758 return false;
1759
Chris Lattner2da14fb2007-12-20 00:26:33 +00001760 // If the common type isn't a real floating type, then the arguments were
1761 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001762 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001763 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001764 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001765 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1766 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001767
Chris Lattner2da14fb2007-12-20 00:26:33 +00001768 return false;
1769}
1770
Benjamin Kramer634fc102010-02-15 22:42:31 +00001771/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1772/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001773/// to check everything. We expect the last argument to be a floating point
1774/// value.
1775bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1776 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001777 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001778 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001779 if (TheCall->getNumArgs() > NumArgs)
1780 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001781 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001782 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001783 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001784 (*(TheCall->arg_end()-1))->getLocEnd());
1785
Benjamin Kramer64aae502010-02-16 10:07:31 +00001786 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001787
Eli Friedman7e4faac2009-08-31 20:06:00 +00001788 if (OrigArg->isTypeDependent())
1789 return false;
1790
Chris Lattner68784ef2010-05-06 05:50:07 +00001791 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001792 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001793 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001794 diag::err_typecheck_call_invalid_unary_fp)
1795 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001796
Chris Lattner68784ef2010-05-06 05:50:07 +00001797 // If this is an implicit conversion from float -> double, remove it.
1798 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1799 Expr *CastArg = Cast->getSubExpr();
1800 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1801 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1802 "promotion from float to double is the only expected cast here");
1803 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001804 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001805 }
1806 }
1807
Eli Friedman7e4faac2009-08-31 20:06:00 +00001808 return false;
1809}
1810
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001811/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1812// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001813ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001814 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001815 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001816 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001817 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1818 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001819
Nate Begemana0110022010-06-08 00:16:34 +00001820 // Determine which of the following types of shufflevector we're checking:
1821 // 1) unary, vector mask: (lhs, mask)
1822 // 2) binary, vector mask: (lhs, rhs, mask)
1823 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1824 QualType resType = TheCall->getArg(0)->getType();
1825 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001826
Douglas Gregorc25f7662009-05-19 22:10:17 +00001827 if (!TheCall->getArg(0)->isTypeDependent() &&
1828 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001829 QualType LHSType = TheCall->getArg(0)->getType();
1830 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001831
Craig Topperbaca3892013-07-29 06:47:04 +00001832 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1833 return ExprError(Diag(TheCall->getLocStart(),
1834 diag::err_shufflevector_non_vector)
1835 << SourceRange(TheCall->getArg(0)->getLocStart(),
1836 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001837
Nate Begemana0110022010-06-08 00:16:34 +00001838 numElements = LHSType->getAs<VectorType>()->getNumElements();
1839 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001840
Nate Begemana0110022010-06-08 00:16:34 +00001841 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1842 // with mask. If so, verify that RHS is an integer vector type with the
1843 // same number of elts as lhs.
1844 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001845 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001846 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001847 return ExprError(Diag(TheCall->getLocStart(),
1848 diag::err_shufflevector_incompatible_vector)
1849 << SourceRange(TheCall->getArg(1)->getLocStart(),
1850 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001851 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001852 return ExprError(Diag(TheCall->getLocStart(),
1853 diag::err_shufflevector_incompatible_vector)
1854 << SourceRange(TheCall->getArg(0)->getLocStart(),
1855 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001856 } else if (numElements != numResElements) {
1857 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001858 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001859 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001860 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001861 }
1862
1863 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001864 if (TheCall->getArg(i)->isTypeDependent() ||
1865 TheCall->getArg(i)->isValueDependent())
1866 continue;
1867
Nate Begemana0110022010-06-08 00:16:34 +00001868 llvm::APSInt Result(32);
1869 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1870 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001871 diag::err_shufflevector_nonconstant_argument)
1872 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001873
Craig Topper50ad5b72013-08-03 17:40:38 +00001874 // Allow -1 which will be translated to undef in the IR.
1875 if (Result.isSigned() && Result.isAllOnesValue())
1876 continue;
1877
Chris Lattner7ab824e2008-08-10 02:05:13 +00001878 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001879 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001880 diag::err_shufflevector_argument_too_large)
1881 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001882 }
1883
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001885
Chris Lattner7ab824e2008-08-10 02:05:13 +00001886 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001887 exprs.push_back(TheCall->getArg(i));
1888 TheCall->setArg(i, 0);
1889 }
1890
Benjamin Kramerc215e762012-08-24 11:54:20 +00001891 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001892 TheCall->getCallee()->getLocStart(),
1893 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001894}
Chris Lattner43be2e62007-12-19 23:59:04 +00001895
Hal Finkelc4d7c822013-09-18 03:29:45 +00001896/// SemaConvertVectorExpr - Handle __builtin_convertvector
1897ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1898 SourceLocation BuiltinLoc,
1899 SourceLocation RParenLoc) {
1900 ExprValueKind VK = VK_RValue;
1901 ExprObjectKind OK = OK_Ordinary;
1902 QualType DstTy = TInfo->getType();
1903 QualType SrcTy = E->getType();
1904
1905 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1906 return ExprError(Diag(BuiltinLoc,
1907 diag::err_convertvector_non_vector)
1908 << E->getSourceRange());
1909 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1910 return ExprError(Diag(BuiltinLoc,
1911 diag::err_convertvector_non_vector_type));
1912
1913 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1914 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1915 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1916 if (SrcElts != DstElts)
1917 return ExprError(Diag(BuiltinLoc,
1918 diag::err_convertvector_incompatible_vector)
1919 << E->getSourceRange());
1920 }
1921
1922 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1923 BuiltinLoc, RParenLoc));
1924
1925}
1926
Daniel Dunbarb7257262008-07-21 22:59:13 +00001927/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1928// This is declared to take (const void*, ...) and can take two
1929// optional constant int args.
1930bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001931 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001932
Chris Lattner3b054132008-11-19 05:08:23 +00001933 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001934 return Diag(TheCall->getLocEnd(),
1935 diag::err_typecheck_call_too_many_args_at_most)
1936 << 0 /*function call*/ << 3 << NumArgs
1937 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001938
1939 // Argument 0 is checked for us and the remaining arguments must be
1940 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001941 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001942 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001943
1944 // We can't check the value of a dependent argument.
1945 if (Arg->isTypeDependent() || Arg->isValueDependent())
1946 continue;
1947
Eli Friedman5efba262009-12-04 00:30:06 +00001948 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001949 if (SemaBuiltinConstantArg(TheCall, i, Result))
1950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001951
Daniel Dunbarb7257262008-07-21 22:59:13 +00001952 // FIXME: gcc issues a warning and rewrites these to 0. These
1953 // seems especially odd for the third argument since the default
1954 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001955 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001956 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001957 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001958 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001959 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001960 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001961 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001962 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001963 }
1964 }
1965
Chris Lattner3b054132008-11-19 05:08:23 +00001966 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001967}
1968
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001969/// SemaBuiltinMMPrefetch - Handle _mm_prefetch.
1970// This is declared to take (const char*, int)
1971bool Sema::SemaBuiltinMMPrefetch(CallExpr *TheCall) {
1972 Expr *Arg = TheCall->getArg(1);
1973
1974 // We can't check the value of a dependent argument.
1975 if (Arg->isTypeDependent() || Arg->isValueDependent())
1976 return false;
1977
1978 llvm::APSInt Result;
1979 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1980 return true;
1981
1982 if (Result.getLimitedValue() > 3)
1983 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1984 << "0" << "3" << Arg->getSourceRange();
1985
1986 return false;
1987}
1988
Eric Christopher8d0c6212010-04-17 02:26:23 +00001989/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1990/// TheCall is a constant expression.
1991bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1992 llvm::APSInt &Result) {
1993 Expr *Arg = TheCall->getArg(ArgNum);
1994 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1995 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1996
1997 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1998
1999 if (!Arg->isIntegerConstantExpr(Result, Context))
2000 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002001 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002002
Chris Lattnerd545ad12009-09-23 06:06:36 +00002003 return false;
2004}
2005
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002006/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
2007/// int type). This simply type checks that type is one of the defined
2008/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00002009// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002010bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002011 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002012
2013 // We can't check the value of a dependent argument.
2014 if (TheCall->getArg(1)->isTypeDependent() ||
2015 TheCall->getArg(1)->isValueDependent())
2016 return false;
2017
Eric Christopher8d0c6212010-04-17 02:26:23 +00002018 // Check constant-ness first.
2019 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2020 return true;
2021
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002022 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002023 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00002024 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2025 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002026 }
2027
2028 return false;
2029}
2030
Eli Friedmanc97d0142009-05-03 06:04:26 +00002031/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002032/// This checks that val is a constant 1.
2033bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2034 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002035 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002036
Eric Christopher8d0c6212010-04-17 02:26:23 +00002037 // TODO: This is less than ideal. Overload this to take a value.
2038 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2039 return true;
2040
2041 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002042 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2043 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2044
2045 return false;
2046}
2047
Richard Smithd7293d72013-08-05 18:49:43 +00002048namespace {
2049enum StringLiteralCheckType {
2050 SLCT_NotALiteral,
2051 SLCT_UncheckedLiteral,
2052 SLCT_CheckedLiteral
2053};
2054}
2055
Richard Smith55ce3522012-06-25 20:30:08 +00002056// Determine if an expression is a string literal or constant string.
2057// If this function returns false on the arguments to a function expecting a
2058// format string, we will usually need to emit a warning.
2059// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002060static StringLiteralCheckType
2061checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2062 bool HasVAListArg, unsigned format_idx,
2063 unsigned firstDataArg, Sema::FormatStringType Type,
2064 Sema::VariadicCallType CallType, bool InFunctionCall,
2065 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002066 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002067 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002068 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002069
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002070 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002071
Richard Smithd7293d72013-08-05 18:49:43 +00002072 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002073 // Technically -Wformat-nonliteral does not warn about this case.
2074 // The behavior of printf and friends in this case is implementation
2075 // dependent. Ideally if the format string cannot be null then
2076 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002077 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002078
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002079 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002080 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002081 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002082 // The expression is a literal if both sub-expressions were, and it was
2083 // completely checked only if both sub-expressions were checked.
2084 const AbstractConditionalOperator *C =
2085 cast<AbstractConditionalOperator>(E);
2086 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002087 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002088 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002089 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002090 if (Left == SLCT_NotALiteral)
2091 return SLCT_NotALiteral;
2092 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002093 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002094 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002095 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002096 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002097 }
2098
2099 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002100 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2101 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002102 }
2103
John McCallc07a0c72011-02-17 10:25:35 +00002104 case Stmt::OpaqueValueExprClass:
2105 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2106 E = src;
2107 goto tryAgain;
2108 }
Richard Smith55ce3522012-06-25 20:30:08 +00002109 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002110
Ted Kremeneka8890832011-02-24 23:03:04 +00002111 case Stmt::PredefinedExprClass:
2112 // While __func__, etc., are technically not string literals, they
2113 // cannot contain format specifiers and thus are not a security
2114 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002115 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002116
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002117 case Stmt::DeclRefExprClass: {
2118 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002119
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002120 // As an exception, do not flag errors for variables binding to
2121 // const string literals.
2122 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2123 bool isConstant = false;
2124 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002125
Richard Smithd7293d72013-08-05 18:49:43 +00002126 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2127 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002128 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002129 isConstant = T.isConstant(S.Context) &&
2130 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002131 } else if (T->isObjCObjectPointerType()) {
2132 // In ObjC, there is usually no "const ObjectPointer" type,
2133 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002134 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002135 }
Mike Stump11289f42009-09-09 15:08:12 +00002136
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002137 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002138 if (const Expr *Init = VD->getAnyInitializer()) {
2139 // Look through initializers like const char c[] = { "foo" }
2140 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2141 if (InitList->isStringLiteralInit())
2142 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2143 }
Richard Smithd7293d72013-08-05 18:49:43 +00002144 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002145 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002146 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002147 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002148 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002149 }
Mike Stump11289f42009-09-09 15:08:12 +00002150
Anders Carlssonb012ca92009-06-28 19:55:58 +00002151 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2152 // special check to see if the format string is a function parameter
2153 // of the function calling the printf function. If the function
2154 // has an attribute indicating it is a printf-like function, then we
2155 // should suppress warnings concerning non-literals being used in a call
2156 // to a vprintf function. For example:
2157 //
2158 // void
2159 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2160 // va_list ap;
2161 // va_start(ap, fmt);
2162 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2163 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002164 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002165 if (HasVAListArg) {
2166 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2167 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2168 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002169 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002170 // adjust for implicit parameter
2171 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2172 if (MD->isInstance())
2173 ++PVIndex;
2174 // We also check if the formats are compatible.
2175 // We can't pass a 'scanf' string to a 'printf' function.
2176 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002177 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002178 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002179 }
2180 }
2181 }
2182 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002183 }
Mike Stump11289f42009-09-09 15:08:12 +00002184
Richard Smith55ce3522012-06-25 20:30:08 +00002185 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002186 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002187
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002188 case Stmt::CallExprClass:
2189 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002190 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002191 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2192 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2193 unsigned ArgIndex = FA->getFormatIdx();
2194 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2195 if (MD->isInstance())
2196 --ArgIndex;
2197 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002198
Richard Smithd7293d72013-08-05 18:49:43 +00002199 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002200 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002201 Type, CallType, InFunctionCall,
2202 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002203 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2204 unsigned BuiltinID = FD->getBuiltinID();
2205 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2206 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2207 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002208 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002209 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002210 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002211 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002212 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002213 }
2214 }
Mike Stump11289f42009-09-09 15:08:12 +00002215
Richard Smith55ce3522012-06-25 20:30:08 +00002216 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002217 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002218 case Stmt::ObjCStringLiteralClass:
2219 case Stmt::StringLiteralClass: {
2220 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002221
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002222 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002223 StrE = ObjCFExpr->getString();
2224 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002225 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002226
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002227 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002228 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2229 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002230 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002231 }
Mike Stump11289f42009-09-09 15:08:12 +00002232
Richard Smith55ce3522012-06-25 20:30:08 +00002233 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002236 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002237 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002238 }
2239}
2240
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002241Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002242 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002243 .Case("scanf", FST_Scanf)
2244 .Cases("printf", "printf0", FST_Printf)
2245 .Cases("NSString", "CFString", FST_NSString)
2246 .Case("strftime", FST_Strftime)
2247 .Case("strfmon", FST_Strfmon)
2248 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2249 .Default(FST_Unknown);
2250}
2251
Jordan Rose3e0ec582012-07-19 18:10:23 +00002252/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002253/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002254/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002255bool Sema::CheckFormatArguments(const FormatAttr *Format,
2256 ArrayRef<const Expr *> Args,
2257 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002258 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002259 SourceLocation Loc, SourceRange Range,
2260 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002261 FormatStringInfo FSI;
2262 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002263 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002264 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002265 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002266 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002267}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002268
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002269bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002270 bool HasVAListArg, unsigned format_idx,
2271 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002272 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002273 SourceLocation Loc, SourceRange Range,
2274 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002275 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002276 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002277 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002278 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002279 }
Mike Stump11289f42009-09-09 15:08:12 +00002280
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002281 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002282
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002283 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002284 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002285 // Dynamically generated format strings are difficult to
2286 // automatically vet at compile time. Requiring that format strings
2287 // are string literals: (1) permits the checking of format strings by
2288 // the compiler and thereby (2) can practically remove the source of
2289 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002290
Mike Stump11289f42009-09-09 15:08:12 +00002291 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002292 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002293 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002294 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002295 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002296 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2297 format_idx, firstDataArg, Type, CallType,
2298 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002299 if (CT != SLCT_NotALiteral)
2300 // Literal format string found, check done!
2301 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002302
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002303 // Strftime is particular as it always uses a single 'time' argument,
2304 // so it is safe to pass a non-literal string.
2305 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002306 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002307
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002308 // Do not emit diag when the string param is a macro expansion and the
2309 // format is either NSString or CFString. This is a hack to prevent
2310 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2311 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002312 if (Type == FST_NSString &&
2313 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002314 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002315
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002316 // If there are no arguments specified, warn with -Wformat-security, otherwise
2317 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002318 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002319 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002320 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002321 << OrigFormatExpr->getSourceRange();
2322 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002323 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002324 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002325 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002326 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002327}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002328
Ted Kremenekab278de2010-01-28 23:39:18 +00002329namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002330class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2331protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002332 Sema &S;
2333 const StringLiteral *FExpr;
2334 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002335 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002336 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002337 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002338 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002339 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002340 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002341 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002342 bool usesPositionalArgs;
2343 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002344 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002345 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002346 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002347public:
Ted Kremenek02087932010-07-16 02:11:22 +00002348 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002349 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002350 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002351 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002352 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002353 Sema::VariadicCallType callType,
2354 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002355 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002356 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2357 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002358 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002359 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002360 inFunctionCall(inFunctionCall), CallType(callType),
2361 CheckedVarArgs(CheckedVarArgs) {
2362 CoveredArgs.resize(numDataArgs);
2363 CoveredArgs.reset();
2364 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002365
Ted Kremenek019d2242010-01-29 01:50:07 +00002366 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002367
Ted Kremenek02087932010-07-16 02:11:22 +00002368 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002369 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002370
Jordan Rose92303592012-09-08 04:00:03 +00002371 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002372 const analyze_format_string::FormatSpecifier &FS,
2373 const analyze_format_string::ConversionSpecifier &CS,
2374 const char *startSpecifier, unsigned specifierLen,
2375 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002376
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002377 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002378 const analyze_format_string::FormatSpecifier &FS,
2379 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002380
2381 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002382 const analyze_format_string::ConversionSpecifier &CS,
2383 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002384
Craig Toppere14c0f82014-03-12 04:55:44 +00002385 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002386
Craig Toppere14c0f82014-03-12 04:55:44 +00002387 void HandleInvalidPosition(const char *startSpecifier,
2388 unsigned specifierLen,
2389 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002390
Craig Toppere14c0f82014-03-12 04:55:44 +00002391 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002392
Craig Toppere14c0f82014-03-12 04:55:44 +00002393 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002394
Richard Trieu03cf7b72011-10-28 00:41:25 +00002395 template <typename Range>
2396 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2397 const Expr *ArgumentExpr,
2398 PartialDiagnostic PDiag,
2399 SourceLocation StringLoc,
2400 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002401 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002402
Ted Kremenek02087932010-07-16 02:11:22 +00002403protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002404 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2405 const char *startSpec,
2406 unsigned specifierLen,
2407 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002408
2409 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2410 const char *startSpec,
2411 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002412
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002413 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002414 CharSourceRange getSpecifierRange(const char *startSpecifier,
2415 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002416 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002417
Ted Kremenek5739de72010-01-29 01:06:55 +00002418 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002419
2420 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2421 const analyze_format_string::ConversionSpecifier &CS,
2422 const char *startSpecifier, unsigned specifierLen,
2423 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002424
2425 template <typename Range>
2426 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2427 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002428 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002429
2430 void CheckPositionalAndNonpositionalArgs(
2431 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002432};
2433}
2434
Ted Kremenek02087932010-07-16 02:11:22 +00002435SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002436 return OrigFormatExpr->getSourceRange();
2437}
2438
Ted Kremenek02087932010-07-16 02:11:22 +00002439CharSourceRange CheckFormatHandler::
2440getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002441 SourceLocation Start = getLocationOfByte(startSpecifier);
2442 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2443
2444 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002445 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002446
2447 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002448}
2449
Ted Kremenek02087932010-07-16 02:11:22 +00002450SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002451 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002452}
2453
Ted Kremenek02087932010-07-16 02:11:22 +00002454void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2455 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2457 getLocationOfByte(startSpecifier),
2458 /*IsStringLocation*/true,
2459 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002460}
2461
Jordan Rose92303592012-09-08 04:00:03 +00002462void CheckFormatHandler::HandleInvalidLengthModifier(
2463 const analyze_format_string::FormatSpecifier &FS,
2464 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002465 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002466 using namespace analyze_format_string;
2467
2468 const LengthModifier &LM = FS.getLengthModifier();
2469 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2470
2471 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002472 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002473 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002474 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002475 getLocationOfByte(LM.getStart()),
2476 /*IsStringLocation*/true,
2477 getSpecifierRange(startSpecifier, specifierLen));
2478
2479 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2480 << FixedLM->toString()
2481 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2482
2483 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002484 FixItHint Hint;
2485 if (DiagID == diag::warn_format_nonsensical_length)
2486 Hint = FixItHint::CreateRemoval(LMRange);
2487
2488 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002489 getLocationOfByte(LM.getStart()),
2490 /*IsStringLocation*/true,
2491 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002492 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002493 }
2494}
2495
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002496void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002497 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002498 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002499 using namespace analyze_format_string;
2500
2501 const LengthModifier &LM = FS.getLengthModifier();
2502 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2503
2504 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002505 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002506 if (FixedLM) {
2507 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2508 << LM.toString() << 0,
2509 getLocationOfByte(LM.getStart()),
2510 /*IsStringLocation*/true,
2511 getSpecifierRange(startSpecifier, specifierLen));
2512
2513 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2514 << FixedLM->toString()
2515 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2516
2517 } else {
2518 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2519 << LM.toString() << 0,
2520 getLocationOfByte(LM.getStart()),
2521 /*IsStringLocation*/true,
2522 getSpecifierRange(startSpecifier, specifierLen));
2523 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002524}
2525
2526void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2527 const analyze_format_string::ConversionSpecifier &CS,
2528 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002529 using namespace analyze_format_string;
2530
2531 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002532 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002533 if (FixedCS) {
2534 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2535 << CS.toString() << /*conversion specifier*/1,
2536 getLocationOfByte(CS.getStart()),
2537 /*IsStringLocation*/true,
2538 getSpecifierRange(startSpecifier, specifierLen));
2539
2540 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2541 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2542 << FixedCS->toString()
2543 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2544 } else {
2545 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2546 << CS.toString() << /*conversion specifier*/1,
2547 getLocationOfByte(CS.getStart()),
2548 /*IsStringLocation*/true,
2549 getSpecifierRange(startSpecifier, specifierLen));
2550 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002551}
2552
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002553void CheckFormatHandler::HandlePosition(const char *startPos,
2554 unsigned posLen) {
2555 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2556 getLocationOfByte(startPos),
2557 /*IsStringLocation*/true,
2558 getSpecifierRange(startPos, posLen));
2559}
2560
Ted Kremenekd1668192010-02-27 01:41:03 +00002561void
Ted Kremenek02087932010-07-16 02:11:22 +00002562CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2563 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002564 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2565 << (unsigned) p,
2566 getLocationOfByte(startPos), /*IsStringLocation*/true,
2567 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002568}
2569
Ted Kremenek02087932010-07-16 02:11:22 +00002570void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002571 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002572 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2573 getLocationOfByte(startPos),
2574 /*IsStringLocation*/true,
2575 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002576}
2577
Ted Kremenek02087932010-07-16 02:11:22 +00002578void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002579 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002580 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002581 EmitFormatDiagnostic(
2582 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2583 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2584 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002585 }
Ted Kremenek02087932010-07-16 02:11:22 +00002586}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002587
Jordan Rose58bbe422012-07-19 18:10:08 +00002588// Note that this may return NULL if there was an error parsing or building
2589// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002590const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002591 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002592}
2593
2594void CheckFormatHandler::DoneProcessing() {
2595 // Does the number of data arguments exceed the number of
2596 // format conversions in the format string?
2597 if (!HasVAListArg) {
2598 // Find any arguments that weren't covered.
2599 CoveredArgs.flip();
2600 signed notCoveredArg = CoveredArgs.find_first();
2601 if (notCoveredArg >= 0) {
2602 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002603 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2604 SourceLocation Loc = E->getLocStart();
2605 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2606 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2607 Loc, /*IsStringLocation*/false,
2608 getFormatStringRange());
2609 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002610 }
Ted Kremenek02087932010-07-16 02:11:22 +00002611 }
2612 }
2613}
2614
Ted Kremenekce815422010-07-19 21:25:57 +00002615bool
2616CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2617 SourceLocation Loc,
2618 const char *startSpec,
2619 unsigned specifierLen,
2620 const char *csStart,
2621 unsigned csLen) {
2622
2623 bool keepGoing = true;
2624 if (argIndex < NumDataArgs) {
2625 // Consider the argument coverered, even though the specifier doesn't
2626 // make sense.
2627 CoveredArgs.set(argIndex);
2628 }
2629 else {
2630 // If argIndex exceeds the number of data arguments we
2631 // don't issue a warning because that is just a cascade of warnings (and
2632 // they may have intended '%%' anyway). We don't want to continue processing
2633 // the format string after this point, however, as we will like just get
2634 // gibberish when trying to match arguments.
2635 keepGoing = false;
2636 }
2637
Richard Trieu03cf7b72011-10-28 00:41:25 +00002638 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2639 << StringRef(csStart, csLen),
2640 Loc, /*IsStringLocation*/true,
2641 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002642
2643 return keepGoing;
2644}
2645
Richard Trieu03cf7b72011-10-28 00:41:25 +00002646void
2647CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2648 const char *startSpec,
2649 unsigned specifierLen) {
2650 EmitFormatDiagnostic(
2651 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2652 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2653}
2654
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002655bool
2656CheckFormatHandler::CheckNumArgs(
2657 const analyze_format_string::FormatSpecifier &FS,
2658 const analyze_format_string::ConversionSpecifier &CS,
2659 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2660
2661 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002662 PartialDiagnostic PDiag = FS.usesPositionalArg()
2663 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2664 << (argIndex+1) << NumDataArgs)
2665 : S.PDiag(diag::warn_printf_insufficient_data_args);
2666 EmitFormatDiagnostic(
2667 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2668 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002669 return false;
2670 }
2671 return true;
2672}
2673
Richard Trieu03cf7b72011-10-28 00:41:25 +00002674template<typename Range>
2675void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2676 SourceLocation Loc,
2677 bool IsStringLocation,
2678 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002679 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002680 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002681 Loc, IsStringLocation, StringRange, FixIt);
2682}
2683
2684/// \brief If the format string is not within the funcion call, emit a note
2685/// so that the function call and string are in diagnostic messages.
2686///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002687/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002688/// call and only one diagnostic message will be produced. Otherwise, an
2689/// extra note will be emitted pointing to location of the format string.
2690///
2691/// \param ArgumentExpr the expression that is passed as the format string
2692/// argument in the function call. Used for getting locations when two
2693/// diagnostics are emitted.
2694///
2695/// \param PDiag the callee should already have provided any strings for the
2696/// diagnostic message. This function only adds locations and fixits
2697/// to diagnostics.
2698///
2699/// \param Loc primary location for diagnostic. If two diagnostics are
2700/// required, one will be at Loc and a new SourceLocation will be created for
2701/// the other one.
2702///
2703/// \param IsStringLocation if true, Loc points to the format string should be
2704/// used for the note. Otherwise, Loc points to the argument list and will
2705/// be used with PDiag.
2706///
2707/// \param StringRange some or all of the string to highlight. This is
2708/// templated so it can accept either a CharSourceRange or a SourceRange.
2709///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002710/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002711template<typename Range>
2712void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2713 const Expr *ArgumentExpr,
2714 PartialDiagnostic PDiag,
2715 SourceLocation Loc,
2716 bool IsStringLocation,
2717 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002718 ArrayRef<FixItHint> FixIt) {
2719 if (InFunctionCall) {
2720 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2721 D << StringRange;
2722 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2723 I != E; ++I) {
2724 D << *I;
2725 }
2726 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002727 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2728 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002729
2730 const Sema::SemaDiagnosticBuilder &Note =
2731 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2732 diag::note_format_string_defined);
2733
2734 Note << StringRange;
2735 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2736 I != E; ++I) {
2737 Note << *I;
2738 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002739 }
2740}
2741
Ted Kremenek02087932010-07-16 02:11:22 +00002742//===--- CHECK: Printf format string checking ------------------------------===//
2743
2744namespace {
2745class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002746 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002747public:
2748 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2749 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002750 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002751 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002752 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002753 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002754 Sema::VariadicCallType CallType,
2755 llvm::SmallBitVector &CheckedVarArgs)
2756 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2757 numDataArgs, beg, hasVAListArg, Args,
2758 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2759 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002760 {}
2761
Craig Toppere14c0f82014-03-12 04:55:44 +00002762
Ted Kremenek02087932010-07-16 02:11:22 +00002763 bool HandleInvalidPrintfConversionSpecifier(
2764 const analyze_printf::PrintfSpecifier &FS,
2765 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002766 unsigned specifierLen) override;
2767
Ted Kremenek02087932010-07-16 02:11:22 +00002768 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2769 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002770 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00002771 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2772 const char *StartSpecifier,
2773 unsigned SpecifierLen,
2774 const Expr *E);
2775
Ted Kremenek02087932010-07-16 02:11:22 +00002776 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2777 const char *startSpecifier, unsigned specifierLen);
2778 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2779 const analyze_printf::OptionalAmount &Amt,
2780 unsigned type,
2781 const char *startSpecifier, unsigned specifierLen);
2782 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2783 const analyze_printf::OptionalFlag &flag,
2784 const char *startSpecifier, unsigned specifierLen);
2785 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2786 const analyze_printf::OptionalFlag &ignoredFlag,
2787 const analyze_printf::OptionalFlag &flag,
2788 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002789 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00002790 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00002791
Ted Kremenek02087932010-07-16 02:11:22 +00002792};
2793}
2794
2795bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2796 const analyze_printf::PrintfSpecifier &FS,
2797 const char *startSpecifier,
2798 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002799 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002800 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002801
Ted Kremenekce815422010-07-19 21:25:57 +00002802 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2803 getLocationOfByte(CS.getStart()),
2804 startSpecifier, specifierLen,
2805 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002806}
2807
Ted Kremenek02087932010-07-16 02:11:22 +00002808bool CheckPrintfHandler::HandleAmount(
2809 const analyze_format_string::OptionalAmount &Amt,
2810 unsigned k, const char *startSpecifier,
2811 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002812
2813 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002814 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002815 unsigned argIndex = Amt.getArgIndex();
2816 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002817 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2818 << k,
2819 getLocationOfByte(Amt.getStart()),
2820 /*IsStringLocation*/true,
2821 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002822 // Don't do any more checking. We will just emit
2823 // spurious errors.
2824 return false;
2825 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002826
Ted Kremenek5739de72010-01-29 01:06:55 +00002827 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002828 // Although not in conformance with C99, we also allow the argument to be
2829 // an 'unsigned int' as that is a reasonably safe case. GCC also
2830 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002831 CoveredArgs.set(argIndex);
2832 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002833 if (!Arg)
2834 return false;
2835
Ted Kremenek5739de72010-01-29 01:06:55 +00002836 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002837
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002838 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2839 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002840
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002841 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002843 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002844 << T << Arg->getSourceRange(),
2845 getLocationOfByte(Amt.getStart()),
2846 /*IsStringLocation*/true,
2847 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002848 // Don't do any more checking. We will just emit
2849 // spurious errors.
2850 return false;
2851 }
2852 }
2853 }
2854 return true;
2855}
Ted Kremenek5739de72010-01-29 01:06:55 +00002856
Tom Careb49ec692010-06-17 19:00:27 +00002857void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002858 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002859 const analyze_printf::OptionalAmount &Amt,
2860 unsigned type,
2861 const char *startSpecifier,
2862 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002863 const analyze_printf::PrintfConversionSpecifier &CS =
2864 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002865
Richard Trieu03cf7b72011-10-28 00:41:25 +00002866 FixItHint fixit =
2867 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2868 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2869 Amt.getConstantLength()))
2870 : FixItHint();
2871
2872 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2873 << type << CS.toString(),
2874 getLocationOfByte(Amt.getStart()),
2875 /*IsStringLocation*/true,
2876 getSpecifierRange(startSpecifier, specifierLen),
2877 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002878}
2879
Ted Kremenek02087932010-07-16 02:11:22 +00002880void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002881 const analyze_printf::OptionalFlag &flag,
2882 const char *startSpecifier,
2883 unsigned specifierLen) {
2884 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002885 const analyze_printf::PrintfConversionSpecifier &CS =
2886 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2888 << flag.toString() << CS.toString(),
2889 getLocationOfByte(flag.getPosition()),
2890 /*IsStringLocation*/true,
2891 getSpecifierRange(startSpecifier, specifierLen),
2892 FixItHint::CreateRemoval(
2893 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002894}
2895
2896void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002897 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002898 const analyze_printf::OptionalFlag &ignoredFlag,
2899 const analyze_printf::OptionalFlag &flag,
2900 const char *startSpecifier,
2901 unsigned specifierLen) {
2902 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002903 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2904 << ignoredFlag.toString() << flag.toString(),
2905 getLocationOfByte(ignoredFlag.getPosition()),
2906 /*IsStringLocation*/true,
2907 getSpecifierRange(startSpecifier, specifierLen),
2908 FixItHint::CreateRemoval(
2909 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002910}
2911
Richard Smith55ce3522012-06-25 20:30:08 +00002912// Determines if the specified is a C++ class or struct containing
2913// a member with the specified name and kind (e.g. a CXXMethodDecl named
2914// "c_str()").
2915template<typename MemberKind>
2916static llvm::SmallPtrSet<MemberKind*, 1>
2917CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2918 const RecordType *RT = Ty->getAs<RecordType>();
2919 llvm::SmallPtrSet<MemberKind*, 1> Results;
2920
2921 if (!RT)
2922 return Results;
2923 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00002924 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00002925 return Results;
2926
2927 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2928 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00002929 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00002930
2931 // We just need to include all members of the right kind turned up by the
2932 // filter, at this point.
2933 if (S.LookupQualifiedName(R, RT->getDecl()))
2934 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2935 NamedDecl *decl = (*I)->getUnderlyingDecl();
2936 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2937 Results.insert(FK);
2938 }
2939 return Results;
2940}
2941
Richard Smith2868a732014-02-28 01:36:39 +00002942/// Check if we could call '.c_str()' on an object.
2943///
2944/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
2945/// allow the call, or if it would be ambiguous).
2946bool Sema::hasCStrMethod(const Expr *E) {
2947 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2948 MethodSet Results =
2949 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
2950 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2951 MI != ME; ++MI)
2952 if ((*MI)->getMinRequiredArguments() == 0)
2953 return true;
2954 return false;
2955}
2956
Richard Smith55ce3522012-06-25 20:30:08 +00002957// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002958// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002959// Returns true when a c_str() conversion method is found.
2960bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00002961 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00002962 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2963
2964 MethodSet Results =
2965 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2966
2967 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2968 MI != ME; ++MI) {
2969 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00002970 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00002971 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002972 // FIXME: Suggest parens if the expression needs them.
2973 SourceLocation EndLoc =
2974 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2975 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2976 << "c_str()"
2977 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2978 return true;
2979 }
2980 }
2981
2982 return false;
2983}
2984
Ted Kremenekab278de2010-01-28 23:39:18 +00002985bool
Ted Kremenek02087932010-07-16 02:11:22 +00002986CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002987 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002988 const char *startSpecifier,
2989 unsigned specifierLen) {
2990
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002991 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002992 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002993 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002994
Ted Kremenek6cd69422010-07-19 22:01:06 +00002995 if (FS.consumesDataArgument()) {
2996 if (atFirstArg) {
2997 atFirstArg = false;
2998 usesPositionalArgs = FS.usesPositionalArg();
2999 }
3000 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003001 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3002 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003003 return false;
3004 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003005 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003006
Ted Kremenekd1668192010-02-27 01:41:03 +00003007 // First check if the field width, precision, and conversion specifier
3008 // have matching data arguments.
3009 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3010 startSpecifier, specifierLen)) {
3011 return false;
3012 }
3013
3014 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3015 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003016 return false;
3017 }
3018
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003019 if (!CS.consumesDataArgument()) {
3020 // FIXME: Technically specifying a precision or field width here
3021 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003022 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003023 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003024
Ted Kremenek4a49d982010-02-26 19:18:41 +00003025 // Consume the argument.
3026 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003027 if (argIndex < NumDataArgs) {
3028 // The check to see if the argIndex is valid will come later.
3029 // We set the bit here because we may exit early from this
3030 // function if we encounter some other error.
3031 CoveredArgs.set(argIndex);
3032 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003033
3034 // Check for using an Objective-C specific conversion specifier
3035 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003036 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003037 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3038 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003039 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003040
Tom Careb49ec692010-06-17 19:00:27 +00003041 // Check for invalid use of field width
3042 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003043 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003044 startSpecifier, specifierLen);
3045 }
3046
3047 // Check for invalid use of precision
3048 if (!FS.hasValidPrecision()) {
3049 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3050 startSpecifier, specifierLen);
3051 }
3052
3053 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003054 if (!FS.hasValidThousandsGroupingPrefix())
3055 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003056 if (!FS.hasValidLeadingZeros())
3057 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3058 if (!FS.hasValidPlusPrefix())
3059 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003060 if (!FS.hasValidSpacePrefix())
3061 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003062 if (!FS.hasValidAlternativeForm())
3063 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3064 if (!FS.hasValidLeftJustified())
3065 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3066
3067 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003068 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3069 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3070 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003071 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3072 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3073 startSpecifier, specifierLen);
3074
3075 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003076 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003077 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3078 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003079 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003080 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003081 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003082 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3083 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003084
Jordan Rose92303592012-09-08 04:00:03 +00003085 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3086 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3087
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003088 // The remaining checks depend on the data arguments.
3089 if (HasVAListArg)
3090 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003091
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003092 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003093 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003094
Jordan Rose58bbe422012-07-19 18:10:08 +00003095 const Expr *Arg = getDataArg(argIndex);
3096 if (!Arg)
3097 return true;
3098
3099 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003100}
3101
Jordan Roseaee34382012-09-05 22:56:26 +00003102static bool requiresParensToAddCast(const Expr *E) {
3103 // FIXME: We should have a general way to reason about operator
3104 // precedence and whether parens are actually needed here.
3105 // Take care of a few common cases where they aren't.
3106 const Expr *Inside = E->IgnoreImpCasts();
3107 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3108 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3109
3110 switch (Inside->getStmtClass()) {
3111 case Stmt::ArraySubscriptExprClass:
3112 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003113 case Stmt::CharacterLiteralClass:
3114 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003115 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003116 case Stmt::FloatingLiteralClass:
3117 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003118 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003119 case Stmt::ObjCArrayLiteralClass:
3120 case Stmt::ObjCBoolLiteralExprClass:
3121 case Stmt::ObjCBoxedExprClass:
3122 case Stmt::ObjCDictionaryLiteralClass:
3123 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003124 case Stmt::ObjCIvarRefExprClass:
3125 case Stmt::ObjCMessageExprClass:
3126 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003127 case Stmt::ObjCStringLiteralClass:
3128 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003129 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003130 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003131 case Stmt::UnaryOperatorClass:
3132 return false;
3133 default:
3134 return true;
3135 }
3136}
3137
Richard Smith55ce3522012-06-25 20:30:08 +00003138bool
3139CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3140 const char *StartSpecifier,
3141 unsigned SpecifierLen,
3142 const Expr *E) {
3143 using namespace analyze_format_string;
3144 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003145 // Now type check the data expression that matches the
3146 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003147 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3148 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003149 if (!AT.isValid())
3150 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003151
Jordan Rose598ec092012-12-05 18:44:40 +00003152 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003153 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3154 ExprTy = TET->getUnderlyingExpr()->getType();
3155 }
3156
Jordan Rose598ec092012-12-05 18:44:40 +00003157 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003158 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003159
Jordan Rose22b74712012-09-05 22:56:19 +00003160 // Look through argument promotions for our error message's reported type.
3161 // This includes the integral and floating promotions, but excludes array
3162 // and function pointer decay; seeing that an argument intended to be a
3163 // string has type 'char [6]' is probably more confusing than 'char *'.
3164 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3165 if (ICE->getCastKind() == CK_IntegralCast ||
3166 ICE->getCastKind() == CK_FloatingCast) {
3167 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003168 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003169
3170 // Check if we didn't match because of an implicit cast from a 'char'
3171 // or 'short' to an 'int'. This is done because printf is a varargs
3172 // function.
3173 if (ICE->getType() == S.Context.IntTy ||
3174 ICE->getType() == S.Context.UnsignedIntTy) {
3175 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003176 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003177 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003178 }
Jordan Rose98709982012-06-04 22:48:57 +00003179 }
Jordan Rose598ec092012-12-05 18:44:40 +00003180 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3181 // Special case for 'a', which has type 'int' in C.
3182 // Note, however, that we do /not/ want to treat multibyte constants like
3183 // 'MooV' as characters! This form is deprecated but still exists.
3184 if (ExprTy == S.Context.IntTy)
3185 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3186 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003187 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003188
Jordan Rose0e5badd2012-12-05 18:44:49 +00003189 // %C in an Objective-C context prints a unichar, not a wchar_t.
3190 // If the argument is an integer of some kind, believe the %C and suggest
3191 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003192 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003193 if (ObjCContext &&
3194 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3195 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3196 !ExprTy->isCharType()) {
3197 // 'unichar' is defined as a typedef of unsigned short, but we should
3198 // prefer using the typedef if it is visible.
3199 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003200
3201 // While we are here, check if the value is an IntegerLiteral that happens
3202 // to be within the valid range.
3203 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3204 const llvm::APInt &V = IL->getValue();
3205 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3206 return true;
3207 }
3208
Jordan Rose0e5badd2012-12-05 18:44:49 +00003209 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3210 Sema::LookupOrdinaryName);
3211 if (S.LookupName(Result, S.getCurScope())) {
3212 NamedDecl *ND = Result.getFoundDecl();
3213 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3214 if (TD->getUnderlyingType() == IntendedTy)
3215 IntendedTy = S.Context.getTypedefType(TD);
3216 }
3217 }
3218 }
3219
3220 // Special-case some of Darwin's platform-independence types by suggesting
3221 // casts to primitive types that are known to be large enough.
3222 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003223 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003224 // Use a 'while' to peel off layers of typedefs.
3225 QualType TyTy = IntendedTy;
3226 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003227 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003228 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003229 .Case("NSInteger", S.Context.LongTy)
3230 .Case("NSUInteger", S.Context.UnsignedLongTy)
3231 .Case("SInt32", S.Context.IntTy)
3232 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003233 .Default(QualType());
3234
3235 if (!CastTy.isNull()) {
3236 ShouldNotPrintDirectly = true;
3237 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003238 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003239 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003240 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003241 }
3242 }
3243
Jordan Rose22b74712012-09-05 22:56:19 +00003244 // We may be able to offer a FixItHint if it is a supported type.
3245 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003246 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003247 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003248
Jordan Rose22b74712012-09-05 22:56:19 +00003249 if (success) {
3250 // Get the fix string from the fixed format specifier
3251 SmallString<16> buf;
3252 llvm::raw_svector_ostream os(buf);
3253 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003254
Jordan Roseaee34382012-09-05 22:56:26 +00003255 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3256
Jordan Rose0e5badd2012-12-05 18:44:49 +00003257 if (IntendedTy == ExprTy) {
3258 // In this case, the specifier is wrong and should be changed to match
3259 // the argument.
3260 EmitFormatDiagnostic(
3261 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3262 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3263 << E->getSourceRange(),
3264 E->getLocStart(),
3265 /*IsStringLocation*/false,
3266 SpecRange,
3267 FixItHint::CreateReplacement(SpecRange, os.str()));
3268
3269 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003270 // The canonical type for formatting this value is different from the
3271 // actual type of the expression. (This occurs, for example, with Darwin's
3272 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3273 // should be printed as 'long' for 64-bit compatibility.)
3274 // Rather than emitting a normal format/argument mismatch, we want to
3275 // add a cast to the recommended type (and correct the format string
3276 // if necessary).
3277 SmallString<16> CastBuf;
3278 llvm::raw_svector_ostream CastFix(CastBuf);
3279 CastFix << "(";
3280 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3281 CastFix << ")";
3282
3283 SmallVector<FixItHint,4> Hints;
3284 if (!AT.matchesType(S.Context, IntendedTy))
3285 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3286
3287 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3288 // If there's already a cast present, just replace it.
3289 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3290 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3291
3292 } else if (!requiresParensToAddCast(E)) {
3293 // If the expression has high enough precedence,
3294 // just write the C-style cast.
3295 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3296 CastFix.str()));
3297 } else {
3298 // Otherwise, add parens around the expression as well as the cast.
3299 CastFix << "(";
3300 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3301 CastFix.str()));
3302
3303 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3304 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3305 }
3306
Jordan Rose0e5badd2012-12-05 18:44:49 +00003307 if (ShouldNotPrintDirectly) {
3308 // The expression has a type that should not be printed directly.
3309 // We extract the name from the typedef because we don't want to show
3310 // the underlying type in the diagnostic.
3311 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003312
Jordan Rose0e5badd2012-12-05 18:44:49 +00003313 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3314 << Name << IntendedTy
3315 << E->getSourceRange(),
3316 E->getLocStart(), /*IsStringLocation=*/false,
3317 SpecRange, Hints);
3318 } else {
3319 // In this case, the expression could be printed using a different
3320 // specifier, but we've decided that the specifier is probably correct
3321 // and we should cast instead. Just use the normal warning message.
3322 EmitFormatDiagnostic(
3323 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3324 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3325 << E->getSourceRange(),
3326 E->getLocStart(), /*IsStringLocation*/false,
3327 SpecRange, Hints);
3328 }
Jordan Roseaee34382012-09-05 22:56:26 +00003329 }
Jordan Rose22b74712012-09-05 22:56:19 +00003330 } else {
3331 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3332 SpecifierLen);
3333 // Since the warning for passing non-POD types to variadic functions
3334 // was deferred until now, we emit a warning for non-POD
3335 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003336 switch (S.isValidVarArgType(ExprTy)) {
3337 case Sema::VAK_Valid:
3338 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003339 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003340 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3341 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3342 << CSR
3343 << E->getSourceRange(),
3344 E->getLocStart(), /*IsStringLocation*/false, CSR);
3345 break;
3346
3347 case Sema::VAK_Undefined:
3348 EmitFormatDiagnostic(
3349 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003350 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003351 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003352 << CallType
3353 << AT.getRepresentativeTypeName(S.Context)
3354 << CSR
3355 << E->getSourceRange(),
3356 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003357 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003358 break;
3359
3360 case Sema::VAK_Invalid:
3361 if (ExprTy->isObjCObjectType())
3362 EmitFormatDiagnostic(
3363 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3364 << S.getLangOpts().CPlusPlus11
3365 << ExprTy
3366 << CallType
3367 << AT.getRepresentativeTypeName(S.Context)
3368 << CSR
3369 << E->getSourceRange(),
3370 E->getLocStart(), /*IsStringLocation*/false, CSR);
3371 else
3372 // FIXME: If this is an initializer list, suggest removing the braces
3373 // or inserting a cast to the target type.
3374 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3375 << isa<InitListExpr>(E) << ExprTy << CallType
3376 << AT.getRepresentativeTypeName(S.Context)
3377 << E->getSourceRange();
3378 break;
3379 }
3380
3381 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3382 "format string specifier index out of range");
3383 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003384 }
3385
Ted Kremenekab278de2010-01-28 23:39:18 +00003386 return true;
3387}
3388
Ted Kremenek02087932010-07-16 02:11:22 +00003389//===--- CHECK: Scanf format string checking ------------------------------===//
3390
3391namespace {
3392class CheckScanfHandler : public CheckFormatHandler {
3393public:
3394 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3395 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003396 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003397 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003398 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003399 Sema::VariadicCallType CallType,
3400 llvm::SmallBitVector &CheckedVarArgs)
3401 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3402 numDataArgs, beg, hasVAListArg,
3403 Args, formatIdx, inFunctionCall, CallType,
3404 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003405 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003406
3407 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3408 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003409 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003410
3411 bool HandleInvalidScanfConversionSpecifier(
3412 const analyze_scanf::ScanfSpecifier &FS,
3413 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003414 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003415
Craig Toppere14c0f82014-03-12 04:55:44 +00003416 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003417};
Ted Kremenek019d2242010-01-29 01:50:07 +00003418}
Ted Kremenekab278de2010-01-28 23:39:18 +00003419
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003420void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3421 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003422 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3423 getLocationOfByte(end), /*IsStringLocation*/true,
3424 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003425}
3426
Ted Kremenekce815422010-07-19 21:25:57 +00003427bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3428 const analyze_scanf::ScanfSpecifier &FS,
3429 const char *startSpecifier,
3430 unsigned specifierLen) {
3431
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003432 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003433 FS.getConversionSpecifier();
3434
3435 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3436 getLocationOfByte(CS.getStart()),
3437 startSpecifier, specifierLen,
3438 CS.getStart(), CS.getLength());
3439}
3440
Ted Kremenek02087932010-07-16 02:11:22 +00003441bool CheckScanfHandler::HandleScanfSpecifier(
3442 const analyze_scanf::ScanfSpecifier &FS,
3443 const char *startSpecifier,
3444 unsigned specifierLen) {
3445
3446 using namespace analyze_scanf;
3447 using namespace analyze_format_string;
3448
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003449 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003450
Ted Kremenek6cd69422010-07-19 22:01:06 +00003451 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3452 // be used to decide if we are using positional arguments consistently.
3453 if (FS.consumesDataArgument()) {
3454 if (atFirstArg) {
3455 atFirstArg = false;
3456 usesPositionalArgs = FS.usesPositionalArg();
3457 }
3458 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003459 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3460 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003461 return false;
3462 }
Ted Kremenek02087932010-07-16 02:11:22 +00003463 }
3464
3465 // Check if the field with is non-zero.
3466 const OptionalAmount &Amt = FS.getFieldWidth();
3467 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3468 if (Amt.getConstantAmount() == 0) {
3469 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3470 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003471 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3472 getLocationOfByte(Amt.getStart()),
3473 /*IsStringLocation*/true, R,
3474 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003475 }
3476 }
3477
3478 if (!FS.consumesDataArgument()) {
3479 // FIXME: Technically specifying a precision or field width here
3480 // makes no sense. Worth issuing a warning at some point.
3481 return true;
3482 }
3483
3484 // Consume the argument.
3485 unsigned argIndex = FS.getArgIndex();
3486 if (argIndex < NumDataArgs) {
3487 // The check to see if the argIndex is valid will come later.
3488 // We set the bit here because we may exit early from this
3489 // function if we encounter some other error.
3490 CoveredArgs.set(argIndex);
3491 }
3492
Ted Kremenek4407ea42010-07-20 20:04:47 +00003493 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003494 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003495 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3496 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003497 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003498 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003499 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003500 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3501 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003502
Jordan Rose92303592012-09-08 04:00:03 +00003503 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3504 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3505
Ted Kremenek02087932010-07-16 02:11:22 +00003506 // The remaining checks depend on the data arguments.
3507 if (HasVAListArg)
3508 return true;
3509
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003510 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003511 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003512
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003513 // Check that the argument type matches the format specifier.
3514 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003515 if (!Ex)
3516 return true;
3517
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003518 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3519 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003520 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003521 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003522 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003523
3524 if (success) {
3525 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003526 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003527 llvm::raw_svector_ostream os(buf);
3528 fixedFS.toString(os);
3529
3530 EmitFormatDiagnostic(
3531 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003532 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003533 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003534 Ex->getLocStart(),
3535 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003536 getSpecifierRange(startSpecifier, specifierLen),
3537 FixItHint::CreateReplacement(
3538 getSpecifierRange(startSpecifier, specifierLen),
3539 os.str()));
3540 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003541 EmitFormatDiagnostic(
3542 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003543 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003544 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003545 Ex->getLocStart(),
3546 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003547 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003548 }
3549 }
3550
Ted Kremenek02087932010-07-16 02:11:22 +00003551 return true;
3552}
3553
3554void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003555 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003556 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003557 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003558 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003559 bool inFunctionCall, VariadicCallType CallType,
3560 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003561
Ted Kremenekab278de2010-01-28 23:39:18 +00003562 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003563 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003564 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003565 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003566 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3567 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003568 return;
3569 }
Ted Kremenek02087932010-07-16 02:11:22 +00003570
Ted Kremenekab278de2010-01-28 23:39:18 +00003571 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003572 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003573 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003574 // Account for cases where the string literal is truncated in a declaration.
3575 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
3576 assert(T && "String literal not of constant array type!");
3577 size_t TypeSize = T->getSize().getZExtValue();
3578 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003579 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00003580
3581 // Emit a warning if the string literal is truncated and does not contain an
3582 // embedded null character.
3583 if (TypeSize <= StrRef.size() &&
3584 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
3585 CheckFormatHandler::EmitFormatDiagnostic(
3586 *this, inFunctionCall, Args[format_idx],
3587 PDiag(diag::warn_printf_format_string_not_null_terminated),
3588 FExpr->getLocStart(),
3589 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
3590 return;
3591 }
3592
Ted Kremenekab278de2010-01-28 23:39:18 +00003593 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003594 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003595 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003596 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003597 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3598 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003599 return;
3600 }
Ted Kremenek02087932010-07-16 02:11:22 +00003601
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003602 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003603 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003604 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003605 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003606 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003607
Hans Wennborg23926bd2011-12-15 10:25:47 +00003608 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003609 getLangOpts(),
3610 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003611 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003612 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003613 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003614 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003615 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003616
Hans Wennborg23926bd2011-12-15 10:25:47 +00003617 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003618 getLangOpts(),
3619 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003620 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003621 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003622}
3623
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003624//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
3625
3626// Returns the related absolute value function that is larger, of 0 if one
3627// does not exist.
3628static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
3629 switch (AbsFunction) {
3630 default:
3631 return 0;
3632
3633 case Builtin::BI__builtin_abs:
3634 return Builtin::BI__builtin_labs;
3635 case Builtin::BI__builtin_labs:
3636 return Builtin::BI__builtin_llabs;
3637 case Builtin::BI__builtin_llabs:
3638 return 0;
3639
3640 case Builtin::BI__builtin_fabsf:
3641 return Builtin::BI__builtin_fabs;
3642 case Builtin::BI__builtin_fabs:
3643 return Builtin::BI__builtin_fabsl;
3644 case Builtin::BI__builtin_fabsl:
3645 return 0;
3646
3647 case Builtin::BI__builtin_cabsf:
3648 return Builtin::BI__builtin_cabs;
3649 case Builtin::BI__builtin_cabs:
3650 return Builtin::BI__builtin_cabsl;
3651 case Builtin::BI__builtin_cabsl:
3652 return 0;
3653
3654 case Builtin::BIabs:
3655 return Builtin::BIlabs;
3656 case Builtin::BIlabs:
3657 return Builtin::BIllabs;
3658 case Builtin::BIllabs:
3659 return 0;
3660
3661 case Builtin::BIfabsf:
3662 return Builtin::BIfabs;
3663 case Builtin::BIfabs:
3664 return Builtin::BIfabsl;
3665 case Builtin::BIfabsl:
3666 return 0;
3667
3668 case Builtin::BIcabsf:
3669 return Builtin::BIcabs;
3670 case Builtin::BIcabs:
3671 return Builtin::BIcabsl;
3672 case Builtin::BIcabsl:
3673 return 0;
3674 }
3675}
3676
3677// Returns the argument type of the absolute value function.
3678static QualType getAbsoluteValueArgumentType(ASTContext &Context,
3679 unsigned AbsType) {
3680 if (AbsType == 0)
3681 return QualType();
3682
3683 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3684 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
3685 if (Error != ASTContext::GE_None)
3686 return QualType();
3687
3688 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
3689 if (!FT)
3690 return QualType();
3691
3692 if (FT->getNumParams() != 1)
3693 return QualType();
3694
3695 return FT->getParamType(0);
3696}
3697
3698// Returns the best absolute value function, or zero, based on type and
3699// current absolute value function.
3700static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
3701 unsigned AbsFunctionKind) {
3702 unsigned BestKind = 0;
3703 uint64_t ArgSize = Context.getTypeSize(ArgType);
3704 for (unsigned Kind = AbsFunctionKind; Kind != 0;
3705 Kind = getLargerAbsoluteValueFunction(Kind)) {
3706 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
3707 if (Context.getTypeSize(ParamType) >= ArgSize) {
3708 if (BestKind == 0)
3709 BestKind = Kind;
3710 else if (Context.hasSameType(ParamType, ArgType)) {
3711 BestKind = Kind;
3712 break;
3713 }
3714 }
3715 }
3716 return BestKind;
3717}
3718
3719enum AbsoluteValueKind {
3720 AVK_Integer,
3721 AVK_Floating,
3722 AVK_Complex
3723};
3724
3725static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
3726 if (T->isIntegralOrEnumerationType())
3727 return AVK_Integer;
3728 if (T->isRealFloatingType())
3729 return AVK_Floating;
3730 if (T->isAnyComplexType())
3731 return AVK_Complex;
3732
3733 llvm_unreachable("Type not integer, floating, or complex");
3734}
3735
3736// Changes the absolute value function to a different type. Preserves whether
3737// the function is a builtin.
3738static unsigned changeAbsFunction(unsigned AbsKind,
3739 AbsoluteValueKind ValueKind) {
3740 switch (ValueKind) {
3741 case AVK_Integer:
3742 switch (AbsKind) {
3743 default:
3744 return 0;
3745 case Builtin::BI__builtin_fabsf:
3746 case Builtin::BI__builtin_fabs:
3747 case Builtin::BI__builtin_fabsl:
3748 case Builtin::BI__builtin_cabsf:
3749 case Builtin::BI__builtin_cabs:
3750 case Builtin::BI__builtin_cabsl:
3751 return Builtin::BI__builtin_abs;
3752 case Builtin::BIfabsf:
3753 case Builtin::BIfabs:
3754 case Builtin::BIfabsl:
3755 case Builtin::BIcabsf:
3756 case Builtin::BIcabs:
3757 case Builtin::BIcabsl:
3758 return Builtin::BIabs;
3759 }
3760 case AVK_Floating:
3761 switch (AbsKind) {
3762 default:
3763 return 0;
3764 case Builtin::BI__builtin_abs:
3765 case Builtin::BI__builtin_labs:
3766 case Builtin::BI__builtin_llabs:
3767 case Builtin::BI__builtin_cabsf:
3768 case Builtin::BI__builtin_cabs:
3769 case Builtin::BI__builtin_cabsl:
3770 return Builtin::BI__builtin_fabsf;
3771 case Builtin::BIabs:
3772 case Builtin::BIlabs:
3773 case Builtin::BIllabs:
3774 case Builtin::BIcabsf:
3775 case Builtin::BIcabs:
3776 case Builtin::BIcabsl:
3777 return Builtin::BIfabsf;
3778 }
3779 case AVK_Complex:
3780 switch (AbsKind) {
3781 default:
3782 return 0;
3783 case Builtin::BI__builtin_abs:
3784 case Builtin::BI__builtin_labs:
3785 case Builtin::BI__builtin_llabs:
3786 case Builtin::BI__builtin_fabsf:
3787 case Builtin::BI__builtin_fabs:
3788 case Builtin::BI__builtin_fabsl:
3789 return Builtin::BI__builtin_cabsf;
3790 case Builtin::BIabs:
3791 case Builtin::BIlabs:
3792 case Builtin::BIllabs:
3793 case Builtin::BIfabsf:
3794 case Builtin::BIfabs:
3795 case Builtin::BIfabsl:
3796 return Builtin::BIcabsf;
3797 }
3798 }
3799 llvm_unreachable("Unable to convert function");
3800}
3801
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00003802static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003803 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
3804 if (!FnInfo)
3805 return 0;
3806
3807 switch (FDecl->getBuiltinID()) {
3808 default:
3809 return 0;
3810 case Builtin::BI__builtin_abs:
3811 case Builtin::BI__builtin_fabs:
3812 case Builtin::BI__builtin_fabsf:
3813 case Builtin::BI__builtin_fabsl:
3814 case Builtin::BI__builtin_labs:
3815 case Builtin::BI__builtin_llabs:
3816 case Builtin::BI__builtin_cabs:
3817 case Builtin::BI__builtin_cabsf:
3818 case Builtin::BI__builtin_cabsl:
3819 case Builtin::BIabs:
3820 case Builtin::BIlabs:
3821 case Builtin::BIllabs:
3822 case Builtin::BIfabs:
3823 case Builtin::BIfabsf:
3824 case Builtin::BIfabsl:
3825 case Builtin::BIcabs:
3826 case Builtin::BIcabsf:
3827 case Builtin::BIcabsl:
3828 return FDecl->getBuiltinID();
3829 }
3830 llvm_unreachable("Unknown Builtin type");
3831}
3832
3833// If the replacement is valid, emit a note with replacement function.
3834// Additionally, suggest including the proper header if not already included.
3835static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
3836 unsigned AbsKind) {
3837 std::string AbsName = S.Context.BuiltinInfo.GetName(AbsKind);
3838
3839 // Look up absolute value function in TU scope.
3840 DeclarationName DN(&S.Context.Idents.get(AbsName));
3841 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
Richard Trieufe771c02014-03-06 02:25:04 +00003842 R.suppressDiagnostics();
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00003843 S.LookupName(R, S.TUScope);
3844
3845 // Skip notes if multiple results found in lookup.
3846 if (!R.empty() && !R.isSingleResult())
3847 return;
3848
3849 FunctionDecl *FD = 0;
3850 bool FoundFunction = R.isSingleResult();
3851 // When one result is found, see if it is the correct function.
3852 if (R.isSingleResult()) {
3853 FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3854 if (!FD || FD->getBuiltinID() != AbsKind)
3855 return;
3856 }
3857
3858 // Look for local name conflict, prepend "::" as necessary.
3859 R.clear();
3860 S.LookupName(R, S.getCurScope());
3861
3862 if (!FoundFunction) {
3863 if (!R.empty()) {
3864 AbsName = "::" + AbsName;
3865 }
3866 } else { // FoundFunction
3867 if (R.isSingleResult()) {
3868 if (R.getFoundDecl() != FD) {
3869 AbsName = "::" + AbsName;
3870 }
3871 } else if (!R.empty()) {
3872 AbsName = "::" + AbsName;
3873 }
3874 }
3875
3876 S.Diag(Loc, diag::note_replace_abs_function)
3877 << AbsName << FixItHint::CreateReplacement(Range, AbsName);
3878
3879 if (!FoundFunction) {
3880 S.Diag(Loc, diag::note_please_include_header)
3881 << S.Context.BuiltinInfo.getHeaderName(AbsKind)
3882 << S.Context.BuiltinInfo.GetName(AbsKind);
3883 }
3884}
3885
3886// Warn when using the wrong abs() function.
3887void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
3888 const FunctionDecl *FDecl,
3889 IdentifierInfo *FnInfo) {
3890 if (Call->getNumArgs() != 1)
3891 return;
3892
3893 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
3894 if (AbsKind == 0)
3895 return;
3896
3897 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
3898 QualType ParamType = Call->getArg(0)->getType();
3899
3900 // Unsigned types can not be negative. Suggest to drop the absolute value
3901 // function.
3902 if (ArgType->isUnsignedIntegerType()) {
3903 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
3904 Diag(Call->getExprLoc(), diag::note_remove_abs)
3905 << FDecl
3906 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
3907 return;
3908 }
3909
3910 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
3911 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
3912
3913 // The argument and parameter are the same kind. Check if they are the right
3914 // size.
3915 if (ArgValueKind == ParamValueKind) {
3916 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
3917 return;
3918
3919 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
3920 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
3921 << FDecl << ArgType << ParamType;
3922
3923 if (NewAbsKind == 0)
3924 return;
3925
3926 emitReplacement(*this, Call->getExprLoc(),
3927 Call->getCallee()->getSourceRange(), NewAbsKind);
3928 return;
3929 }
3930
3931 // ArgValueKind != ParamValueKind
3932 // The wrong type of absolute value function was used. Attempt to find the
3933 // proper one.
3934 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
3935 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
3936 if (NewAbsKind == 0)
3937 return;
3938
3939 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
3940 << FDecl << ParamValueKind << ArgValueKind;
3941
3942 emitReplacement(*this, Call->getExprLoc(),
3943 Call->getCallee()->getSourceRange(), NewAbsKind);
3944 return;
3945}
3946
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003947//===--- CHECK: Standard memory functions ---------------------------------===//
3948
Nico Weber0e6daef2013-12-26 23:38:39 +00003949/// \brief Takes the expression passed to the size_t parameter of functions
3950/// such as memcmp, strncat, etc and warns if it's a comparison.
3951///
3952/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3953static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3954 IdentifierInfo *FnName,
3955 SourceLocation FnLoc,
3956 SourceLocation RParenLoc) {
3957 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3958 if (!Size)
3959 return false;
3960
3961 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3962 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3963 return false;
3964
3965 Preprocessor &PP = S.getPreprocessor();
3966 SourceRange SizeRange = Size->getSourceRange();
3967 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3968 << SizeRange << FnName;
3969 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3970 << FnName
3971 << FixItHint::CreateInsertion(
3972 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3973 ")")
3974 << FixItHint::CreateRemoval(RParenLoc);
3975 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3976 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3977 << FixItHint::CreateInsertion(
3978 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3979
3980 return true;
3981}
3982
Douglas Gregora74926b2011-05-03 20:05:22 +00003983/// \brief Determine whether the given type is a dynamic class type (e.g.,
3984/// whether it has a vtable).
3985static bool isDynamicClassType(QualType T) {
3986 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3987 if (CXXRecordDecl *Definition = Record->getDefinition())
3988 if (Definition->isDynamicClass())
3989 return true;
3990
3991 return false;
3992}
3993
Chandler Carruth889ed862011-06-21 23:04:20 +00003994/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003995/// otherwise returns NULL.
3996static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003997 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003998 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3999 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4000 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004001
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004002 return 0;
4003}
4004
Chandler Carruth889ed862011-06-21 23:04:20 +00004005/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004006static QualType getSizeOfArgType(const Expr* E) {
4007 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4008 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4009 if (SizeOf->getKind() == clang::UETT_SizeOf)
4010 return SizeOf->getTypeOfArgument();
4011
4012 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004013}
4014
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004015/// \brief Check for dangerous or invalid arguments to memset().
4016///
Chandler Carruthac687262011-06-03 06:23:57 +00004017/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004018/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4019/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004020///
4021/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004022void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004023 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004024 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004025 assert(BId != 0);
4026
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004027 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004028 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004029 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004030 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004031 return;
4032
Anna Zaks22122702012-01-17 00:37:07 +00004033 unsigned LastArg = (BId == Builtin::BImemset ||
4034 BId == Builtin::BIstrndup ? 1 : 2);
4035 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004036 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004037
Nico Weber0e6daef2013-12-26 23:38:39 +00004038 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4039 Call->getLocStart(), Call->getRParenLoc()))
4040 return;
4041
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004042 // We have special checking when the length is a sizeof expression.
4043 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4044 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4045 llvm::FoldingSetNodeID SizeOfArgID;
4046
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004047 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4048 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004049 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004050
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004051 QualType DestTy = Dest->getType();
4052 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4053 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004054
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004055 // Never warn about void type pointers. This can be used to suppress
4056 // false positives.
4057 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004058 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004059
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004060 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4061 // actually comparing the expressions for equality. Because computing the
4062 // expression IDs can be expensive, we only do this if the diagnostic is
4063 // enabled.
4064 if (SizeOfArg &&
4065 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
4066 SizeOfArg->getExprLoc())) {
4067 // We only compute IDs for expressions if the warning is enabled, and
4068 // cache the sizeof arg's ID.
4069 if (SizeOfArgID == llvm::FoldingSetNodeID())
4070 SizeOfArg->Profile(SizeOfArgID, Context, true);
4071 llvm::FoldingSetNodeID DestID;
4072 Dest->Profile(DestID, Context, true);
4073 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004074 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4075 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004076 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004077 StringRef ReadableName = FnName->getName();
4078
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004079 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004080 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004081 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004082 if (!PointeeTy->isIncompleteType() &&
4083 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004084 ActionIdx = 2; // If the pointee's size is sizeof(char),
4085 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004086
4087 // If the function is defined as a builtin macro, do not show macro
4088 // expansion.
4089 SourceLocation SL = SizeOfArg->getExprLoc();
4090 SourceRange DSR = Dest->getSourceRange();
4091 SourceRange SSR = SizeOfArg->getSourceRange();
4092 SourceManager &SM = PP.getSourceManager();
4093
4094 if (SM.isMacroArgExpansion(SL)) {
4095 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4096 SL = SM.getSpellingLoc(SL);
4097 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4098 SM.getSpellingLoc(DSR.getEnd()));
4099 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4100 SM.getSpellingLoc(SSR.getEnd()));
4101 }
4102
Anna Zaksd08d9152012-05-30 23:14:52 +00004103 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004104 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004105 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004106 << PointeeTy
4107 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004108 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004109 << SSR);
4110 DiagRuntimeBehavior(SL, SizeOfArg,
4111 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4112 << ActionIdx
4113 << SSR);
4114
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004115 break;
4116 }
4117 }
4118
4119 // Also check for cases where the sizeof argument is the exact same
4120 // type as the memory argument, and where it points to a user-defined
4121 // record type.
4122 if (SizeOfArgTy != QualType()) {
4123 if (PointeeTy->isRecordType() &&
4124 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4125 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4126 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4127 << FnName << SizeOfArgTy << ArgIdx
4128 << PointeeTy << Dest->getSourceRange()
4129 << LenExpr->getSourceRange());
4130 break;
4131 }
Nico Weberc5e73862011-06-14 16:14:58 +00004132 }
4133
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004134 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00004135 if (isDynamicClassType(PointeeTy)) {
4136
4137 unsigned OperationType = 0;
4138 // "overwritten" if we're warning about the destination for any call
4139 // but memcmp; otherwise a verb appropriate to the call.
4140 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4141 if (BId == Builtin::BImemcpy)
4142 OperationType = 1;
4143 else if(BId == Builtin::BImemmove)
4144 OperationType = 2;
4145 else if (BId == Builtin::BImemcmp)
4146 OperationType = 3;
4147 }
4148
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004149 DiagRuntimeBehavior(
4150 Dest->getExprLoc(), Dest,
4151 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004152 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00004153 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00004154 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004155 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004156 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4157 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004158 DiagRuntimeBehavior(
4159 Dest->getExprLoc(), Dest,
4160 PDiag(diag::warn_arc_object_memaccess)
4161 << ArgIdx << FnName << PointeeTy
4162 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004163 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004164 continue;
John McCall31168b02011-06-15 23:02:42 +00004165
4166 DiagRuntimeBehavior(
4167 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004168 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004169 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4170 break;
4171 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004172 }
4173}
4174
Ted Kremenek6865f772011-08-18 20:55:45 +00004175// A little helper routine: ignore addition and subtraction of integer literals.
4176// This intentionally does not ignore all integer constant expressions because
4177// we don't want to remove sizeof().
4178static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4179 Ex = Ex->IgnoreParenCasts();
4180
4181 for (;;) {
4182 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4183 if (!BO || !BO->isAdditiveOp())
4184 break;
4185
4186 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4187 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4188
4189 if (isa<IntegerLiteral>(RHS))
4190 Ex = LHS;
4191 else if (isa<IntegerLiteral>(LHS))
4192 Ex = RHS;
4193 else
4194 break;
4195 }
4196
4197 return Ex;
4198}
4199
Anna Zaks13b08572012-08-08 21:42:23 +00004200static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4201 ASTContext &Context) {
4202 // Only handle constant-sized or VLAs, but not flexible members.
4203 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4204 // Only issue the FIXIT for arrays of size > 1.
4205 if (CAT->getSize().getSExtValue() <= 1)
4206 return false;
4207 } else if (!Ty->isVariableArrayType()) {
4208 return false;
4209 }
4210 return true;
4211}
4212
Ted Kremenek6865f772011-08-18 20:55:45 +00004213// Warn if the user has made the 'size' argument to strlcpy or strlcat
4214// be the size of the source, instead of the destination.
4215void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4216 IdentifierInfo *FnName) {
4217
4218 // Don't crash if the user has the wrong number of arguments
4219 if (Call->getNumArgs() != 3)
4220 return;
4221
4222 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4223 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4224 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00004225
4226 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4227 Call->getLocStart(), Call->getRParenLoc()))
4228 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004229
4230 // Look for 'strlcpy(dst, x, sizeof(x))'
4231 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4232 CompareWithSrc = Ex;
4233 else {
4234 // Look for 'strlcpy(dst, x, strlen(x))'
4235 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004236 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4237 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004238 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4239 }
4240 }
4241
4242 if (!CompareWithSrc)
4243 return;
4244
4245 // Determine if the argument to sizeof/strlen is equal to the source
4246 // argument. In principle there's all kinds of things you could do
4247 // here, for instance creating an == expression and evaluating it with
4248 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4249 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4250 if (!SrcArgDRE)
4251 return;
4252
4253 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4254 if (!CompareWithSrcDRE ||
4255 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4256 return;
4257
4258 const Expr *OriginalSizeArg = Call->getArg(2);
4259 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4260 << OriginalSizeArg->getSourceRange() << FnName;
4261
4262 // Output a FIXIT hint if the destination is an array (rather than a
4263 // pointer to an array). This could be enhanced to handle some
4264 // pointers if we know the actual size, like if DstArg is 'array+2'
4265 // we could say 'sizeof(array)-2'.
4266 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004267 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004268 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004269
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004270 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004271 llvm::raw_svector_ostream OS(sizeString);
4272 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004273 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004274 OS << ")";
4275
4276 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4277 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4278 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004279}
4280
Anna Zaks314cd092012-02-01 19:08:57 +00004281/// Check if two expressions refer to the same declaration.
4282static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4283 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4284 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4285 return D1->getDecl() == D2->getDecl();
4286 return false;
4287}
4288
4289static const Expr *getStrlenExprArg(const Expr *E) {
4290 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4291 const FunctionDecl *FD = CE->getDirectCallee();
4292 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4293 return 0;
4294 return CE->getArg(0)->IgnoreParenCasts();
4295 }
4296 return 0;
4297}
4298
4299// Warn on anti-patterns as the 'size' argument to strncat.
4300// The correct size argument should look like following:
4301// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4302void Sema::CheckStrncatArguments(const CallExpr *CE,
4303 IdentifierInfo *FnName) {
4304 // Don't crash if the user has the wrong number of arguments.
4305 if (CE->getNumArgs() < 3)
4306 return;
4307 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4308 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4309 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4310
Nico Weber0e6daef2013-12-26 23:38:39 +00004311 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4312 CE->getRParenLoc()))
4313 return;
4314
Anna Zaks314cd092012-02-01 19:08:57 +00004315 // Identify common expressions, which are wrongly used as the size argument
4316 // to strncat and may lead to buffer overflows.
4317 unsigned PatternType = 0;
4318 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4319 // - sizeof(dst)
4320 if (referToTheSameDecl(SizeOfArg, DstArg))
4321 PatternType = 1;
4322 // - sizeof(src)
4323 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4324 PatternType = 2;
4325 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4326 if (BE->getOpcode() == BO_Sub) {
4327 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4328 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4329 // - sizeof(dst) - strlen(dst)
4330 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4331 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4332 PatternType = 1;
4333 // - sizeof(src) - (anything)
4334 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4335 PatternType = 2;
4336 }
4337 }
4338
4339 if (PatternType == 0)
4340 return;
4341
Anna Zaks5069aa32012-02-03 01:27:37 +00004342 // Generate the diagnostic.
4343 SourceLocation SL = LenArg->getLocStart();
4344 SourceRange SR = LenArg->getSourceRange();
4345 SourceManager &SM = PP.getSourceManager();
4346
4347 // If the function is defined as a builtin macro, do not show macro expansion.
4348 if (SM.isMacroArgExpansion(SL)) {
4349 SL = SM.getSpellingLoc(SL);
4350 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4351 SM.getSpellingLoc(SR.getEnd()));
4352 }
4353
Anna Zaks13b08572012-08-08 21:42:23 +00004354 // Check if the destination is an array (rather than a pointer to an array).
4355 QualType DstTy = DstArg->getType();
4356 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4357 Context);
4358 if (!isKnownSizeArray) {
4359 if (PatternType == 1)
4360 Diag(SL, diag::warn_strncat_wrong_size) << SR;
4361 else
4362 Diag(SL, diag::warn_strncat_src_size) << SR;
4363 return;
4364 }
4365
Anna Zaks314cd092012-02-01 19:08:57 +00004366 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00004367 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004368 else
Anna Zaks5069aa32012-02-03 01:27:37 +00004369 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00004370
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004371 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004372 llvm::raw_svector_ostream OS(sizeString);
4373 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004374 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004375 OS << ") - ";
4376 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004377 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004378 OS << ") - 1";
4379
Anna Zaks5069aa32012-02-03 01:27:37 +00004380 Diag(SL, diag::note_strncat_wrong_size)
4381 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004382}
4383
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004384//===--- CHECK: Return Address of Stack Variable --------------------------===//
4385
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004386static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4387 Decl *ParentDecl);
4388static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4389 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004390
4391/// CheckReturnStackAddr - Check if a return statement returns the address
4392/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004393static void
4394CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
4395 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004396
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004397 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004398 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004399
4400 // Perform checking for returned stack addresses, local blocks,
4401 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004402 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004403 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004404 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004405 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004406 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004407 }
4408
4409 if (stackE == 0)
4410 return; // Nothing suspicious was found.
4411
4412 SourceLocation diagLoc;
4413 SourceRange diagRange;
4414 if (refVars.empty()) {
4415 diagLoc = stackE->getLocStart();
4416 diagRange = stackE->getSourceRange();
4417 } else {
4418 // We followed through a reference variable. 'stackE' contains the
4419 // problematic expression but we will warn at the return statement pointing
4420 // at the reference variable. We will later display the "trail" of
4421 // reference variables using notes.
4422 diagLoc = refVars[0]->getLocStart();
4423 diagRange = refVars[0]->getSourceRange();
4424 }
4425
4426 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004427 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004428 : diag::warn_ret_stack_addr)
4429 << DR->getDecl()->getDeclName() << diagRange;
4430 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004431 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004432 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004433 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004434 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004435 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4436 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004437 << diagRange;
4438 }
4439
4440 // Display the "trail" of reference variables that we followed until we
4441 // found the problematic expression using notes.
4442 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4443 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4444 // If this var binds to another reference var, show the range of the next
4445 // var, otherwise the var binds to the problematic expression, in which case
4446 // show the range of the expression.
4447 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4448 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004449 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4450 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004451 }
4452}
4453
4454/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4455/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004456/// to a location on the stack, a local block, an address of a label, or a
4457/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004458/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004459/// encounter a subexpression that (1) clearly does not lead to one of the
4460/// above problematic expressions (2) is something we cannot determine leads to
4461/// a problematic expression based on such local checking.
4462///
4463/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4464/// the expression that they point to. Such variables are added to the
4465/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004466///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004467/// EvalAddr processes expressions that are pointers that are used as
4468/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004469/// At the base case of the recursion is a check for the above problematic
4470/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004471///
4472/// This implementation handles:
4473///
4474/// * pointer-to-pointer casts
4475/// * implicit conversions from array references to pointers
4476/// * taking the address of fields
4477/// * arbitrary interplay between "&" and "*" operators
4478/// * pointer arithmetic from an address of a stack variable
4479/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004480static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4481 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004482 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004483 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004484
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004485 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004486 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004487 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004488 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004489 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004490
Peter Collingbourne91147592011-04-15 00:35:48 +00004491 E = E->IgnoreParens();
4492
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004493 // Our "symbolic interpreter" is just a dispatch off the currently
4494 // viewed AST node. We then recursively traverse the AST by calling
4495 // EvalAddr and EvalVal appropriately.
4496 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004497 case Stmt::DeclRefExprClass: {
4498 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4499
Richard Smith40f08eb2014-01-30 22:05:38 +00004500 // If we leave the immediate function, the lifetime isn't about to end.
4501 if (DR->refersToEnclosingLocal())
4502 return 0;
4503
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004504 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4505 // If this is a reference variable, follow through to the expression that
4506 // it points to.
4507 if (V->hasLocalStorage() &&
4508 V->getType()->isReferenceType() && V->hasInit()) {
4509 // Add the reference variable to the "trail".
4510 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004511 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004512 }
4513
4514 return NULL;
4515 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004516
Chris Lattner934edb22007-12-28 05:31:15 +00004517 case Stmt::UnaryOperatorClass: {
4518 // The only unary operator that make sense to handle here
4519 // is AddrOf. All others don't make sense as pointers.
4520 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004521
John McCalle3027922010-08-25 11:45:40 +00004522 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004523 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004524 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004525 return NULL;
4526 }
Mike Stump11289f42009-09-09 15:08:12 +00004527
Chris Lattner934edb22007-12-28 05:31:15 +00004528 case Stmt::BinaryOperatorClass: {
4529 // Handle pointer arithmetic. All other binary operators are not valid
4530 // in this context.
4531 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004532 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004533
John McCalle3027922010-08-25 11:45:40 +00004534 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004535 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004536
Chris Lattner934edb22007-12-28 05:31:15 +00004537 Expr *Base = B->getLHS();
4538
4539 // Determine which argument is the real pointer base. It could be
4540 // the RHS argument instead of the LHS.
4541 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004542
Chris Lattner934edb22007-12-28 05:31:15 +00004543 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004544 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004545 }
Steve Naroff2752a172008-09-10 19:17:48 +00004546
Chris Lattner934edb22007-12-28 05:31:15 +00004547 // For conditional operators we need to see if either the LHS or RHS are
4548 // valid DeclRefExpr*s. If one of them is valid, we return it.
4549 case Stmt::ConditionalOperatorClass: {
4550 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004551
Chris Lattner934edb22007-12-28 05:31:15 +00004552 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004553 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
4554 if (Expr *LHSExpr = C->getLHS()) {
4555 // In C++, we can have a throw-expression, which has 'void' type.
4556 if (!LHSExpr->getType()->isVoidType())
4557 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004558 return LHS;
4559 }
Chris Lattner934edb22007-12-28 05:31:15 +00004560
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004561 // In C++, we can have a throw-expression, which has 'void' type.
4562 if (C->getRHS()->getType()->isVoidType())
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004563 return 0;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004564
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004565 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004566 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004567
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004568 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004569 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004570 return E; // local block.
4571 return NULL;
4572
4573 case Stmt::AddrLabelExprClass:
4574 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004575
John McCall28fc7092011-11-10 05:35:25 +00004576 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004577 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4578 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004579
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004580 // For casts, we need to handle conversions from arrays to
4581 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004582 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004583 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004584 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004585 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004586 case Stmt::CXXStaticCastExprClass:
4587 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004588 case Stmt::CXXConstCastExprClass:
4589 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004590 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4591 switch (cast<CastExpr>(E)->getCastKind()) {
4592 case CK_BitCast:
4593 case CK_LValueToRValue:
4594 case CK_NoOp:
4595 case CK_BaseToDerived:
4596 case CK_DerivedToBase:
4597 case CK_UncheckedDerivedToBase:
4598 case CK_Dynamic:
4599 case CK_CPointerToObjCPointerCast:
4600 case CK_BlockPointerToObjCPointerCast:
4601 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004602 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004603
4604 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004605 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004606
4607 default:
4608 return 0;
4609 }
Chris Lattner934edb22007-12-28 05:31:15 +00004610 }
Mike Stump11289f42009-09-09 15:08:12 +00004611
Douglas Gregorfe314812011-06-21 17:03:29 +00004612 case Stmt::MaterializeTemporaryExprClass:
4613 if (Expr *Result = EvalAddr(
4614 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004615 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004616 return Result;
4617
4618 return E;
4619
Chris Lattner934edb22007-12-28 05:31:15 +00004620 // Everything else: we simply don't reason about them.
4621 default:
4622 return NULL;
4623 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004624}
Mike Stump11289f42009-09-09 15:08:12 +00004625
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004626
4627/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4628/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004629static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4630 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004631do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004632 // We should only be called for evaluating non-pointer expressions, or
4633 // expressions with a pointer type that are not used as references but instead
4634 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004635
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004636 // Our "symbolic interpreter" is just a dispatch off the currently
4637 // viewed AST node. We then recursively traverse the AST by calling
4638 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004639
4640 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004641 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004642 case Stmt::ImplicitCastExprClass: {
4643 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004644 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004645 E = IE->getSubExpr();
4646 continue;
4647 }
4648 return NULL;
4649 }
4650
John McCall28fc7092011-11-10 05:35:25 +00004651 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004652 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004653
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004654 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004655 // When we hit a DeclRefExpr we are looking at code that refers to a
4656 // variable's name. If it's not a reference variable we check if it has
4657 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004658 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004659
Richard Smith40f08eb2014-01-30 22:05:38 +00004660 // If we leave the immediate function, the lifetime isn't about to end.
4661 if (DR->refersToEnclosingLocal())
4662 return 0;
4663
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004664 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4665 // Check if it refers to itself, e.g. "int& i = i;".
4666 if (V == ParentDecl)
4667 return DR;
4668
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004669 if (V->hasLocalStorage()) {
4670 if (!V->getType()->isReferenceType())
4671 return DR;
4672
4673 // Reference variable, follow through to the expression that
4674 // it points to.
4675 if (V->hasInit()) {
4676 // Add the reference variable to the "trail".
4677 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004678 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004679 }
4680 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004681 }
Mike Stump11289f42009-09-09 15:08:12 +00004682
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004683 return NULL;
4684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004686 case Stmt::UnaryOperatorClass: {
4687 // The only unary operator that make sense to handle here
4688 // is Deref. All others don't resolve to a "name." This includes
4689 // handling all sorts of rvalues passed to a unary operator.
4690 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004691
John McCalle3027922010-08-25 11:45:40 +00004692 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004693 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004694
4695 return NULL;
4696 }
Mike Stump11289f42009-09-09 15:08:12 +00004697
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004698 case Stmt::ArraySubscriptExprClass: {
4699 // Array subscripts are potential references to data on the stack. We
4700 // retrieve the DeclRefExpr* for the array variable if it indeed
4701 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004702 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004705 case Stmt::ConditionalOperatorClass: {
4706 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004707 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004708 ConditionalOperator *C = cast<ConditionalOperator>(E);
4709
Anders Carlsson801c5c72007-11-30 19:04:31 +00004710 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004711 if (Expr *LHSExpr = C->getLHS()) {
4712 // In C++, we can have a throw-expression, which has 'void' type.
4713 if (!LHSExpr->getType()->isVoidType())
4714 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
4715 return LHS;
4716 }
4717
4718 // In C++, we can have a throw-expression, which has 'void' type.
4719 if (C->getRHS()->getType()->isVoidType())
4720 return 0;
Anders Carlsson801c5c72007-11-30 19:04:31 +00004721
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004722 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004723 }
Mike Stump11289f42009-09-09 15:08:12 +00004724
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004725 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004726 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004727 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004728
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004729 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004730 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004731 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004732
4733 // Check whether the member type is itself a reference, in which case
4734 // we're not going to refer to the member, but to what the member refers to.
4735 if (M->getMemberDecl()->getType()->isReferenceType())
4736 return NULL;
4737
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004738 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004739 }
Mike Stump11289f42009-09-09 15:08:12 +00004740
Douglas Gregorfe314812011-06-21 17:03:29 +00004741 case Stmt::MaterializeTemporaryExprClass:
4742 if (Expr *Result = EvalVal(
4743 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004744 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004745 return Result;
4746
4747 return E;
4748
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004749 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004750 // Check that we don't return or take the address of a reference to a
4751 // temporary. This is only useful in C++.
4752 if (!E->isTypeDependent() && E->isRValue())
4753 return E;
4754
4755 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004756 return NULL;
4757 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004758} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004759}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004760
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004761void
4762Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
4763 SourceLocation ReturnLoc,
4764 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00004765 const AttrVec *Attrs,
4766 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004767 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
4768
4769 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00004770 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
4771 CheckNonNullExpr(*this, RetValExp))
4772 Diag(ReturnLoc, diag::warn_null_ret)
4773 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00004774
4775 // C++11 [basic.stc.dynamic.allocation]p4:
4776 // If an allocation function declared with a non-throwing
4777 // exception-specification fails to allocate storage, it shall return
4778 // a null pointer. Any other allocation function that fails to allocate
4779 // storage shall indicate failure only by throwing an exception [...]
4780 if (FD) {
4781 OverloadedOperatorKind Op = FD->getOverloadedOperator();
4782 if (Op == OO_New || Op == OO_Array_New) {
4783 const FunctionProtoType *Proto
4784 = FD->getType()->castAs<FunctionProtoType>();
4785 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
4786 CheckNonNullExpr(*this, RetValExp))
4787 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
4788 << FD << getLangOpts().CPlusPlus11;
4789 }
4790 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00004791}
4792
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004793//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4794
4795/// Check for comparisons of floating point operands using != and ==.
4796/// Issue a warning if these are no self-comparisons, as they are not likely
4797/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004798void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004799 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4800 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004801
4802 // Special case: check for x == x (which is OK).
4803 // Do not emit warnings for such cases.
4804 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4805 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4806 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004807 return;
Mike Stump11289f42009-09-09 15:08:12 +00004808
4809
Ted Kremenekeda40e22007-11-29 00:59:04 +00004810 // Special case: check for comparisons against literals that can be exactly
4811 // represented by APFloat. In such cases, do not emit a warning. This
4812 // is a heuristic: often comparison against such literals are used to
4813 // detect if a value in a variable has not changed. This clearly can
4814 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004815 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4816 if (FLL->isExact())
4817 return;
4818 } else
4819 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4820 if (FLR->isExact())
4821 return;
Mike Stump11289f42009-09-09 15:08:12 +00004822
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004823 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004824 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004825 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004826 return;
Mike Stump11289f42009-09-09 15:08:12 +00004827
David Blaikie1f4ff152012-07-16 20:47:22 +00004828 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004829 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004830 return;
Mike Stump11289f42009-09-09 15:08:12 +00004831
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004832 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004833 Diag(Loc, diag::warn_floatingpoint_eq)
4834 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004835}
John McCallca01b222010-01-04 23:21:16 +00004836
John McCall70aa5392010-01-06 05:24:50 +00004837//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4838//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004839
John McCall70aa5392010-01-06 05:24:50 +00004840namespace {
John McCallca01b222010-01-04 23:21:16 +00004841
John McCall70aa5392010-01-06 05:24:50 +00004842/// Structure recording the 'active' range of an integer-valued
4843/// expression.
4844struct IntRange {
4845 /// The number of bits active in the int.
4846 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004847
John McCall70aa5392010-01-06 05:24:50 +00004848 /// True if the int is known not to have negative values.
4849 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004850
John McCall70aa5392010-01-06 05:24:50 +00004851 IntRange(unsigned Width, bool NonNegative)
4852 : Width(Width), NonNegative(NonNegative)
4853 {}
John McCallca01b222010-01-04 23:21:16 +00004854
John McCall817d4af2010-11-10 23:38:19 +00004855 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004856 static IntRange forBoolType() {
4857 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004858 }
4859
John McCall817d4af2010-11-10 23:38:19 +00004860 /// Returns the range of an opaque value of the given integral type.
4861 static IntRange forValueOfType(ASTContext &C, QualType T) {
4862 return forValueOfCanonicalType(C,
4863 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004864 }
4865
John McCall817d4af2010-11-10 23:38:19 +00004866 /// Returns the range of an opaque value of a canonical integral type.
4867 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004868 assert(T->isCanonicalUnqualified());
4869
4870 if (const VectorType *VT = dyn_cast<VectorType>(T))
4871 T = VT->getElementType().getTypePtr();
4872 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4873 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004874
David Majnemer6a426652013-06-07 22:07:20 +00004875 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004876 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004877 EnumDecl *Enum = ET->getDecl();
4878 if (!Enum->isCompleteDefinition())
4879 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004880
David Majnemer6a426652013-06-07 22:07:20 +00004881 unsigned NumPositive = Enum->getNumPositiveBits();
4882 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004883
David Majnemer6a426652013-06-07 22:07:20 +00004884 if (NumNegative == 0)
4885 return IntRange(NumPositive, true/*NonNegative*/);
4886 else
4887 return IntRange(std::max(NumPositive + 1, NumNegative),
4888 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004889 }
John McCall70aa5392010-01-06 05:24:50 +00004890
4891 const BuiltinType *BT = cast<BuiltinType>(T);
4892 assert(BT->isInteger());
4893
4894 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4895 }
4896
John McCall817d4af2010-11-10 23:38:19 +00004897 /// Returns the "target" range of a canonical integral type, i.e.
4898 /// the range of values expressible in the type.
4899 ///
4900 /// This matches forValueOfCanonicalType except that enums have the
4901 /// full range of their type, not the range of their enumerators.
4902 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4903 assert(T->isCanonicalUnqualified());
4904
4905 if (const VectorType *VT = dyn_cast<VectorType>(T))
4906 T = VT->getElementType().getTypePtr();
4907 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4908 T = CT->getElementType().getTypePtr();
4909 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004910 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004911
4912 const BuiltinType *BT = cast<BuiltinType>(T);
4913 assert(BT->isInteger());
4914
4915 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4916 }
4917
4918 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004919 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004920 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004921 L.NonNegative && R.NonNegative);
4922 }
4923
John McCall817d4af2010-11-10 23:38:19 +00004924 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004925 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004926 return IntRange(std::min(L.Width, R.Width),
4927 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004928 }
4929};
4930
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004931static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4932 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004933 if (value.isSigned() && value.isNegative())
4934 return IntRange(value.getMinSignedBits(), false);
4935
4936 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004937 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004938
4939 // isNonNegative() just checks the sign bit without considering
4940 // signedness.
4941 return IntRange(value.getActiveBits(), true);
4942}
4943
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004944static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4945 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004946 if (result.isInt())
4947 return GetValueRange(C, result.getInt(), MaxWidth);
4948
4949 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004950 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4951 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4952 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4953 R = IntRange::join(R, El);
4954 }
John McCall70aa5392010-01-06 05:24:50 +00004955 return R;
4956 }
4957
4958 if (result.isComplexInt()) {
4959 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4960 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4961 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004962 }
4963
4964 // This can happen with lossless casts to intptr_t of "based" lvalues.
4965 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004966 // FIXME: The only reason we need to pass the type in here is to get
4967 // the sign right on this one case. It would be nice if APValue
4968 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004969 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004970 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004971}
John McCall70aa5392010-01-06 05:24:50 +00004972
Eli Friedmane6d33952013-07-08 20:20:06 +00004973static QualType GetExprType(Expr *E) {
4974 QualType Ty = E->getType();
4975 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4976 Ty = AtomicRHS->getValueType();
4977 return Ty;
4978}
4979
John McCall70aa5392010-01-06 05:24:50 +00004980/// Pseudo-evaluate the given integer expression, estimating the
4981/// range of values it might take.
4982///
4983/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004984static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004985 E = E->IgnoreParens();
4986
4987 // Try a full evaluation first.
4988 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004989 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004990 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004991
4992 // I think we only want to look through implicit casts here; if the
4993 // user has an explicit widening cast, we should treat the value as
4994 // being of the new, wider type.
4995 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004996 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004997 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4998
Eli Friedmane6d33952013-07-08 20:20:06 +00004999 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005000
John McCalle3027922010-08-25 11:45:40 +00005001 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005002
John McCall70aa5392010-01-06 05:24:50 +00005003 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005004 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005005 return OutputTypeRange;
5006
5007 IntRange SubRange
5008 = GetExprRange(C, CE->getSubExpr(),
5009 std::min(MaxWidth, OutputTypeRange.Width));
5010
5011 // Bail out if the subexpr's range is as wide as the cast type.
5012 if (SubRange.Width >= OutputTypeRange.Width)
5013 return OutputTypeRange;
5014
5015 // Otherwise, we take the smaller width, and we're non-negative if
5016 // either the output type or the subexpr is.
5017 return IntRange(SubRange.Width,
5018 SubRange.NonNegative || OutputTypeRange.NonNegative);
5019 }
5020
5021 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5022 // If we can fold the condition, just take that operand.
5023 bool CondResult;
5024 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5025 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5026 : CO->getFalseExpr(),
5027 MaxWidth);
5028
5029 // Otherwise, conservatively merge.
5030 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5031 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5032 return IntRange::join(L, R);
5033 }
5034
5035 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5036 switch (BO->getOpcode()) {
5037
5038 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005039 case BO_LAnd:
5040 case BO_LOr:
5041 case BO_LT:
5042 case BO_GT:
5043 case BO_LE:
5044 case BO_GE:
5045 case BO_EQ:
5046 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005047 return IntRange::forBoolType();
5048
John McCallc3688382011-07-13 06:35:24 +00005049 // The type of the assignments is the type of the LHS, so the RHS
5050 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005051 case BO_MulAssign:
5052 case BO_DivAssign:
5053 case BO_RemAssign:
5054 case BO_AddAssign:
5055 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005056 case BO_XorAssign:
5057 case BO_OrAssign:
5058 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005059 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005060
John McCallc3688382011-07-13 06:35:24 +00005061 // Simple assignments just pass through the RHS, which will have
5062 // been coerced to the LHS type.
5063 case BO_Assign:
5064 // TODO: bitfields?
5065 return GetExprRange(C, BO->getRHS(), MaxWidth);
5066
John McCall70aa5392010-01-06 05:24:50 +00005067 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005068 case BO_PtrMemD:
5069 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005070 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005071
John McCall2ce81ad2010-01-06 22:07:33 +00005072 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005073 case BO_And:
5074 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005075 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5076 GetExprRange(C, BO->getRHS(), MaxWidth));
5077
John McCall70aa5392010-01-06 05:24:50 +00005078 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005079 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005080 // ...except that we want to treat '1 << (blah)' as logically
5081 // positive. It's an important idiom.
5082 if (IntegerLiteral *I
5083 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5084 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005085 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005086 return IntRange(R.Width, /*NonNegative*/ true);
5087 }
5088 }
5089 // fallthrough
5090
John McCalle3027922010-08-25 11:45:40 +00005091 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005092 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005093
John McCall2ce81ad2010-01-06 22:07:33 +00005094 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005095 case BO_Shr:
5096 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005097 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5098
5099 // If the shift amount is a positive constant, drop the width by
5100 // that much.
5101 llvm::APSInt shift;
5102 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5103 shift.isNonNegative()) {
5104 unsigned zext = shift.getZExtValue();
5105 if (zext >= L.Width)
5106 L.Width = (L.NonNegative ? 0 : 1);
5107 else
5108 L.Width -= zext;
5109 }
5110
5111 return L;
5112 }
5113
5114 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005115 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005116 return GetExprRange(C, BO->getRHS(), MaxWidth);
5117
John McCall2ce81ad2010-01-06 22:07:33 +00005118 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005119 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005120 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005121 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005122 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005123
John McCall51431812011-07-14 22:39:48 +00005124 // The width of a division result is mostly determined by the size
5125 // of the LHS.
5126 case BO_Div: {
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
5131 // If the divisor is constant, use that.
5132 llvm::APSInt divisor;
5133 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5134 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5135 if (log2 >= L.Width)
5136 L.Width = (L.NonNegative ? 0 : 1);
5137 else
5138 L.Width = std::min(L.Width - log2, MaxWidth);
5139 return L;
5140 }
5141
5142 // Otherwise, just use the LHS's width.
5143 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5144 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5145 }
5146
5147 // The result of a remainder can't be larger than the result of
5148 // either side.
5149 case BO_Rem: {
5150 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005151 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005152 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5153 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5154
5155 IntRange meet = IntRange::meet(L, R);
5156 meet.Width = std::min(meet.Width, MaxWidth);
5157 return meet;
5158 }
5159
5160 // The default behavior is okay for these.
5161 case BO_Mul:
5162 case BO_Add:
5163 case BO_Xor:
5164 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005165 break;
5166 }
5167
John McCall51431812011-07-14 22:39:48 +00005168 // The default case is to treat the operation as if it were closed
5169 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005170 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5171 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5172 return IntRange::join(L, R);
5173 }
5174
5175 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5176 switch (UO->getOpcode()) {
5177 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005178 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005179 return IntRange::forBoolType();
5180
5181 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005182 case UO_Deref:
5183 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005184 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005185
5186 default:
5187 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5188 }
5189 }
5190
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005191 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5192 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5193
John McCalld25db7e2013-05-06 21:39:12 +00005194 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005195 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005196 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005197
Eli Friedmane6d33952013-07-08 20:20:06 +00005198 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005199}
John McCall263a48b2010-01-04 23:31:57 +00005200
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005201static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005202 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005203}
5204
John McCall263a48b2010-01-04 23:31:57 +00005205/// Checks whether the given value, which currently has the given
5206/// source semantics, has the same value when coerced through the
5207/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005208static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5209 const llvm::fltSemantics &Src,
5210 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005211 llvm::APFloat truncated = value;
5212
5213 bool ignored;
5214 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5215 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5216
5217 return truncated.bitwiseIsEqual(value);
5218}
5219
5220/// Checks whether the given value, which currently has the given
5221/// source semantics, has the same value when coerced through the
5222/// target semantics.
5223///
5224/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005225static bool IsSameFloatAfterCast(const APValue &value,
5226 const llvm::fltSemantics &Src,
5227 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005228 if (value.isFloat())
5229 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5230
5231 if (value.isVector()) {
5232 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5233 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5234 return false;
5235 return true;
5236 }
5237
5238 assert(value.isComplexFloat());
5239 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5240 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5241}
5242
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005243static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005244
Ted Kremenek6274be42010-09-23 21:43:44 +00005245static bool IsZero(Sema &S, Expr *E) {
5246 // Suppress cases where we are comparing against an enum constant.
5247 if (const DeclRefExpr *DR =
5248 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5249 if (isa<EnumConstantDecl>(DR->getDecl()))
5250 return false;
5251
5252 // Suppress cases where the '0' value is expanded from a macro.
5253 if (E->getLocStart().isMacroID())
5254 return false;
5255
John McCallcc7e5bf2010-05-06 08:58:33 +00005256 llvm::APSInt Value;
5257 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5258}
5259
John McCall2551c1b2010-10-06 00:25:24 +00005260static bool HasEnumType(Expr *E) {
5261 // Strip off implicit integral promotions.
5262 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005263 if (ICE->getCastKind() != CK_IntegralCast &&
5264 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005265 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005266 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005267 }
5268
5269 return E->getType()->isEnumeralType();
5270}
5271
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005272static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005273 // Disable warning in template instantiations.
5274 if (!S.ActiveTemplateInstantiations.empty())
5275 return;
5276
John McCalle3027922010-08-25 11:45:40 +00005277 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005278 if (E->isValueDependent())
5279 return;
5280
John McCalle3027922010-08-25 11:45:40 +00005281 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005282 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005283 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005284 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005285 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005286 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005287 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005288 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005289 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005290 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005291 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005292 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005293 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005294 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005295 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005296 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5297 }
5298}
5299
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005300static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005301 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005302 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005303 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005304 // Disable warning in template instantiations.
5305 if (!S.ActiveTemplateInstantiations.empty())
5306 return;
5307
Richard Trieu560910c2012-11-14 22:50:24 +00005308 // 0 values are handled later by CheckTrivialUnsignedComparison().
5309 if (Value == 0)
5310 return;
5311
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005312 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005313 QualType OtherT = Other->getType();
5314 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005315 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005316 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005317 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005318 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005319 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00005320
5321 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00005322 bool CommonSigned = CommonT->isSignedIntegerType();
5323
5324 bool EqualityOnly = false;
5325
5326 // TODO: Investigate using GetExprRange() to get tighter bounds on
5327 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005328 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00005329 unsigned OtherWidth = OtherRange.Width;
5330
5331 if (CommonSigned) {
5332 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00005333 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005334 // Check that the constant is representable in type OtherT.
5335 if (ConstantSigned) {
5336 if (OtherWidth >= Value.getMinSignedBits())
5337 return;
5338 } else { // !ConstantSigned
5339 if (OtherWidth >= Value.getActiveBits() + 1)
5340 return;
5341 }
5342 } else { // !OtherSigned
5343 // Check that the constant is representable in type OtherT.
5344 // Negative values are out of range.
5345 if (ConstantSigned) {
5346 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5347 return;
5348 } else { // !ConstantSigned
5349 if (OtherWidth >= Value.getActiveBits())
5350 return;
5351 }
5352 }
5353 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00005354 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00005355 if (OtherWidth >= Value.getActiveBits())
5356 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00005357 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00005358 // Check to see if the constant is representable in OtherT.
5359 if (OtherWidth > Value.getActiveBits())
5360 return;
5361 // Check to see if the constant is equivalent to a negative value
5362 // cast to CommonT.
5363 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00005364 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00005365 return;
5366 // The constant value rests between values that OtherT can represent after
5367 // conversion. Relational comparison still works, but equality
5368 // comparisons will be tautological.
5369 EqualityOnly = true;
5370 } else { // OtherSigned && ConstantSigned
5371 assert(0 && "Two signed types converted to unsigned types.");
5372 }
5373 }
5374
5375 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
5376
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005377 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005378 if (op == BO_EQ || op == BO_NE) {
5379 IsTrue = op == BO_NE;
5380 } else if (EqualityOnly) {
5381 return;
5382 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005383 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00005384 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005385 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00005386 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005387 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005388 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00005389 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005390 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00005391 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005392 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005393
5394 // If this is a comparison to an enum constant, include that
5395 // constant in the diagnostic.
5396 const EnumConstantDecl *ED = 0;
5397 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
5398 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
5399
5400 SmallString<64> PrettySourceValue;
5401 llvm::raw_svector_ostream OS(PrettySourceValue);
5402 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00005403 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00005404 else
5405 OS << Value;
5406
Richard Trieuc38786b2014-01-10 04:38:09 +00005407 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5408 S.PDiag(diag::warn_out_of_range_compare)
5409 << OS.str() << OtherT << IsTrue
5410 << E->getLHS()->getSourceRange()
5411 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005412}
5413
John McCallcc7e5bf2010-05-06 08:58:33 +00005414/// Analyze the operands of the given comparison. Implements the
5415/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005416static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00005417 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5418 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005419}
John McCall263a48b2010-01-04 23:31:57 +00005420
John McCallca01b222010-01-04 23:21:16 +00005421/// \brief Implements -Wsign-compare.
5422///
Richard Trieu82402a02011-09-15 21:56:47 +00005423/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005424static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005425 // The type the comparison is being performed in.
5426 QualType T = E->getLHS()->getType();
5427 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5428 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005429 if (E->isValueDependent())
5430 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005431
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005432 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5433 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005434
5435 bool IsComparisonConstant = false;
5436
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005437 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005438 // of 'true' or 'false'.
5439 if (T->isIntegralType(S.Context)) {
5440 llvm::APSInt RHSValue;
5441 bool IsRHSIntegralLiteral =
5442 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5443 llvm::APSInt LHSValue;
5444 bool IsLHSIntegralLiteral =
5445 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5446 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5447 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5448 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5449 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5450 else
5451 IsComparisonConstant =
5452 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005453 } else if (!T->hasUnsignedIntegerRepresentation())
5454 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005455
John McCallcc7e5bf2010-05-06 08:58:33 +00005456 // We don't do anything special if this isn't an unsigned integral
5457 // comparison: we're only interested in integral comparisons, and
5458 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005459 //
5460 // We also don't care about value-dependent expressions or expressions
5461 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005462 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005463 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005464
John McCallcc7e5bf2010-05-06 08:58:33 +00005465 // Check to see if one of the (unmodified) operands is of different
5466 // signedness.
5467 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005468 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5469 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005470 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005471 signedOperand = LHS;
5472 unsignedOperand = RHS;
5473 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5474 signedOperand = RHS;
5475 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005476 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005477 CheckTrivialUnsignedComparison(S, E);
5478 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005479 }
5480
John McCallcc7e5bf2010-05-06 08:58:33 +00005481 // Otherwise, calculate the effective range of the signed operand.
5482 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005483
John McCallcc7e5bf2010-05-06 08:58:33 +00005484 // Go ahead and analyze implicit conversions in the operands. Note
5485 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005486 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5487 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005488
John McCallcc7e5bf2010-05-06 08:58:33 +00005489 // If the signed range is non-negative, -Wsign-compare won't fire,
5490 // but we should still check for comparisons which are always true
5491 // or false.
5492 if (signedRange.NonNegative)
5493 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005494
5495 // For (in)equality comparisons, if the unsigned operand is a
5496 // constant which cannot collide with a overflowed signed operand,
5497 // then reinterpreting the signed operand as unsigned will not
5498 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005499 if (E->isEqualityOp()) {
5500 unsigned comparisonWidth = S.Context.getIntWidth(T);
5501 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005502
John McCallcc7e5bf2010-05-06 08:58:33 +00005503 // We should never be unable to prove that the unsigned operand is
5504 // non-negative.
5505 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5506
5507 if (unsignedRange.Width < comparisonWidth)
5508 return;
5509 }
5510
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005511 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5512 S.PDiag(diag::warn_mixed_sign_comparison)
5513 << LHS->getType() << RHS->getType()
5514 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005515}
5516
John McCall1f425642010-11-11 03:21:53 +00005517/// Analyzes an attempt to assign the given value to a bitfield.
5518///
5519/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005520static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5521 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005522 assert(Bitfield->isBitField());
5523 if (Bitfield->isInvalidDecl())
5524 return false;
5525
John McCalldeebbcf2010-11-11 05:33:51 +00005526 // White-list bool bitfields.
5527 if (Bitfield->getType()->isBooleanType())
5528 return false;
5529
Douglas Gregor789adec2011-02-04 13:09:01 +00005530 // Ignore value- or type-dependent expressions.
5531 if (Bitfield->getBitWidth()->isValueDependent() ||
5532 Bitfield->getBitWidth()->isTypeDependent() ||
5533 Init->isValueDependent() ||
5534 Init->isTypeDependent())
5535 return false;
5536
John McCall1f425642010-11-11 03:21:53 +00005537 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5538
Richard Smith5fab0c92011-12-28 19:48:30 +00005539 llvm::APSInt Value;
5540 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005541 return false;
5542
John McCall1f425642010-11-11 03:21:53 +00005543 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005544 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005545
5546 if (OriginalWidth <= FieldWidth)
5547 return false;
5548
Eli Friedmanc267a322012-01-26 23:11:39 +00005549 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005550 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005551 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005552
Eli Friedmanc267a322012-01-26 23:11:39 +00005553 // Check whether the stored value is equal to the original value.
5554 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005555 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005556 return false;
5557
Eli Friedmanc267a322012-01-26 23:11:39 +00005558 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005559 // therefore don't strictly fit into a signed bitfield of width 1.
5560 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005561 return false;
5562
John McCall1f425642010-11-11 03:21:53 +00005563 std::string PrettyValue = Value.toString(10);
5564 std::string PrettyTrunc = TruncatedValue.toString(10);
5565
5566 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5567 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5568 << Init->getSourceRange();
5569
5570 return true;
5571}
5572
John McCalld2a53122010-11-09 23:24:47 +00005573/// Analyze the given simple or compound assignment for warning-worthy
5574/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005575static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005576 // Just recurse on the LHS.
5577 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5578
5579 // We want to recurse on the RHS as normal unless we're assigning to
5580 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005581 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005582 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005583 E->getOperatorLoc())) {
5584 // Recurse, ignoring any implicit conversions on the RHS.
5585 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5586 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005587 }
5588 }
5589
5590 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5591}
5592
John McCall263a48b2010-01-04 23:31:57 +00005593/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005594static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005595 SourceLocation CContext, unsigned diag,
5596 bool pruneControlFlow = false) {
5597 if (pruneControlFlow) {
5598 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5599 S.PDiag(diag)
5600 << SourceType << T << E->getSourceRange()
5601 << SourceRange(CContext));
5602 return;
5603 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005604 S.Diag(E->getExprLoc(), diag)
5605 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5606}
5607
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005608/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005609static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005610 SourceLocation CContext, unsigned diag,
5611 bool pruneControlFlow = false) {
5612 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005613}
5614
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005615/// Diagnose an implicit cast from a literal expression. Does not warn when the
5616/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005617void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5618 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005619 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005620 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005621 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005622 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5623 T->hasUnsignedIntegerRepresentation());
5624 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005625 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005626 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005627 return;
5628
Eli Friedman07185912013-08-29 23:44:43 +00005629 // FIXME: Force the precision of the source value down so we don't print
5630 // digits which are usually useless (we don't really care here if we
5631 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5632 // would automatically print the shortest representation, but it's a bit
5633 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005634 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005635 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5636 precision = (precision * 59 + 195) / 196;
5637 Value.toString(PrettySourceValue, precision);
5638
David Blaikie9b88cc02012-05-15 17:18:27 +00005639 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005640 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5641 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5642 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005643 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005644
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005645 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005646 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5647 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005648}
5649
John McCall18a2c2c2010-11-09 22:22:12 +00005650std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5651 if (!Range.Width) return "0";
5652
5653 llvm::APSInt ValueInRange = Value;
5654 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005655 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005656 return ValueInRange.toString(10);
5657}
5658
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005659static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5660 if (!isa<ImplicitCastExpr>(Ex))
5661 return false;
5662
5663 Expr *InnerE = Ex->IgnoreParenImpCasts();
5664 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5665 const Type *Source =
5666 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5667 if (Target->isDependentType())
5668 return false;
5669
5670 const BuiltinType *FloatCandidateBT =
5671 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5672 const Type *BoolCandidateType = ToBool ? Target : Source;
5673
5674 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5675 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5676}
5677
5678void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5679 SourceLocation CC) {
5680 unsigned NumArgs = TheCall->getNumArgs();
5681 for (unsigned i = 0; i < NumArgs; ++i) {
5682 Expr *CurrA = TheCall->getArg(i);
5683 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5684 continue;
5685
5686 bool IsSwapped = ((i > 0) &&
5687 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5688 IsSwapped |= ((i < (NumArgs - 1)) &&
5689 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5690 if (IsSwapped) {
5691 // Warn on this floating-point to bool conversion.
5692 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5693 CurrA->getType(), CC,
5694 diag::warn_impcast_floating_point_to_bool);
5695 }
5696 }
5697}
5698
John McCallcc7e5bf2010-05-06 08:58:33 +00005699void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005700 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005701 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005702
John McCallcc7e5bf2010-05-06 08:58:33 +00005703 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5704 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5705 if (Source == Target) return;
5706 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005707
Chandler Carruthc22845a2011-07-26 05:40:03 +00005708 // If the conversion context location is invalid don't complain. We also
5709 // don't want to emit a warning if the issue occurs from the expansion of
5710 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5711 // delay this check as long as possible. Once we detect we are in that
5712 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005713 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005714 return;
5715
Richard Trieu021baa32011-09-23 20:10:00 +00005716 // Diagnose implicit casts to bool.
5717 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5718 if (isa<StringLiteral>(E))
5719 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00005720 // and expressions, for instance, assert(0 && "error here"), are
5721 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00005722 return DiagnoseImpCast(S, E, T, CC,
5723 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00005724 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
5725 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
5726 // This covers the literal expressions that evaluate to Objective-C
5727 // objects.
5728 return DiagnoseImpCast(S, E, T, CC,
5729 diag::warn_impcast_objective_c_literal_to_bool);
5730 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00005731 if (Source->isPointerType() || Source->canDecayToPointerType()) {
5732 // Warn on pointer to bool conversion that is always true.
5733 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
5734 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00005735 }
Richard Trieu021baa32011-09-23 20:10:00 +00005736 }
John McCall263a48b2010-01-04 23:31:57 +00005737
5738 // Strip vector types.
5739 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005740 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005741 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005742 return;
John McCallacf0ee52010-10-08 02:01:28 +00005743 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005744 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005745
5746 // If the vector cast is cast between two vectors of the same size, it is
5747 // a bitcast, not a conversion.
5748 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5749 return;
John McCall263a48b2010-01-04 23:31:57 +00005750
5751 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5752 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5753 }
5754
5755 // Strip complex types.
5756 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005757 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005758 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005759 return;
5760
John McCallacf0ee52010-10-08 02:01:28 +00005761 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005762 }
John McCall263a48b2010-01-04 23:31:57 +00005763
5764 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5765 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5766 }
5767
5768 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5769 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5770
5771 // If the source is floating point...
5772 if (SourceBT && SourceBT->isFloatingPoint()) {
5773 // ...and the target is floating point...
5774 if (TargetBT && TargetBT->isFloatingPoint()) {
5775 // ...then warn if we're dropping FP rank.
5776
5777 // Builtin FP kinds are ordered by increasing FP rank.
5778 if (SourceBT->getKind() > TargetBT->getKind()) {
5779 // Don't warn about float constants that are precisely
5780 // representable in the target type.
5781 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005782 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005783 // Value might be a float, a float vector, or a float complex.
5784 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005785 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5786 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005787 return;
5788 }
5789
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005790 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005791 return;
5792
John McCallacf0ee52010-10-08 02:01:28 +00005793 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005794 }
5795 return;
5796 }
5797
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005798 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005799 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005800 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005801 return;
5802
Chandler Carruth22c7a792011-02-17 11:05:49 +00005803 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005804 // We also want to warn on, e.g., "int i = -1.234"
5805 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5806 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5807 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5808
Chandler Carruth016ef402011-04-10 08:36:24 +00005809 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5810 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005811 } else {
5812 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5813 }
5814 }
John McCall263a48b2010-01-04 23:31:57 +00005815
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005816 // If the target is bool, warn if expr is a function or method call.
5817 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5818 isa<CallExpr>(E)) {
5819 // Check last argument of function call to see if it is an
5820 // implicit cast from a type matching the type the result
5821 // is being cast to.
5822 CallExpr *CEx = cast<CallExpr>(E);
5823 unsigned NumArgs = CEx->getNumArgs();
5824 if (NumArgs > 0) {
5825 Expr *LastA = CEx->getArg(NumArgs - 1);
5826 Expr *InnerE = LastA->IgnoreParenImpCasts();
5827 const Type *InnerType =
5828 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5829 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5830 // Warn on this floating-point to bool conversion
5831 DiagnoseImpCast(S, E, T, CC,
5832 diag::warn_impcast_floating_point_to_bool);
5833 }
5834 }
5835 }
John McCall263a48b2010-01-04 23:31:57 +00005836 return;
5837 }
5838
Richard Trieubeaf3452011-05-29 19:59:02 +00005839 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005840 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005841 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005842 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005843 SourceLocation Loc = E->getSourceRange().getBegin();
5844 if (Loc.isMacroID())
5845 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005846 if (!Loc.isMacroID() || CC.isMacroID())
5847 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5848 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005849 << FixItHint::CreateReplacement(Loc,
5850 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005851 }
5852
David Blaikie9366d2b2012-06-19 21:19:06 +00005853 if (!Source->isIntegerType() || !Target->isIntegerType())
5854 return;
5855
David Blaikie7555b6a2012-05-15 16:56:36 +00005856 // TODO: remove this early return once the false positives for constant->bool
5857 // in templates, macros, etc, are reduced or removed.
5858 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5859 return;
5860
John McCallcc7e5bf2010-05-06 08:58:33 +00005861 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005862 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005863
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005864 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005865 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005866 // TODO: this should happen for bitfield stores, too.
5867 llvm::APSInt Value(32);
5868 if (E->isIntegerConstantExpr(Value, S.Context)) {
5869 if (S.SourceMgr.isInSystemMacro(CC))
5870 return;
5871
John McCall18a2c2c2010-11-09 22:22:12 +00005872 std::string PrettySourceValue = Value.toString(10);
5873 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005874
Ted Kremenek33ba9952011-10-22 02:37:33 +00005875 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5876 S.PDiag(diag::warn_impcast_integer_precision_constant)
5877 << PrettySourceValue << PrettyTargetValue
5878 << E->getType() << T << E->getSourceRange()
5879 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005880 return;
5881 }
5882
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005883 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5884 if (S.SourceMgr.isInSystemMacro(CC))
5885 return;
5886
David Blaikie9455da02012-04-12 22:40:54 +00005887 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005888 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5889 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005890 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005891 }
5892
5893 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5894 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5895 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005896
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005897 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005898 return;
5899
John McCallcc7e5bf2010-05-06 08:58:33 +00005900 unsigned DiagID = diag::warn_impcast_integer_sign;
5901
5902 // Traditionally, gcc has warned about this under -Wsign-compare.
5903 // We also want to warn about it in -Wconversion.
5904 // So if -Wconversion is off, use a completely identical diagnostic
5905 // in the sign-compare group.
5906 // The conditional-checking code will
5907 if (ICContext) {
5908 DiagID = diag::warn_impcast_integer_sign_conditional;
5909 *ICContext = true;
5910 }
5911
John McCallacf0ee52010-10-08 02:01:28 +00005912 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005913 }
5914
Douglas Gregora78f1932011-02-22 02:45:07 +00005915 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005916 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5917 // type, to give us better diagnostics.
5918 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005919 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005920 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5921 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5922 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5923 SourceType = S.Context.getTypeDeclType(Enum);
5924 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5925 }
5926 }
5927
Douglas Gregora78f1932011-02-22 02:45:07 +00005928 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5929 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005930 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5931 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005932 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005933 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005934 return;
5935
Douglas Gregor364f7db2011-03-12 00:14:31 +00005936 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005937 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005938 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005939
John McCall263a48b2010-01-04 23:31:57 +00005940 return;
5941}
5942
David Blaikie18e9ac72012-05-15 21:57:38 +00005943void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5944 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005945
5946void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005947 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005948 E = E->IgnoreParenImpCasts();
5949
5950 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005951 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005952
John McCallacf0ee52010-10-08 02:01:28 +00005953 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005954 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005955 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005956 return;
5957}
5958
David Blaikie18e9ac72012-05-15 21:57:38 +00005959void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5960 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005961 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005962
5963 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005964 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5965 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005966
5967 // If -Wconversion would have warned about either of the candidates
5968 // for a signedness conversion to the context type...
5969 if (!Suspicious) return;
5970
5971 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005972 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5973 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005974 return;
5975
John McCallcc7e5bf2010-05-06 08:58:33 +00005976 // ...then check whether it would have warned about either of the
5977 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005978 if (E->getType() == T) return;
5979
5980 Suspicious = false;
5981 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5982 E->getType(), CC, &Suspicious);
5983 if (!Suspicious)
5984 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005985 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005986}
5987
5988/// AnalyzeImplicitConversions - Find and report any interesting
5989/// implicit conversions in the given expression. There are a couple
5990/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005991void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005992 QualType T = OrigE->getType();
5993 Expr *E = OrigE->IgnoreParenImpCasts();
5994
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005995 if (E->isTypeDependent() || E->isValueDependent())
5996 return;
5997
John McCallcc7e5bf2010-05-06 08:58:33 +00005998 // For conditional operators, we analyze the arguments as if they
5999 // were being fed directly into the output.
6000 if (isa<ConditionalOperator>(E)) {
6001 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006002 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006003 return;
6004 }
6005
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006006 // Check implicit argument conversions for function calls.
6007 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6008 CheckImplicitArgumentConversions(S, Call, CC);
6009
John McCallcc7e5bf2010-05-06 08:58:33 +00006010 // Go ahead and check any implicit conversions we might have skipped.
6011 // The non-canonical typecheck is just an optimization;
6012 // CheckImplicitConversion will filter out dead implicit conversions.
6013 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006014 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006015
6016 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006017
6018 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006019 if (POE->getResultExpr())
6020 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006021 }
6022
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006023 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6024 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6025
John McCallcc7e5bf2010-05-06 08:58:33 +00006026 // Skip past explicit casts.
6027 if (isa<ExplicitCastExpr>(E)) {
6028 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006029 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006030 }
6031
John McCalld2a53122010-11-09 23:24:47 +00006032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6033 // Do a somewhat different check with comparison operators.
6034 if (BO->isComparisonOp())
6035 return AnalyzeComparison(S, BO);
6036
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006037 // And with simple assignments.
6038 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006039 return AnalyzeAssignment(S, BO);
6040 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006041
6042 // These break the otherwise-useful invariant below. Fortunately,
6043 // we don't really need to recurse into them, because any internal
6044 // expressions should have been analyzed already when they were
6045 // built into statements.
6046 if (isa<StmtExpr>(E)) return;
6047
6048 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006049 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006050
6051 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006052 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006053 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006054 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006055 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006056 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006057 if (!ChildExpr)
6058 continue;
6059
Richard Trieu955231d2014-01-25 01:10:35 +00006060 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006061 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006062 // Ignore checking string literals that are in logical and operators.
6063 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006064 continue;
6065 AnalyzeImplicitConversions(S, ChildExpr, CC);
6066 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006067}
6068
6069} // end anonymous namespace
6070
Richard Trieu3bb8b562014-02-26 02:36:06 +00006071enum {
6072 AddressOf,
6073 FunctionPointer,
6074 ArrayPointer
6075};
6076
6077/// \brief Diagnose pointers that are always non-null.
6078/// \param E the expression containing the pointer
6079/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6080/// compared to a null pointer
6081/// \param IsEqual True when the comparison is equal to a null pointer
6082/// \param Range Extra SourceRange to highlight in the diagnostic
6083void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6084 Expr::NullPointerConstantKind NullKind,
6085 bool IsEqual, SourceRange Range) {
6086
6087 // Don't warn inside macros.
6088 if (E->getExprLoc().isMacroID())
6089 return;
6090 E = E->IgnoreImpCasts();
6091
6092 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6093
6094 bool IsAddressOf = false;
6095
6096 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6097 if (UO->getOpcode() != UO_AddrOf)
6098 return;
6099 IsAddressOf = true;
6100 E = UO->getSubExpr();
6101 }
6102
6103 // Expect to find a single Decl. Skip anything more complicated.
6104 ValueDecl *D = 0;
6105 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6106 D = R->getDecl();
6107 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6108 D = M->getMemberDecl();
6109 }
6110
6111 // Weak Decls can be null.
6112 if (!D || D->isWeak())
6113 return;
6114
6115 QualType T = D->getType();
6116 const bool IsArray = T->isArrayType();
6117 const bool IsFunction = T->isFunctionType();
6118
6119 if (IsAddressOf) {
6120 // Address of function is used to silence the function warning.
6121 if (IsFunction)
6122 return;
6123 // Address of reference can be null.
6124 if (T->isReferenceType())
6125 return;
6126 }
6127
6128 // Found nothing.
6129 if (!IsAddressOf && !IsFunction && !IsArray)
6130 return;
6131
6132 // Pretty print the expression for the diagnostic.
6133 std::string Str;
6134 llvm::raw_string_ostream S(Str);
6135 E->printPretty(S, 0, getPrintingPolicy());
6136
6137 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
6138 : diag::warn_impcast_pointer_to_bool;
6139 unsigned DiagType;
6140 if (IsAddressOf)
6141 DiagType = AddressOf;
6142 else if (IsFunction)
6143 DiagType = FunctionPointer;
6144 else if (IsArray)
6145 DiagType = ArrayPointer;
6146 else
6147 llvm_unreachable("Could not determine diagnostic.");
6148 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
6149 << Range << IsEqual;
6150
6151 if (!IsFunction)
6152 return;
6153
6154 // Suggest '&' to silence the function warning.
6155 Diag(E->getExprLoc(), diag::note_function_warning_silence)
6156 << FixItHint::CreateInsertion(E->getLocStart(), "&");
6157
6158 // Check to see if '()' fixit should be emitted.
6159 QualType ReturnType;
6160 UnresolvedSet<4> NonTemplateOverloads;
6161 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
6162 if (ReturnType.isNull())
6163 return;
6164
6165 if (IsCompare) {
6166 // There are two cases here. If there is null constant, the only suggest
6167 // for a pointer return type. If the null is 0, then suggest if the return
6168 // type is a pointer or an integer type.
6169 if (!ReturnType->isPointerType()) {
6170 if (NullKind == Expr::NPCK_ZeroExpression ||
6171 NullKind == Expr::NPCK_ZeroLiteral) {
6172 if (!ReturnType->isIntegerType())
6173 return;
6174 } else {
6175 return;
6176 }
6177 }
6178 } else { // !IsCompare
6179 // For function to bool, only suggest if the function pointer has bool
6180 // return type.
6181 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
6182 return;
6183 }
6184 Diag(E->getExprLoc(), diag::note_function_to_function_call)
6185 << FixItHint::CreateInsertion(
6186 getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
6187}
6188
6189
John McCallcc7e5bf2010-05-06 08:58:33 +00006190/// Diagnoses "dangerous" implicit conversions within the given
6191/// expression (which is a full expression). Implements -Wconversion
6192/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006193///
6194/// \param CC the "context" location of the implicit conversion, i.e.
6195/// the most location of the syntactic entity requiring the implicit
6196/// conversion
6197void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006198 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00006199 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00006200 return;
6201
6202 // Don't diagnose for value- or type-dependent expressions.
6203 if (E->isTypeDependent() || E->isValueDependent())
6204 return;
6205
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006206 // Check for array bounds violations in cases where the check isn't triggered
6207 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
6208 // ArraySubscriptExpr is on the RHS of a variable initialization.
6209 CheckArrayAccess(E);
6210
John McCallacf0ee52010-10-08 02:01:28 +00006211 // This is not the right CC for (e.g.) a variable initialization.
6212 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006213}
6214
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006215/// Diagnose when expression is an integer constant expression and its evaluation
6216/// results in integer overflow
6217void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00006218 if (isa<BinaryOperator>(E->IgnoreParens()))
6219 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006220}
6221
Richard Smithc406cb72013-01-17 01:17:56 +00006222namespace {
6223/// \brief Visitor for expressions which looks for unsequenced operations on the
6224/// same object.
6225class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006226 typedef EvaluatedExprVisitor<SequenceChecker> Base;
6227
Richard Smithc406cb72013-01-17 01:17:56 +00006228 /// \brief A tree of sequenced regions within an expression. Two regions are
6229 /// unsequenced if one is an ancestor or a descendent of the other. When we
6230 /// finish processing an expression with sequencing, such as a comma
6231 /// expression, we fold its tree nodes into its parent, since they are
6232 /// unsequenced with respect to nodes we will visit later.
6233 class SequenceTree {
6234 struct Value {
6235 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
6236 unsigned Parent : 31;
6237 bool Merged : 1;
6238 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006239 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00006240
6241 public:
6242 /// \brief A region within an expression which may be sequenced with respect
6243 /// to some other region.
6244 class Seq {
6245 explicit Seq(unsigned N) : Index(N) {}
6246 unsigned Index;
6247 friend class SequenceTree;
6248 public:
6249 Seq() : Index(0) {}
6250 };
6251
6252 SequenceTree() { Values.push_back(Value(0)); }
6253 Seq root() const { return Seq(0); }
6254
6255 /// \brief Create a new sequence of operations, which is an unsequenced
6256 /// subset of \p Parent. This sequence of operations is sequenced with
6257 /// respect to other children of \p Parent.
6258 Seq allocate(Seq Parent) {
6259 Values.push_back(Value(Parent.Index));
6260 return Seq(Values.size() - 1);
6261 }
6262
6263 /// \brief Merge a sequence of operations into its parent.
6264 void merge(Seq S) {
6265 Values[S.Index].Merged = true;
6266 }
6267
6268 /// \brief Determine whether two operations are unsequenced. This operation
6269 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
6270 /// should have been merged into its parent as appropriate.
6271 bool isUnsequenced(Seq Cur, Seq Old) {
6272 unsigned C = representative(Cur.Index);
6273 unsigned Target = representative(Old.Index);
6274 while (C >= Target) {
6275 if (C == Target)
6276 return true;
6277 C = Values[C].Parent;
6278 }
6279 return false;
6280 }
6281
6282 private:
6283 /// \brief Pick a representative for a sequence.
6284 unsigned representative(unsigned K) {
6285 if (Values[K].Merged)
6286 // Perform path compression as we go.
6287 return Values[K].Parent = representative(Values[K].Parent);
6288 return K;
6289 }
6290 };
6291
6292 /// An object for which we can track unsequenced uses.
6293 typedef NamedDecl *Object;
6294
6295 /// Different flavors of object usage which we track. We only track the
6296 /// least-sequenced usage of each kind.
6297 enum UsageKind {
6298 /// A read of an object. Multiple unsequenced reads are OK.
6299 UK_Use,
6300 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00006301 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00006302 UK_ModAsValue,
6303 /// A modification of an object which is not sequenced before the value
6304 /// computation of the expression, such as n++.
6305 UK_ModAsSideEffect,
6306
6307 UK_Count = UK_ModAsSideEffect + 1
6308 };
6309
6310 struct Usage {
6311 Usage() : Use(0), Seq() {}
6312 Expr *Use;
6313 SequenceTree::Seq Seq;
6314 };
6315
6316 struct UsageInfo {
6317 UsageInfo() : Diagnosed(false) {}
6318 Usage Uses[UK_Count];
6319 /// Have we issued a diagnostic for this variable already?
6320 bool Diagnosed;
6321 };
6322 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
6323
6324 Sema &SemaRef;
6325 /// Sequenced regions within the expression.
6326 SequenceTree Tree;
6327 /// Declaration modifications and references which we have seen.
6328 UsageInfoMap UsageMap;
6329 /// The region we are currently within.
6330 SequenceTree::Seq Region;
6331 /// Filled in with declarations which were modified as a side-effect
6332 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006333 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00006334 /// Expressions to check later. We defer checking these to reduce
6335 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006336 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00006337
6338 /// RAII object wrapping the visitation of a sequenced subexpression of an
6339 /// expression. At the end of this process, the side-effects of the evaluation
6340 /// become sequenced with respect to the value computation of the result, so
6341 /// we downgrade any UK_ModAsSideEffect within the evaluation to
6342 /// UK_ModAsValue.
6343 struct SequencedSubexpression {
6344 SequencedSubexpression(SequenceChecker &Self)
6345 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
6346 Self.ModAsSideEffect = &ModAsSideEffect;
6347 }
6348 ~SequencedSubexpression() {
6349 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
6350 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
6351 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
6352 Self.addUsage(U, ModAsSideEffect[I].first,
6353 ModAsSideEffect[I].second.Use, UK_ModAsValue);
6354 }
6355 Self.ModAsSideEffect = OldModAsSideEffect;
6356 }
6357
6358 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006359 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
6360 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00006361 };
6362
Richard Smith40238f02013-06-20 22:21:56 +00006363 /// RAII object wrapping the visitation of a subexpression which we might
6364 /// choose to evaluate as a constant. If any subexpression is evaluated and
6365 /// found to be non-constant, this allows us to suppress the evaluation of
6366 /// the outer expression.
6367 class EvaluationTracker {
6368 public:
6369 EvaluationTracker(SequenceChecker &Self)
6370 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
6371 Self.EvalTracker = this;
6372 }
6373 ~EvaluationTracker() {
6374 Self.EvalTracker = Prev;
6375 if (Prev)
6376 Prev->EvalOK &= EvalOK;
6377 }
6378
6379 bool evaluate(const Expr *E, bool &Result) {
6380 if (!EvalOK || E->isValueDependent())
6381 return false;
6382 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
6383 return EvalOK;
6384 }
6385
6386 private:
6387 SequenceChecker &Self;
6388 EvaluationTracker *Prev;
6389 bool EvalOK;
6390 } *EvalTracker;
6391
Richard Smithc406cb72013-01-17 01:17:56 +00006392 /// \brief Find the object which is produced by the specified expression,
6393 /// if any.
6394 Object getObject(Expr *E, bool Mod) const {
6395 E = E->IgnoreParenCasts();
6396 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6397 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
6398 return getObject(UO->getSubExpr(), Mod);
6399 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6400 if (BO->getOpcode() == BO_Comma)
6401 return getObject(BO->getRHS(), Mod);
6402 if (Mod && BO->isAssignmentOp())
6403 return getObject(BO->getLHS(), Mod);
6404 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6405 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
6406 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
6407 return ME->getMemberDecl();
6408 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6409 // FIXME: If this is a reference, map through to its value.
6410 return DRE->getDecl();
6411 return 0;
6412 }
6413
6414 /// \brief Note that an object was modified or used by an expression.
6415 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
6416 Usage &U = UI.Uses[UK];
6417 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
6418 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
6419 ModAsSideEffect->push_back(std::make_pair(O, U));
6420 U.Use = Ref;
6421 U.Seq = Region;
6422 }
6423 }
6424 /// \brief Check whether a modification or use conflicts with a prior usage.
6425 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
6426 bool IsModMod) {
6427 if (UI.Diagnosed)
6428 return;
6429
6430 const Usage &U = UI.Uses[OtherKind];
6431 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
6432 return;
6433
6434 Expr *Mod = U.Use;
6435 Expr *ModOrUse = Ref;
6436 if (OtherKind == UK_Use)
6437 std::swap(Mod, ModOrUse);
6438
6439 SemaRef.Diag(Mod->getExprLoc(),
6440 IsModMod ? diag::warn_unsequenced_mod_mod
6441 : diag::warn_unsequenced_mod_use)
6442 << O << SourceRange(ModOrUse->getExprLoc());
6443 UI.Diagnosed = true;
6444 }
6445
6446 void notePreUse(Object O, Expr *Use) {
6447 UsageInfo &U = UsageMap[O];
6448 // Uses conflict with other modifications.
6449 checkUsage(O, U, Use, UK_ModAsValue, false);
6450 }
6451 void notePostUse(Object O, Expr *Use) {
6452 UsageInfo &U = UsageMap[O];
6453 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
6454 addUsage(U, O, Use, UK_Use);
6455 }
6456
6457 void notePreMod(Object O, Expr *Mod) {
6458 UsageInfo &U = UsageMap[O];
6459 // Modifications conflict with other modifications and with uses.
6460 checkUsage(O, U, Mod, UK_ModAsValue, true);
6461 checkUsage(O, U, Mod, UK_Use, false);
6462 }
6463 void notePostMod(Object O, Expr *Use, UsageKind UK) {
6464 UsageInfo &U = UsageMap[O];
6465 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
6466 addUsage(U, O, Use, UK);
6467 }
6468
6469public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006470 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
6471 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
6472 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00006473 Visit(E);
6474 }
6475
6476 void VisitStmt(Stmt *S) {
6477 // Skip all statements which aren't expressions for now.
6478 }
6479
6480 void VisitExpr(Expr *E) {
6481 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00006482 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006483 }
6484
6485 void VisitCastExpr(CastExpr *E) {
6486 Object O = Object();
6487 if (E->getCastKind() == CK_LValueToRValue)
6488 O = getObject(E->getSubExpr(), false);
6489
6490 if (O)
6491 notePreUse(O, E);
6492 VisitExpr(E);
6493 if (O)
6494 notePostUse(O, E);
6495 }
6496
6497 void VisitBinComma(BinaryOperator *BO) {
6498 // C++11 [expr.comma]p1:
6499 // Every value computation and side effect associated with the left
6500 // expression is sequenced before every value computation and side
6501 // effect associated with the right expression.
6502 SequenceTree::Seq LHS = Tree.allocate(Region);
6503 SequenceTree::Seq RHS = Tree.allocate(Region);
6504 SequenceTree::Seq OldRegion = Region;
6505
6506 {
6507 SequencedSubexpression SeqLHS(*this);
6508 Region = LHS;
6509 Visit(BO->getLHS());
6510 }
6511
6512 Region = RHS;
6513 Visit(BO->getRHS());
6514
6515 Region = OldRegion;
6516
6517 // Forget that LHS and RHS are sequenced. They are both unsequenced
6518 // with respect to other stuff.
6519 Tree.merge(LHS);
6520 Tree.merge(RHS);
6521 }
6522
6523 void VisitBinAssign(BinaryOperator *BO) {
6524 // The modification is sequenced after the value computation of the LHS
6525 // and RHS, so check it before inspecting the operands and update the
6526 // map afterwards.
6527 Object O = getObject(BO->getLHS(), true);
6528 if (!O)
6529 return VisitExpr(BO);
6530
6531 notePreMod(O, BO);
6532
6533 // C++11 [expr.ass]p7:
6534 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6535 // only once.
6536 //
6537 // Therefore, for a compound assignment operator, O is considered used
6538 // everywhere except within the evaluation of E1 itself.
6539 if (isa<CompoundAssignOperator>(BO))
6540 notePreUse(O, BO);
6541
6542 Visit(BO->getLHS());
6543
6544 if (isa<CompoundAssignOperator>(BO))
6545 notePostUse(O, BO);
6546
6547 Visit(BO->getRHS());
6548
Richard Smith83e37bee2013-06-26 23:16:51 +00006549 // C++11 [expr.ass]p1:
6550 // the assignment is sequenced [...] before the value computation of the
6551 // assignment expression.
6552 // C11 6.5.16/3 has no such rule.
6553 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6554 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006555 }
6556 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6557 VisitBinAssign(CAO);
6558 }
6559
6560 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6561 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6562 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6563 Object O = getObject(UO->getSubExpr(), true);
6564 if (!O)
6565 return VisitExpr(UO);
6566
6567 notePreMod(O, UO);
6568 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006569 // C++11 [expr.pre.incr]p1:
6570 // the expression ++x is equivalent to x+=1
6571 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6572 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006573 }
6574
6575 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6576 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6577 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6578 Object O = getObject(UO->getSubExpr(), true);
6579 if (!O)
6580 return VisitExpr(UO);
6581
6582 notePreMod(O, UO);
6583 Visit(UO->getSubExpr());
6584 notePostMod(O, UO, UK_ModAsSideEffect);
6585 }
6586
6587 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6588 void VisitBinLOr(BinaryOperator *BO) {
6589 // The side-effects of the LHS of an '&&' are sequenced before the
6590 // value computation of the RHS, and hence before the value computation
6591 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6592 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006593 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006594 {
6595 SequencedSubexpression Sequenced(*this);
6596 Visit(BO->getLHS());
6597 }
6598
6599 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006600 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006601 if (!Result)
6602 Visit(BO->getRHS());
6603 } else {
6604 // Check for unsequenced operations in the RHS, treating it as an
6605 // entirely separate evaluation.
6606 //
6607 // FIXME: If there are operations in the RHS which are unsequenced
6608 // with respect to operations outside the RHS, and those operations
6609 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006610 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006611 }
Richard Smithc406cb72013-01-17 01:17:56 +00006612 }
6613 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006614 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006615 {
6616 SequencedSubexpression Sequenced(*this);
6617 Visit(BO->getLHS());
6618 }
6619
6620 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006621 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006622 if (Result)
6623 Visit(BO->getRHS());
6624 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006625 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006626 }
Richard Smithc406cb72013-01-17 01:17:56 +00006627 }
6628
6629 // Only visit the condition, unless we can be sure which subexpression will
6630 // be chosen.
6631 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006632 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006633 {
6634 SequencedSubexpression Sequenced(*this);
6635 Visit(CO->getCond());
6636 }
Richard Smithc406cb72013-01-17 01:17:56 +00006637
6638 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006639 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006640 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006641 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006642 WorkList.push_back(CO->getTrueExpr());
6643 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006644 }
Richard Smithc406cb72013-01-17 01:17:56 +00006645 }
6646
Richard Smithe3dbfe02013-06-30 10:40:20 +00006647 void VisitCallExpr(CallExpr *CE) {
6648 // C++11 [intro.execution]p15:
6649 // When calling a function [...], every value computation and side effect
6650 // associated with any argument expression, or with the postfix expression
6651 // designating the called function, is sequenced before execution of every
6652 // expression or statement in the body of the function [and thus before
6653 // the value computation of its result].
6654 SequencedSubexpression Sequenced(*this);
6655 Base::VisitCallExpr(CE);
6656
6657 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6658 }
6659
Richard Smithc406cb72013-01-17 01:17:56 +00006660 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006661 // This is a call, so all subexpressions are sequenced before the result.
6662 SequencedSubexpression Sequenced(*this);
6663
Richard Smithc406cb72013-01-17 01:17:56 +00006664 if (!CCE->isListInitialization())
6665 return VisitExpr(CCE);
6666
6667 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006668 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006669 SequenceTree::Seq Parent = Region;
6670 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6671 E = CCE->arg_end();
6672 I != E; ++I) {
6673 Region = Tree.allocate(Parent);
6674 Elts.push_back(Region);
6675 Visit(*I);
6676 }
6677
6678 // Forget that the initializers are sequenced.
6679 Region = Parent;
6680 for (unsigned I = 0; I < Elts.size(); ++I)
6681 Tree.merge(Elts[I]);
6682 }
6683
6684 void VisitInitListExpr(InitListExpr *ILE) {
6685 if (!SemaRef.getLangOpts().CPlusPlus11)
6686 return VisitExpr(ILE);
6687
6688 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006689 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006690 SequenceTree::Seq Parent = Region;
6691 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6692 Expr *E = ILE->getInit(I);
6693 if (!E) continue;
6694 Region = Tree.allocate(Parent);
6695 Elts.push_back(Region);
6696 Visit(E);
6697 }
6698
6699 // Forget that the initializers are sequenced.
6700 Region = Parent;
6701 for (unsigned I = 0; I < Elts.size(); ++I)
6702 Tree.merge(Elts[I]);
6703 }
6704};
6705}
6706
6707void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006708 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006709 WorkList.push_back(E);
6710 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006711 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006712 SequenceChecker(*this, Item, WorkList);
6713 }
Richard Smithc406cb72013-01-17 01:17:56 +00006714}
6715
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006716void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6717 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006718 CheckImplicitConversions(E, CheckLoc);
6719 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006720 if (!IsConstexpr && !E->isValueDependent())
6721 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006722}
6723
John McCall1f425642010-11-11 03:21:53 +00006724void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6725 FieldDecl *BitField,
6726 Expr *Init) {
6727 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6728}
6729
Mike Stump0c2ec772010-01-21 03:59:47 +00006730/// CheckParmsForFunctionDef - Check that the parameters of the given
6731/// function are appropriate for the definition of a function. This
6732/// takes care of any checks that cannot be performed on the
6733/// declaration itself, e.g., that the types of each of the function
6734/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006735bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6736 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006737 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006738 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006739 for (; P != PEnd; ++P) {
6740 ParmVarDecl *Param = *P;
6741
Mike Stump0c2ec772010-01-21 03:59:47 +00006742 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6743 // function declarator that is part of a function definition of
6744 // that function shall not have incomplete type.
6745 //
6746 // This is also C++ [dcl.fct]p6.
6747 if (!Param->isInvalidDecl() &&
6748 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006749 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006750 Param->setInvalidDecl();
6751 HasInvalidParm = true;
6752 }
6753
6754 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6755 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006756 if (CheckParameterNames &&
6757 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006758 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006759 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006760 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006761
6762 // C99 6.7.5.3p12:
6763 // If the function declarator is not part of a definition of that
6764 // function, parameters may have incomplete type and may use the [*]
6765 // notation in their sequences of declarator specifiers to specify
6766 // variable length array types.
6767 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006768 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006769 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006770 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006771 // information is added for it.
6772 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006773 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006774 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006775 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006776 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006777
6778 // MSVC destroys objects passed by value in the callee. Therefore a
6779 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006780 // object's destructor. However, we don't perform any direct access check
6781 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006782 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6783 .getCXXABI()
6784 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006785 if (!Param->isInvalidDecl()) {
6786 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6787 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6788 if (!ClassDecl->isInvalidDecl() &&
6789 !ClassDecl->hasIrrelevantDestructor() &&
6790 !ClassDecl->isDependentContext()) {
6791 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6792 MarkFunctionReferenced(Param->getLocation(), Destructor);
6793 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6794 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006795 }
6796 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006797 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006798 }
6799
6800 return HasInvalidParm;
6801}
John McCall2b5c1b22010-08-12 21:44:57 +00006802
6803/// CheckCastAlign - Implements -Wcast-align, which warns when a
6804/// pointer cast increases the alignment requirements.
6805void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6806 // This is actually a lot of work to potentially be doing on every
6807 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006808 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6809 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006810 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006811 return;
6812
6813 // Ignore dependent types.
6814 if (T->isDependentType() || Op->getType()->isDependentType())
6815 return;
6816
6817 // Require that the destination be a pointer type.
6818 const PointerType *DestPtr = T->getAs<PointerType>();
6819 if (!DestPtr) return;
6820
6821 // If the destination has alignment 1, we're done.
6822 QualType DestPointee = DestPtr->getPointeeType();
6823 if (DestPointee->isIncompleteType()) return;
6824 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6825 if (DestAlign.isOne()) return;
6826
6827 // Require that the source be a pointer type.
6828 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6829 if (!SrcPtr) return;
6830 QualType SrcPointee = SrcPtr->getPointeeType();
6831
6832 // Whitelist casts from cv void*. We already implicitly
6833 // whitelisted casts to cv void*, since they have alignment 1.
6834 // Also whitelist casts involving incomplete types, which implicitly
6835 // includes 'void'.
6836 if (SrcPointee->isIncompleteType()) return;
6837
6838 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6839 if (SrcAlign >= DestAlign) return;
6840
6841 Diag(TRange.getBegin(), diag::warn_cast_align)
6842 << Op->getType() << T
6843 << static_cast<unsigned>(SrcAlign.getQuantity())
6844 << static_cast<unsigned>(DestAlign.getQuantity())
6845 << TRange << Op->getSourceRange();
6846}
6847
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006848static const Type* getElementType(const Expr *BaseExpr) {
6849 const Type* EltType = BaseExpr->getType().getTypePtr();
6850 if (EltType->isAnyPointerType())
6851 return EltType->getPointeeType().getTypePtr();
6852 else if (EltType->isArrayType())
6853 return EltType->getBaseElementTypeUnsafe();
6854 return EltType;
6855}
6856
Chandler Carruth28389f02011-08-05 09:10:50 +00006857/// \brief Check whether this array fits the idiom of a size-one tail padded
6858/// array member of a struct.
6859///
6860/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6861/// commonly used to emulate flexible arrays in C89 code.
6862static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6863 const NamedDecl *ND) {
6864 if (Size != 1 || !ND) return false;
6865
6866 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6867 if (!FD) return false;
6868
6869 // Don't consider sizes resulting from macro expansions or template argument
6870 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006871
6872 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006873 while (TInfo) {
6874 TypeLoc TL = TInfo->getTypeLoc();
6875 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006876 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6877 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006878 TInfo = TDL->getTypeSourceInfo();
6879 continue;
6880 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006881 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6882 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006883 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6884 return false;
6885 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006886 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006887 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006888
6889 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006890 if (!RD) return false;
6891 if (RD->isUnion()) return false;
6892 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6893 if (!CRD->isStandardLayout()) return false;
6894 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006895
Benjamin Kramer8c543672011-08-06 03:04:42 +00006896 // See if this is the last field decl in the record.
6897 const Decl *D = FD;
6898 while ((D = D->getNextDeclInContext()))
6899 if (isa<FieldDecl>(D))
6900 return false;
6901 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006902}
6903
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006904void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006905 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006906 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006907 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006908 if (IndexExpr->isValueDependent())
6909 return;
6910
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006911 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006912 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006913 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006914 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006915 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006916 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006917
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006918 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006919 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006920 return;
Richard Smith13f67182011-12-16 19:31:14 +00006921 if (IndexNegated)
6922 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006923
Chandler Carruth126b1552011-08-05 08:07:29 +00006924 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006925 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6926 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006927 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006928 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006929
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006930 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006931 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006932 if (!size.isStrictlyPositive())
6933 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006934
6935 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006936 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006937 // Make sure we're comparing apples to apples when comparing index to size
6938 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6939 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006940 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006941 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006942 if (ptrarith_typesize != array_typesize) {
6943 // There's a cast to a different size type involved
6944 uint64_t ratio = array_typesize / ptrarith_typesize;
6945 // TODO: Be smarter about handling cases where array_typesize is not a
6946 // multiple of ptrarith_typesize
6947 if (ptrarith_typesize * ratio == array_typesize)
6948 size *= llvm::APInt(size.getBitWidth(), ratio);
6949 }
6950 }
6951
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006952 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006953 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006954 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006955 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006956
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006957 // For array subscripting the index must be less than size, but for pointer
6958 // arithmetic also allow the index (offset) to be equal to size since
6959 // computing the next address after the end of the array is legal and
6960 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006961 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006962 return;
6963
6964 // Also don't warn for arrays of size 1 which are members of some
6965 // structure. These are often used to approximate flexible arrays in C89
6966 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006967 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006968 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006969
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006970 // Suppress the warning if the subscript expression (as identified by the
6971 // ']' location) and the index expression are both from macro expansions
6972 // within a system header.
6973 if (ASE) {
6974 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6975 ASE->getRBracketLoc());
6976 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6977 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6978 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006979 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006980 return;
6981 }
6982 }
6983
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006984 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006985 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006986 DiagID = diag::warn_array_index_exceeds_bounds;
6987
6988 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6989 PDiag(DiagID) << index.toString(10, true)
6990 << size.toString(10, true)
6991 << (unsigned)size.getLimitedValue(~0U)
6992 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006993 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006994 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006995 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006996 DiagID = diag::warn_ptr_arith_precedes_bounds;
6997 if (index.isNegative()) index = -index;
6998 }
6999
7000 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7001 PDiag(DiagID) << index.toString(10, true)
7002 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007003 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007004
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007005 if (!ND) {
7006 // Try harder to find a NamedDecl to point at in the note.
7007 while (const ArraySubscriptExpr *ASE =
7008 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7009 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7010 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7011 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7012 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7013 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7014 }
7015
Chandler Carruth1af88f12011-02-17 21:10:52 +00007016 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007017 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7018 PDiag(diag::note_array_index_out_of_bounds)
7019 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007020}
7021
Ted Kremenekdf26df72011-03-01 18:41:00 +00007022void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007023 int AllowOnePastEnd = 0;
7024 while (expr) {
7025 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007026 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007027 case Stmt::ArraySubscriptExprClass: {
7028 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007029 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007030 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007031 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007032 }
7033 case Stmt::UnaryOperatorClass: {
7034 // Only unwrap the * and & unary operators
7035 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7036 expr = UO->getSubExpr();
7037 switch (UO->getOpcode()) {
7038 case UO_AddrOf:
7039 AllowOnePastEnd++;
7040 break;
7041 case UO_Deref:
7042 AllowOnePastEnd--;
7043 break;
7044 default:
7045 return;
7046 }
7047 break;
7048 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007049 case Stmt::ConditionalOperatorClass: {
7050 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7051 if (const Expr *lhs = cond->getLHS())
7052 CheckArrayAccess(lhs);
7053 if (const Expr *rhs = cond->getRHS())
7054 CheckArrayAccess(rhs);
7055 return;
7056 }
7057 default:
7058 return;
7059 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007060 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007061}
John McCall31168b02011-06-15 23:02:42 +00007062
7063//===--- CHECK: Objective-C retain cycles ----------------------------------//
7064
7065namespace {
7066 struct RetainCycleOwner {
7067 RetainCycleOwner() : Variable(0), Indirect(false) {}
7068 VarDecl *Variable;
7069 SourceRange Range;
7070 SourceLocation Loc;
7071 bool Indirect;
7072
7073 void setLocsFrom(Expr *e) {
7074 Loc = e->getExprLoc();
7075 Range = e->getSourceRange();
7076 }
7077 };
7078}
7079
7080/// Consider whether capturing the given variable can possibly lead to
7081/// a retain cycle.
7082static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00007083 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00007084 // lifetime. In MRR, it's captured strongly if the variable is
7085 // __block and has an appropriate type.
7086 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7087 return false;
7088
7089 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007090 if (ref)
7091 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00007092 return true;
7093}
7094
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007095static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00007096 while (true) {
7097 e = e->IgnoreParens();
7098 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7099 switch (cast->getCastKind()) {
7100 case CK_BitCast:
7101 case CK_LValueBitCast:
7102 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00007103 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00007104 e = cast->getSubExpr();
7105 continue;
7106
John McCall31168b02011-06-15 23:02:42 +00007107 default:
7108 return false;
7109 }
7110 }
7111
7112 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7113 ObjCIvarDecl *ivar = ref->getDecl();
7114 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7115 return false;
7116
7117 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007118 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00007119 return false;
7120
7121 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
7122 owner.Indirect = true;
7123 return true;
7124 }
7125
7126 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
7127 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
7128 if (!var) return false;
7129 return considerVariable(var, ref, owner);
7130 }
7131
John McCall31168b02011-06-15 23:02:42 +00007132 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
7133 if (member->isArrow()) return false;
7134
7135 // Don't count this as an indirect ownership.
7136 e = member->getBase();
7137 continue;
7138 }
7139
John McCallfe96e0b2011-11-06 09:01:30 +00007140 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
7141 // Only pay attention to pseudo-objects on property references.
7142 ObjCPropertyRefExpr *pre
7143 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
7144 ->IgnoreParens());
7145 if (!pre) return false;
7146 if (pre->isImplicitProperty()) return false;
7147 ObjCPropertyDecl *property = pre->getExplicitProperty();
7148 if (!property->isRetaining() &&
7149 !(property->getPropertyIvarDecl() &&
7150 property->getPropertyIvarDecl()->getType()
7151 .getObjCLifetime() == Qualifiers::OCL_Strong))
7152 return false;
7153
7154 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007155 if (pre->isSuperReceiver()) {
7156 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
7157 if (!owner.Variable)
7158 return false;
7159 owner.Loc = pre->getLocation();
7160 owner.Range = pre->getSourceRange();
7161 return true;
7162 }
John McCallfe96e0b2011-11-06 09:01:30 +00007163 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
7164 ->getSourceExpr());
7165 continue;
7166 }
7167
John McCall31168b02011-06-15 23:02:42 +00007168 // Array ivars?
7169
7170 return false;
7171 }
7172}
7173
7174namespace {
7175 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
7176 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
7177 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
7178 Variable(variable), Capturer(0) {}
7179
7180 VarDecl *Variable;
7181 Expr *Capturer;
7182
7183 void VisitDeclRefExpr(DeclRefExpr *ref) {
7184 if (ref->getDecl() == Variable && !Capturer)
7185 Capturer = ref;
7186 }
7187
John McCall31168b02011-06-15 23:02:42 +00007188 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
7189 if (Capturer) return;
7190 Visit(ref->getBase());
7191 if (Capturer && ref->isFreeIvar())
7192 Capturer = ref;
7193 }
7194
7195 void VisitBlockExpr(BlockExpr *block) {
7196 // Look inside nested blocks
7197 if (block->getBlockDecl()->capturesVariable(Variable))
7198 Visit(block->getBlockDecl()->getBody());
7199 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00007200
7201 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
7202 if (Capturer) return;
7203 if (OVE->getSourceExpr())
7204 Visit(OVE->getSourceExpr());
7205 }
John McCall31168b02011-06-15 23:02:42 +00007206 };
7207}
7208
7209/// Check whether the given argument is a block which captures a
7210/// variable.
7211static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
7212 assert(owner.Variable && owner.Loc.isValid());
7213
7214 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00007215
7216 // Look through [^{...} copy] and Block_copy(^{...}).
7217 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
7218 Selector Cmd = ME->getSelector();
7219 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
7220 e = ME->getInstanceReceiver();
7221 if (!e)
7222 return 0;
7223 e = e->IgnoreParenCasts();
7224 }
7225 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
7226 if (CE->getNumArgs() == 1) {
7227 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00007228 if (Fn) {
7229 const IdentifierInfo *FnI = Fn->getIdentifier();
7230 if (FnI && FnI->isStr("_Block_copy")) {
7231 e = CE->getArg(0)->IgnoreParenCasts();
7232 }
7233 }
Jordan Rose67e887c2012-09-17 17:54:30 +00007234 }
7235 }
7236
John McCall31168b02011-06-15 23:02:42 +00007237 BlockExpr *block = dyn_cast<BlockExpr>(e);
7238 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
7239 return 0;
7240
7241 FindCaptureVisitor visitor(S.Context, owner.Variable);
7242 visitor.Visit(block->getBlockDecl()->getBody());
7243 return visitor.Capturer;
7244}
7245
7246static void diagnoseRetainCycle(Sema &S, Expr *capturer,
7247 RetainCycleOwner &owner) {
7248 assert(capturer);
7249 assert(owner.Variable && owner.Loc.isValid());
7250
7251 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
7252 << owner.Variable << capturer->getSourceRange();
7253 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
7254 << owner.Indirect << owner.Range;
7255}
7256
7257/// Check for a keyword selector that starts with the word 'add' or
7258/// 'set'.
7259static bool isSetterLikeSelector(Selector sel) {
7260 if (sel.isUnarySelector()) return false;
7261
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007262 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00007263 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007264 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00007265 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00007266 else if (str.startswith("add")) {
7267 // Specially whitelist 'addOperationWithBlock:'.
7268 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
7269 return false;
7270 str = str.substr(3);
7271 }
John McCall31168b02011-06-15 23:02:42 +00007272 else
7273 return false;
7274
7275 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00007276 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00007277}
7278
7279/// Check a message send to see if it's likely to cause a retain cycle.
7280void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
7281 // Only check instance methods whose selector looks like a setter.
7282 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
7283 return;
7284
7285 // Try to find a variable that the receiver is strongly owned by.
7286 RetainCycleOwner owner;
7287 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007288 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00007289 return;
7290 } else {
7291 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
7292 owner.Variable = getCurMethodDecl()->getSelfDecl();
7293 owner.Loc = msg->getSuperLoc();
7294 owner.Range = msg->getSuperLoc();
7295 }
7296
7297 // Check whether the receiver is captured by any of the arguments.
7298 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
7299 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
7300 return diagnoseRetainCycle(*this, capturer, owner);
7301}
7302
7303/// Check a property assign to see if it's likely to cause a retain cycle.
7304void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
7305 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00007306 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00007307 return;
7308
7309 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
7310 diagnoseRetainCycle(*this, capturer, owner);
7311}
7312
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00007313void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
7314 RetainCycleOwner Owner;
7315 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
7316 return;
7317
7318 // Because we don't have an expression for the variable, we have to set the
7319 // location explicitly here.
7320 Owner.Loc = Var->getLocation();
7321 Owner.Range = Var->getSourceRange();
7322
7323 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
7324 diagnoseRetainCycle(*this, Capturer, Owner);
7325}
7326
Ted Kremenek9304da92012-12-21 08:04:28 +00007327static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
7328 Expr *RHS, bool isProperty) {
7329 // Check if RHS is an Objective-C object literal, which also can get
7330 // immediately zapped in a weak reference. Note that we explicitly
7331 // allow ObjCStringLiterals, since those are designed to never really die.
7332 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007333
Ted Kremenek64873352012-12-21 22:46:35 +00007334 // This enum needs to match with the 'select' in
7335 // warn_objc_arc_literal_assign (off-by-1).
7336 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
7337 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
7338 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007339
7340 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00007341 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00007342 << (isProperty ? 0 : 1)
7343 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00007344
7345 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00007346}
7347
Ted Kremenekc1f014a2012-12-21 19:45:30 +00007348static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
7349 Qualifiers::ObjCLifetime LT,
7350 Expr *RHS, bool isProperty) {
7351 // Strip off any implicit cast added to get to the one ARC-specific.
7352 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
7353 if (cast->getCastKind() == CK_ARCConsumeObject) {
7354 S.Diag(Loc, diag::warn_arc_retained_assign)
7355 << (LT == Qualifiers::OCL_ExplicitNone)
7356 << (isProperty ? 0 : 1)
7357 << RHS->getSourceRange();
7358 return true;
7359 }
7360 RHS = cast->getSubExpr();
7361 }
7362
7363 if (LT == Qualifiers::OCL_Weak &&
7364 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
7365 return true;
7366
7367 return false;
7368}
7369
Ted Kremenekb36234d2012-12-21 08:04:20 +00007370bool Sema::checkUnsafeAssigns(SourceLocation Loc,
7371 QualType LHS, Expr *RHS) {
7372 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
7373
7374 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
7375 return false;
7376
7377 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
7378 return true;
7379
7380 return false;
7381}
7382
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007383void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
7384 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007385 QualType LHSType;
7386 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00007387 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007388 ObjCPropertyRefExpr *PRE
7389 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
7390 if (PRE && !PRE->isImplicitProperty()) {
7391 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7392 if (PD)
7393 LHSType = PD->getType();
7394 }
7395
7396 if (LHSType.isNull())
7397 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00007398
7399 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
7400
7401 if (LT == Qualifiers::OCL_Weak) {
7402 DiagnosticsEngine::Level Level =
7403 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
7404 if (Level != DiagnosticsEngine::Ignored)
7405 getCurFunction()->markSafeWeakUse(LHS);
7406 }
7407
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007408 if (checkUnsafeAssigns(Loc, LHSType, RHS))
7409 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00007410
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007411 // FIXME. Check for other life times.
7412 if (LT != Qualifiers::OCL_None)
7413 return;
7414
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007415 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007416 if (PRE->isImplicitProperty())
7417 return;
7418 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
7419 if (!PD)
7420 return;
7421
Bill Wendling44426052012-12-20 19:22:21 +00007422 unsigned Attributes = PD->getPropertyAttributes();
7423 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007424 // when 'assign' attribute was not explicitly specified
7425 // by user, ignore it and rely on property type itself
7426 // for lifetime info.
7427 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
7428 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
7429 LHSType->isObjCRetainableType())
7430 return;
7431
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007432 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00007433 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007434 Diag(Loc, diag::warn_arc_retained_property_assign)
7435 << RHS->getSourceRange();
7436 return;
7437 }
7438 RHS = cast->getSubExpr();
7439 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00007440 }
Bill Wendling44426052012-12-20 19:22:21 +00007441 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00007442 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
7443 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00007444 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007445 }
7446}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00007447
7448//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
7449
7450namespace {
7451bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
7452 SourceLocation StmtLoc,
7453 const NullStmt *Body) {
7454 // Do not warn if the body is a macro that expands to nothing, e.g:
7455 //
7456 // #define CALL(x)
7457 // if (condition)
7458 // CALL(0);
7459 //
7460 if (Body->hasLeadingEmptyMacro())
7461 return false;
7462
7463 // Get line numbers of statement and body.
7464 bool StmtLineInvalid;
7465 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
7466 &StmtLineInvalid);
7467 if (StmtLineInvalid)
7468 return false;
7469
7470 bool BodyLineInvalid;
7471 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
7472 &BodyLineInvalid);
7473 if (BodyLineInvalid)
7474 return false;
7475
7476 // Warn if null statement and body are on the same line.
7477 if (StmtLine != BodyLine)
7478 return false;
7479
7480 return true;
7481}
7482} // Unnamed namespace
7483
7484void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
7485 const Stmt *Body,
7486 unsigned DiagID) {
7487 // Since this is a syntactic check, don't emit diagnostic for template
7488 // instantiations, this just adds noise.
7489 if (CurrentInstantiationScope)
7490 return;
7491
7492 // The body should be a null statement.
7493 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7494 if (!NBody)
7495 return;
7496
7497 // Do the usual checks.
7498 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7499 return;
7500
7501 Diag(NBody->getSemiLoc(), DiagID);
7502 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7503}
7504
7505void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
7506 const Stmt *PossibleBody) {
7507 assert(!CurrentInstantiationScope); // Ensured by caller
7508
7509 SourceLocation StmtLoc;
7510 const Stmt *Body;
7511 unsigned DiagID;
7512 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
7513 StmtLoc = FS->getRParenLoc();
7514 Body = FS->getBody();
7515 DiagID = diag::warn_empty_for_body;
7516 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
7517 StmtLoc = WS->getCond()->getSourceRange().getEnd();
7518 Body = WS->getBody();
7519 DiagID = diag::warn_empty_while_body;
7520 } else
7521 return; // Neither `for' nor `while'.
7522
7523 // The body should be a null statement.
7524 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7525 if (!NBody)
7526 return;
7527
7528 // Skip expensive checks if diagnostic is disabled.
7529 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7530 DiagnosticsEngine::Ignored)
7531 return;
7532
7533 // Do the usual checks.
7534 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7535 return;
7536
7537 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7538 // noise level low, emit diagnostics only if for/while is followed by a
7539 // CompoundStmt, e.g.:
7540 // for (int i = 0; i < n; i++);
7541 // {
7542 // a(i);
7543 // }
7544 // or if for/while is followed by a statement with more indentation
7545 // than for/while itself:
7546 // for (int i = 0; i < n; i++);
7547 // a(i);
7548 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7549 if (!ProbableTypo) {
7550 bool BodyColInvalid;
7551 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7552 PossibleBody->getLocStart(),
7553 &BodyColInvalid);
7554 if (BodyColInvalid)
7555 return;
7556
7557 bool StmtColInvalid;
7558 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7559 S->getLocStart(),
7560 &StmtColInvalid);
7561 if (StmtColInvalid)
7562 return;
7563
7564 if (BodyCol > StmtCol)
7565 ProbableTypo = true;
7566 }
7567
7568 if (ProbableTypo) {
7569 Diag(NBody->getSemiLoc(), DiagID);
7570 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7571 }
7572}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007573
7574//===--- Layout compatibility ----------------------------------------------//
7575
7576namespace {
7577
7578bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7579
7580/// \brief Check if two enumeration types are layout-compatible.
7581bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7582 // C++11 [dcl.enum] p8:
7583 // Two enumeration types are layout-compatible if they have the same
7584 // underlying type.
7585 return ED1->isComplete() && ED2->isComplete() &&
7586 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7587}
7588
7589/// \brief Check if two fields are layout-compatible.
7590bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7591 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7592 return false;
7593
7594 if (Field1->isBitField() != Field2->isBitField())
7595 return false;
7596
7597 if (Field1->isBitField()) {
7598 // Make sure that the bit-fields are the same length.
7599 unsigned Bits1 = Field1->getBitWidthValue(C);
7600 unsigned Bits2 = Field2->getBitWidthValue(C);
7601
7602 if (Bits1 != Bits2)
7603 return false;
7604 }
7605
7606 return true;
7607}
7608
7609/// \brief Check if two standard-layout structs are layout-compatible.
7610/// (C++11 [class.mem] p17)
7611bool isLayoutCompatibleStruct(ASTContext &C,
7612 RecordDecl *RD1,
7613 RecordDecl *RD2) {
7614 // If both records are C++ classes, check that base classes match.
7615 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7616 // If one of records is a CXXRecordDecl we are in C++ mode,
7617 // thus the other one is a CXXRecordDecl, too.
7618 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7619 // Check number of base classes.
7620 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7621 return false;
7622
7623 // Check the base classes.
7624 for (CXXRecordDecl::base_class_const_iterator
7625 Base1 = D1CXX->bases_begin(),
7626 BaseEnd1 = D1CXX->bases_end(),
7627 Base2 = D2CXX->bases_begin();
7628 Base1 != BaseEnd1;
7629 ++Base1, ++Base2) {
7630 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7631 return false;
7632 }
7633 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7634 // If only RD2 is a C++ class, it should have zero base classes.
7635 if (D2CXX->getNumBases() > 0)
7636 return false;
7637 }
7638
7639 // Check the fields.
7640 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7641 Field2End = RD2->field_end(),
7642 Field1 = RD1->field_begin(),
7643 Field1End = RD1->field_end();
7644 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7645 if (!isLayoutCompatible(C, *Field1, *Field2))
7646 return false;
7647 }
7648 if (Field1 != Field1End || Field2 != Field2End)
7649 return false;
7650
7651 return true;
7652}
7653
7654/// \brief Check if two standard-layout unions are layout-compatible.
7655/// (C++11 [class.mem] p18)
7656bool isLayoutCompatibleUnion(ASTContext &C,
7657 RecordDecl *RD1,
7658 RecordDecl *RD2) {
7659 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007660 for (auto *Field2 : RD2->fields())
7661 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007662
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007663 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007664 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7665 I = UnmatchedFields.begin(),
7666 E = UnmatchedFields.end();
7667
7668 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00007669 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007670 bool Result = UnmatchedFields.erase(*I);
7671 (void) Result;
7672 assert(Result);
7673 break;
7674 }
7675 }
7676 if (I == E)
7677 return false;
7678 }
7679
7680 return UnmatchedFields.empty();
7681}
7682
7683bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7684 if (RD1->isUnion() != RD2->isUnion())
7685 return false;
7686
7687 if (RD1->isUnion())
7688 return isLayoutCompatibleUnion(C, RD1, RD2);
7689 else
7690 return isLayoutCompatibleStruct(C, RD1, RD2);
7691}
7692
7693/// \brief Check if two types are layout-compatible in C++11 sense.
7694bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7695 if (T1.isNull() || T2.isNull())
7696 return false;
7697
7698 // C++11 [basic.types] p11:
7699 // If two types T1 and T2 are the same type, then T1 and T2 are
7700 // layout-compatible types.
7701 if (C.hasSameType(T1, T2))
7702 return true;
7703
7704 T1 = T1.getCanonicalType().getUnqualifiedType();
7705 T2 = T2.getCanonicalType().getUnqualifiedType();
7706
7707 const Type::TypeClass TC1 = T1->getTypeClass();
7708 const Type::TypeClass TC2 = T2->getTypeClass();
7709
7710 if (TC1 != TC2)
7711 return false;
7712
7713 if (TC1 == Type::Enum) {
7714 return isLayoutCompatible(C,
7715 cast<EnumType>(T1)->getDecl(),
7716 cast<EnumType>(T2)->getDecl());
7717 } else if (TC1 == Type::Record) {
7718 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7719 return false;
7720
7721 return isLayoutCompatible(C,
7722 cast<RecordType>(T1)->getDecl(),
7723 cast<RecordType>(T2)->getDecl());
7724 }
7725
7726 return false;
7727}
7728}
7729
7730//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7731
7732namespace {
7733/// \brief Given a type tag expression find the type tag itself.
7734///
7735/// \param TypeExpr Type tag expression, as it appears in user's code.
7736///
7737/// \param VD Declaration of an identifier that appears in a type tag.
7738///
7739/// \param MagicValue Type tag magic value.
7740bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7741 const ValueDecl **VD, uint64_t *MagicValue) {
7742 while(true) {
7743 if (!TypeExpr)
7744 return false;
7745
7746 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7747
7748 switch (TypeExpr->getStmtClass()) {
7749 case Stmt::UnaryOperatorClass: {
7750 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7751 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7752 TypeExpr = UO->getSubExpr();
7753 continue;
7754 }
7755 return false;
7756 }
7757
7758 case Stmt::DeclRefExprClass: {
7759 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7760 *VD = DRE->getDecl();
7761 return true;
7762 }
7763
7764 case Stmt::IntegerLiteralClass: {
7765 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7766 llvm::APInt MagicValueAPInt = IL->getValue();
7767 if (MagicValueAPInt.getActiveBits() <= 64) {
7768 *MagicValue = MagicValueAPInt.getZExtValue();
7769 return true;
7770 } else
7771 return false;
7772 }
7773
7774 case Stmt::BinaryConditionalOperatorClass:
7775 case Stmt::ConditionalOperatorClass: {
7776 const AbstractConditionalOperator *ACO =
7777 cast<AbstractConditionalOperator>(TypeExpr);
7778 bool Result;
7779 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7780 if (Result)
7781 TypeExpr = ACO->getTrueExpr();
7782 else
7783 TypeExpr = ACO->getFalseExpr();
7784 continue;
7785 }
7786 return false;
7787 }
7788
7789 case Stmt::BinaryOperatorClass: {
7790 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7791 if (BO->getOpcode() == BO_Comma) {
7792 TypeExpr = BO->getRHS();
7793 continue;
7794 }
7795 return false;
7796 }
7797
7798 default:
7799 return false;
7800 }
7801 }
7802}
7803
7804/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7805///
7806/// \param TypeExpr Expression that specifies a type tag.
7807///
7808/// \param MagicValues Registered magic values.
7809///
7810/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7811/// kind.
7812///
7813/// \param TypeInfo Information about the corresponding C type.
7814///
7815/// \returns true if the corresponding C type was found.
7816bool GetMatchingCType(
7817 const IdentifierInfo *ArgumentKind,
7818 const Expr *TypeExpr, const ASTContext &Ctx,
7819 const llvm::DenseMap<Sema::TypeTagMagicValue,
7820 Sema::TypeTagData> *MagicValues,
7821 bool &FoundWrongKind,
7822 Sema::TypeTagData &TypeInfo) {
7823 FoundWrongKind = false;
7824
7825 // Variable declaration that has type_tag_for_datatype attribute.
7826 const ValueDecl *VD = NULL;
7827
7828 uint64_t MagicValue;
7829
7830 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7831 return false;
7832
7833 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00007834 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007835 if (I->getArgumentKind() != ArgumentKind) {
7836 FoundWrongKind = true;
7837 return false;
7838 }
7839 TypeInfo.Type = I->getMatchingCType();
7840 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7841 TypeInfo.MustBeNull = I->getMustBeNull();
7842 return true;
7843 }
7844 return false;
7845 }
7846
7847 if (!MagicValues)
7848 return false;
7849
7850 llvm::DenseMap<Sema::TypeTagMagicValue,
7851 Sema::TypeTagData>::const_iterator I =
7852 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7853 if (I == MagicValues->end())
7854 return false;
7855
7856 TypeInfo = I->second;
7857 return true;
7858}
7859} // unnamed namespace
7860
7861void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7862 uint64_t MagicValue, QualType Type,
7863 bool LayoutCompatible,
7864 bool MustBeNull) {
7865 if (!TypeTagForDatatypeMagicValues)
7866 TypeTagForDatatypeMagicValues.reset(
7867 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7868
7869 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7870 (*TypeTagForDatatypeMagicValues)[Magic] =
7871 TypeTagData(Type, LayoutCompatible, MustBeNull);
7872}
7873
7874namespace {
7875bool IsSameCharType(QualType T1, QualType T2) {
7876 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7877 if (!BT1)
7878 return false;
7879
7880 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7881 if (!BT2)
7882 return false;
7883
7884 BuiltinType::Kind T1Kind = BT1->getKind();
7885 BuiltinType::Kind T2Kind = BT2->getKind();
7886
7887 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7888 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7889 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7890 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7891}
7892} // unnamed namespace
7893
7894void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7895 const Expr * const *ExprArgs) {
7896 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7897 bool IsPointerAttr = Attr->getIsPointer();
7898
7899 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7900 bool FoundWrongKind;
7901 TypeTagData TypeInfo;
7902 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7903 TypeTagForDatatypeMagicValues.get(),
7904 FoundWrongKind, TypeInfo)) {
7905 if (FoundWrongKind)
7906 Diag(TypeTagExpr->getExprLoc(),
7907 diag::warn_type_tag_for_datatype_wrong_kind)
7908 << TypeTagExpr->getSourceRange();
7909 return;
7910 }
7911
7912 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7913 if (IsPointerAttr) {
7914 // Skip implicit cast of pointer to `void *' (as a function argument).
7915 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007916 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007917 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007918 ArgumentExpr = ICE->getSubExpr();
7919 }
7920 QualType ArgumentType = ArgumentExpr->getType();
7921
7922 // Passing a `void*' pointer shouldn't trigger a warning.
7923 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7924 return;
7925
7926 if (TypeInfo.MustBeNull) {
7927 // Type tag with matching void type requires a null pointer.
7928 if (!ArgumentExpr->isNullPointerConstant(Context,
7929 Expr::NPC_ValueDependentIsNotNull)) {
7930 Diag(ArgumentExpr->getExprLoc(),
7931 diag::warn_type_safety_null_pointer_required)
7932 << ArgumentKind->getName()
7933 << ArgumentExpr->getSourceRange()
7934 << TypeTagExpr->getSourceRange();
7935 }
7936 return;
7937 }
7938
7939 QualType RequiredType = TypeInfo.Type;
7940 if (IsPointerAttr)
7941 RequiredType = Context.getPointerType(RequiredType);
7942
7943 bool mismatch = false;
7944 if (!TypeInfo.LayoutCompatible) {
7945 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7946
7947 // C++11 [basic.fundamental] p1:
7948 // Plain char, signed char, and unsigned char are three distinct types.
7949 //
7950 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7951 // char' depending on the current char signedness mode.
7952 if (mismatch)
7953 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7954 RequiredType->getPointeeType())) ||
7955 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7956 mismatch = false;
7957 } else
7958 if (IsPointerAttr)
7959 mismatch = !isLayoutCompatible(Context,
7960 ArgumentType->getPointeeType(),
7961 RequiredType->getPointeeType());
7962 else
7963 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7964
7965 if (mismatch)
7966 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007967 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007968 << TypeInfo.LayoutCompatible << RequiredType
7969 << ArgumentExpr->getSourceRange()
7970 << TypeTagExpr->getSourceRange();
7971}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00007972