blob: 4636c92eccb7fbf64e68ed674c2737ac541ed5ff [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:
310 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311 return ExprError();
312 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000313 case llvm::Triple::mips:
314 case llvm::Triple::mipsel:
315 case llvm::Triple::mips64:
316 case llvm::Triple::mips64el:
317 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318 return ExprError();
319 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000320 default:
321 break;
322 }
323 }
324
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000325 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000326}
327
Nate Begeman91e1fea2010-06-14 05:21:25 +0000328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000330 NeonTypeFlags Type(t);
331 int IsQuad = Type.isQuad();
332 switch (Type.getEltType()) {
333 case NeonTypeFlags::Int8:
334 case NeonTypeFlags::Poly8:
335 return shift ? 7 : (8 << IsQuad) - 1;
336 case NeonTypeFlags::Int16:
337 case NeonTypeFlags::Poly16:
338 return shift ? 15 : (4 << IsQuad) - 1;
339 case NeonTypeFlags::Int32:
340 return shift ? 31 : (2 << IsQuad) - 1;
341 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000342 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000343 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000344 case NeonTypeFlags::Poly128:
345 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000346 case NeonTypeFlags::Float16:
347 assert(!shift && "cannot shift float types!");
348 return (4 << IsQuad) - 1;
349 case NeonTypeFlags::Float32:
350 assert(!shift && "cannot shift float types!");
351 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000352 case NeonTypeFlags::Float64:
353 assert(!shift && "cannot shift float types!");
354 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000355 }
David Blaikie8a40f702012-01-17 06:56:22 +0000356 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000357}
358
Bob Wilsone4d77232011-11-08 05:04:11 +0000359/// getNeonEltType - Return the QualType corresponding to the elements of
360/// the vector type specified by the NeonTypeFlags. This is used to check
361/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000362static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
363 bool IsAArch64) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000364 switch (Flags.getEltType()) {
365 case NeonTypeFlags::Int8:
366 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
367 case NeonTypeFlags::Int16:
368 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
369 case NeonTypeFlags::Int32:
370 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
371 case NeonTypeFlags::Int64:
372 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
373 case NeonTypeFlags::Poly8:
Kevin Qincaac85e2013-11-14 03:29:16 +0000374 return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000375 case NeonTypeFlags::Poly16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000376 return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
377 case NeonTypeFlags::Poly64:
378 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000379 case NeonTypeFlags::Poly128:
380 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000381 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000382 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000383 case NeonTypeFlags::Float32:
384 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000385 case NeonTypeFlags::Float64:
386 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000387 }
David Blaikie8a40f702012-01-17 06:56:22 +0000388 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000389}
390
Tim Northover2fe823a2013-08-01 09:23:19 +0000391bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
392 CallExpr *TheCall) {
393
394 llvm::APSInt Result;
395
396 uint64_t mask = 0;
397 unsigned TV = 0;
398 int PtrArgNum = -1;
399 bool HasConstPtr = false;
400 switch (BuiltinID) {
401#define GET_NEON_AARCH64_OVERLOAD_CHECK
402#include "clang/Basic/arm_neon.inc"
403#undef GET_NEON_AARCH64_OVERLOAD_CHECK
404 }
405
406 // For NEON intrinsics which are overloaded on vector element type, validate
407 // the immediate which specifies which variant to emit.
408 unsigned ImmArg = TheCall->getNumArgs() - 1;
409 if (mask) {
410 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
411 return true;
412
413 TV = Result.getLimitedValue(64);
414 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
415 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
416 << TheCall->getArg(ImmArg)->getSourceRange();
417 }
418
419 if (PtrArgNum >= 0) {
420 // Check that pointer arguments have the specified type.
421 Expr *Arg = TheCall->getArg(PtrArgNum);
422 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
423 Arg = ICE->getSubExpr();
424 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
425 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000426 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
Tim Northover2fe823a2013-08-01 09:23:19 +0000427 if (HasConstPtr)
428 EltTy = EltTy.withConst();
429 QualType LHSTy = Context.getPointerType(EltTy);
430 AssignConvertType ConvTy;
431 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
432 if (RHS.isInvalid())
433 return true;
434 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
435 RHS.get(), AA_Assigning))
436 return true;
437 }
438
439 // For NEON intrinsics which take an immediate value as part of the
440 // instruction, range check them here.
441 unsigned i = 0, l = 0, u = 0;
442 switch (BuiltinID) {
443 default:
444 return false;
445#define GET_NEON_AARCH64_IMMEDIATE_CHECK
446#include "clang/Basic/arm_neon.inc"
447#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
448 }
449 ;
450
451 // We can't check the value of a dependent argument.
452 if (TheCall->getArg(i)->isTypeDependent() ||
453 TheCall->getArg(i)->isValueDependent())
454 return false;
455
456 // Check that the immediate argument is actually a constant.
457 if (SemaBuiltinConstantArg(TheCall, i, Result))
458 return true;
459
460 // Range check against the upper/lower values for this isntruction.
461 unsigned Val = Result.getZExtValue();
462 if (Val < l || Val > (u + l))
463 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
464 << l << u + l << TheCall->getArg(i)->getSourceRange();
465
466 return false;
467}
468
Tim Northover6aacd492013-07-16 09:47:53 +0000469bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
470 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
471 BuiltinID == ARM::BI__builtin_arm_strex) &&
472 "unexpected ARM builtin");
473 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
474
475 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
476
477 // Ensure that we have the proper number of arguments.
478 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
479 return true;
480
481 // Inspect the pointer argument of the atomic builtin. This should always be
482 // a pointer type, whose element is an integral scalar or pointer type.
483 // Because it is a pointer type, we don't have to worry about any implicit
484 // casts here.
485 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
486 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
487 if (PointerArgRes.isInvalid())
488 return true;
489 PointerArg = PointerArgRes.take();
490
491 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
492 if (!pointerType) {
493 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
494 << PointerArg->getType() << PointerArg->getSourceRange();
495 return true;
496 }
497
498 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
499 // task is to insert the appropriate casts into the AST. First work out just
500 // what the appropriate type is.
501 QualType ValType = pointerType->getPointeeType();
502 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
503 if (IsLdrex)
504 AddrType.addConst();
505
506 // Issue a warning if the cast is dodgy.
507 CastKind CastNeeded = CK_NoOp;
508 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
509 CastNeeded = CK_BitCast;
510 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
511 << PointerArg->getType()
512 << Context.getPointerType(AddrType)
513 << AA_Passing << PointerArg->getSourceRange();
514 }
515
516 // Finally, do the cast and replace the argument with the corrected version.
517 AddrType = Context.getPointerType(AddrType);
518 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
519 if (PointerArgRes.isInvalid())
520 return true;
521 PointerArg = PointerArgRes.take();
522
523 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
524
525 // In general, we allow ints, floats and pointers to be loaded and stored.
526 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
527 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
529 << PointerArg->getType() << PointerArg->getSourceRange();
530 return true;
531 }
532
533 // But ARM doesn't have instructions to deal with 128-bit versions.
534 if (Context.getTypeSize(ValType) > 64) {
535 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
536 << PointerArg->getType() << PointerArg->getSourceRange();
537 return true;
538 }
539
540 switch (ValType.getObjCLifetime()) {
541 case Qualifiers::OCL_None:
542 case Qualifiers::OCL_ExplicitNone:
543 // okay
544 break;
545
546 case Qualifiers::OCL_Weak:
547 case Qualifiers::OCL_Strong:
548 case Qualifiers::OCL_Autoreleasing:
549 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
550 << ValType << PointerArg->getSourceRange();
551 return true;
552 }
553
554
555 if (IsLdrex) {
556 TheCall->setType(ValType);
557 return false;
558 }
559
560 // Initialize the argument to be stored.
561 ExprResult ValArg = TheCall->getArg(0);
562 InitializedEntity Entity = InitializedEntity::InitializeParameter(
563 Context, ValType, /*consume*/ false);
564 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
565 if (ValArg.isInvalid())
566 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000567 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000568
569 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
570 // but the custom checker bypasses all default analysis.
571 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000572 return false;
573}
574
Nate Begeman4904e322010-06-08 02:47:44 +0000575bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000576 llvm::APSInt Result;
577
Tim Northover6aacd492013-07-16 09:47:53 +0000578 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
579 BuiltinID == ARM::BI__builtin_arm_strex) {
580 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
581 }
582
Richard Smith7d6d47b2012-08-14 01:28:02 +0000583 uint64_t mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000584 unsigned TV = 0;
Bob Wilson89d14242011-11-16 21:32:23 +0000585 int PtrArgNum = -1;
Bob Wilsone4d77232011-11-08 05:04:11 +0000586 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000587 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000588#define GET_NEON_OVERLOAD_CHECK
589#include "clang/Basic/arm_neon.inc"
590#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000591 }
592
Nate Begemand773fe62010-06-13 04:47:52 +0000593 // For NEON intrinsics which are overloaded on vector element type, validate
594 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000595 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000596 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000597 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000598 return true;
599
Bob Wilson98bc98c2011-11-08 01:16:11 +0000600 TV = Result.getLimitedValue(64);
Richard Smith7d6d47b2012-08-14 01:28:02 +0000601 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000602 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000603 << TheCall->getArg(ImmArg)->getSourceRange();
604 }
605
Bob Wilson89d14242011-11-16 21:32:23 +0000606 if (PtrArgNum >= 0) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000607 // Check that pointer arguments have the specified type.
Bob Wilson89d14242011-11-16 21:32:23 +0000608 Expr *Arg = TheCall->getArg(PtrArgNum);
609 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
610 Arg = ICE->getSubExpr();
611 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
612 QualType RHSTy = RHS.get()->getType();
Kevin Qincaac85e2013-11-14 03:29:16 +0000613 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
Bob Wilson89d14242011-11-16 21:32:23 +0000614 if (HasConstPtr)
615 EltTy = EltTy.withConst();
616 QualType LHSTy = Context.getPointerType(EltTy);
617 AssignConvertType ConvTy;
618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
619 if (RHS.isInvalid())
620 return true;
621 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
622 RHS.get(), AA_Assigning))
623 return true;
Nate Begemand773fe62010-06-13 04:47:52 +0000624 }
Nico Weber0e6daef2013-12-26 23:38:39 +0000625
Nate Begemand773fe62010-06-13 04:47:52 +0000626 // For NEON intrinsics which take an immediate value as part of the
627 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000628 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000629 switch (BuiltinID) {
630 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000631 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
632 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000633 case ARM::BI__builtin_arm_vcvtr_f:
634 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000635 case ARM::BI__builtin_arm_dmb:
636 case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000637#define GET_NEON_IMMEDIATE_CHECK
638#include "clang/Basic/arm_neon.inc"
639#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000640 };
641
Douglas Gregor98c3cfc2012-06-29 01:05:22 +0000642 // We can't check the value of a dependent argument.
643 if (TheCall->getArg(i)->isTypeDependent() ||
644 TheCall->getArg(i)->isValueDependent())
645 return false;
646
Nate Begeman91e1fea2010-06-14 05:21:25 +0000647 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000648 if (SemaBuiltinConstantArg(TheCall, i, Result))
649 return true;
650
Nate Begeman91e1fea2010-06-14 05:21:25 +0000651 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000652 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000653 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000654 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000655 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000656
Nate Begemanf568b072010-08-03 21:32:34 +0000657 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000658 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000659}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000660
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000661bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
662 unsigned i = 0, l = 0, u = 0;
663 switch (BuiltinID) {
664 default: return false;
665 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
666 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000667 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
668 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
669 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
670 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
671 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000672 };
673
674 // We can't check the value of a dependent argument.
675 if (TheCall->getArg(i)->isTypeDependent() ||
676 TheCall->getArg(i)->isValueDependent())
677 return false;
678
679 // Check that the immediate argument is actually a constant.
680 llvm::APSInt Result;
681 if (SemaBuiltinConstantArg(TheCall, i, Result))
682 return true;
683
684 // Range check against the upper/lower values for this instruction.
685 unsigned Val = Result.getZExtValue();
686 if (Val < l || Val > u)
687 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
688 << l << u << TheCall->getArg(i)->getSourceRange();
689
690 return false;
691}
692
Richard Smith55ce3522012-06-25 20:30:08 +0000693/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
694/// parameter with the FormatAttr's correct format_idx and firstDataArg.
695/// Returns true when the format fits the function and the FormatStringInfo has
696/// been populated.
697bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
698 FormatStringInfo *FSI) {
699 FSI->HasVAListArg = Format->getFirstArg() == 0;
700 FSI->FormatIdx = Format->getFormatIdx() - 1;
701 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000702
Richard Smith55ce3522012-06-25 20:30:08 +0000703 // The way the format attribute works in GCC, the implicit this argument
704 // of member functions is counted. However, it doesn't appear in our own
705 // lists, so decrement format_idx in that case.
706 if (IsCXXMember) {
707 if(FSI->FormatIdx == 0)
708 return false;
709 --FSI->FormatIdx;
710 if (FSI->FirstDataArg != 0)
711 --FSI->FirstDataArg;
712 }
713 return true;
714}
Mike Stump11289f42009-09-09 15:08:12 +0000715
Ted Kremeneka146db32014-01-17 06:24:47 +0000716static void CheckNonNullArgument(Sema &S,
717 const Expr *ArgExpr,
718 SourceLocation CallSiteLoc) {
719 // As a special case, transparent unions initialized with zero are
720 // considered null for the purposes of the nonnull attribute.
721 if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
722 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
723 if (const CompoundLiteralExpr *CLE =
724 dyn_cast<CompoundLiteralExpr>(ArgExpr))
725 if (const InitListExpr *ILE =
726 dyn_cast<InitListExpr>(CLE->getInitializer()))
727 ArgExpr = ILE->getInit(0);
728 }
729
730 bool Result;
731 if (ArgExpr->EvaluateAsBooleanCondition(Result, S.Context) && !Result)
732 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
733}
734
Ted Kremenek2bc73332014-01-17 06:24:43 +0000735static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +0000736 const NamedDecl *FDecl,
Ted Kremenek2bc73332014-01-17 06:24:43 +0000737 const Expr * const *ExprArgs,
738 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +0000739 // Check the attributes attached to the method/function itself.
Ted Kremeneka146db32014-01-17 06:24:47 +0000740 for (specific_attr_iterator<NonNullAttr>
741 I = FDecl->specific_attr_begin<NonNullAttr>(),
742 E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I) {
Ted Kremenek2bc73332014-01-17 06:24:43 +0000743
Ted Kremeneka146db32014-01-17 06:24:47 +0000744 const NonNullAttr *NonNull = *I;
745 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
746 e = NonNull->args_end();
747 i != e; ++i) {
748 CheckNonNullArgument(S, ExprArgs[*i], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +0000749 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000750 }
Ted Kremenek9aedc152014-01-17 06:24:56 +0000751
752 // Check the attributes on the parameters.
753 ArrayRef<ParmVarDecl*> parms;
754 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
755 parms = FD->parameters();
756 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
757 parms = MD->parameters();
758
759 unsigned argIndex = 0;
760 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
761 I != E; ++I, ++argIndex) {
762 const ParmVarDecl *PVD = *I;
763 if (PVD->hasAttr<NonNullAttr>())
764 CheckNonNullArgument(S, ExprArgs[argIndex], CallSiteLoc);
765 }
Ted Kremenek2bc73332014-01-17 06:24:43 +0000766}
767
Richard Smith55ce3522012-06-25 20:30:08 +0000768/// Handles the checks for format strings, non-POD arguments to vararg
769/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +0000770void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
771 unsigned NumParams, bool IsMemberFunction,
772 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +0000773 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +0000774 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +0000775 if (CurContext->isDependentContext())
776 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000777
Ted Kremenekb8176da2010-09-09 04:33:05 +0000778 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +0000779 llvm::SmallBitVector CheckedVarArgs;
780 if (FDecl) {
Richard Trieu41bc0992013-06-22 00:20:41 +0000781 for (specific_attr_iterator<FormatAttr>
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000782 I = FDecl->specific_attr_begin<FormatAttr>(),
783 E = FDecl->specific_attr_end<FormatAttr>();
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000784 I != E; ++I) {
785 // Only create vector if there are format attributes.
786 CheckedVarArgs.resize(Args.size());
787
Benjamin Kramerf62e81d2013-08-08 11:08:26 +0000788 CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
789 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +0000790 }
Richard Smithd7293d72013-08-05 18:49:43 +0000791 }
Richard Smith55ce3522012-06-25 20:30:08 +0000792
793 // Refuse POD arguments that weren't caught by the format string
794 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +0000795 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000796 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000797 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +0000798 if (const Expr *Arg = Args[ArgIdx]) {
799 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
800 checkVariadicArgument(Arg, CallType);
801 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +0000802 }
Richard Smithd7293d72013-08-05 18:49:43 +0000803 }
Mike Stump11289f42009-09-09 15:08:12 +0000804
Richard Trieu41bc0992013-06-22 00:20:41 +0000805 if (FDecl) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000806 CheckNonNullArguments(*this, FDecl, Args.data(), Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000807
Richard Trieu41bc0992013-06-22 00:20:41 +0000808 // Type safety checking.
809 for (specific_attr_iterator<ArgumentWithTypeTagAttr>
810 i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
811 e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
812 i != e; ++i) {
813 CheckArgumentWithTypeTag(*i, Args.data());
814 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +0000815 }
Richard Smith55ce3522012-06-25 20:30:08 +0000816}
817
818/// CheckConstructorCall - Check a constructor call for correctness and safety
819/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +0000820void Sema::CheckConstructorCall(FunctionDecl *FDecl,
821 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +0000822 const FunctionProtoType *Proto,
823 SourceLocation Loc) {
824 VariadicCallType CallType =
825 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +0000826 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +0000827 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
828}
829
830/// CheckFunctionCall - Check a direct function call for various correctness
831/// and safety properties not strictly enforced by the C type system.
832bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
833 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000834 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
835 isa<CXXMethodDecl>(FDecl);
836 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
837 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +0000838 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
839 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000840 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +0000841 Expr** Args = TheCall->getArgs();
842 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +0000843 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +0000844 // If this is a call to a member operator, hide the first argument
845 // from checkCall.
846 // FIXME: Our choice of AST representation here is less than ideal.
847 ++Args;
848 --NumArgs;
849 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000850 checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +0000851 IsMemberFunction, TheCall->getRParenLoc(),
852 TheCall->getCallee()->getSourceRange(), CallType);
853
854 IdentifierInfo *FnInfo = FDecl->getIdentifier();
855 // None of the checks below are needed for functions that don't have
856 // simple names (e.g., C++ conversion functions).
857 if (!FnInfo)
858 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000859
Anna Zaks22122702012-01-17 00:37:07 +0000860 unsigned CMId = FDecl->getMemoryFunctionKind();
861 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +0000862 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +0000863
Anna Zaks201d4892012-01-13 21:52:01 +0000864 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +0000865 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +0000866 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +0000867 else if (CMId == Builtin::BIstrncat)
868 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +0000869 else
Anna Zaks22122702012-01-17 00:37:07 +0000870 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000871
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000872 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000873}
874
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000875bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000876 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +0000877 VariadicCallType CallType =
878 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000879
Dmitri Gribenko1debc462013-05-05 19:42:09 +0000880 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +0000881 /*IsMemberFunction=*/false,
882 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +0000883
884 return false;
885}
886
Richard Trieu664c4c62013-06-20 21:03:13 +0000887bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
888 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000889 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
890 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000891 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000892
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000893 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +0000894 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000895 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000896
Richard Trieu664c4c62013-06-20 21:03:13 +0000897 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +0000898 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +0000899 CallType = VariadicDoesNotApply;
900 } else if (Ty->isBlockPointerType()) {
901 CallType = VariadicBlock;
902 } else { // Ty->isFunctionPointerType()
903 CallType = VariadicFunction;
904 }
Alp Toker9cacbab2014-01-20 20:26:09 +0000905 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000906
Alp Toker9cacbab2014-01-20 20:26:09 +0000907 checkCall(NDecl, llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
908 TheCall->getNumArgs()),
909 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +0000910 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +0000911
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000913}
914
Richard Trieu41bc0992013-06-22 00:20:41 +0000915/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
916/// such as function pointers returned from functions.
917bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
918 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
919 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +0000920 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +0000921
Alp Toker9cacbab2014-01-20 20:26:09 +0000922 checkCall(/*FDecl=*/0, llvm::makeArrayRef<const Expr *>(
923 TheCall->getArgs(), TheCall->getNumArgs()),
924 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +0000925 TheCall->getCallee()->getSourceRange(), CallType);
926
927 return false;
928}
929
Richard Smithfeea8832012-04-12 05:08:17 +0000930ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
931 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000932 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
933 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000934
Richard Smithfeea8832012-04-12 05:08:17 +0000935 // All these operations take one of the following forms:
936 enum {
937 // C __c11_atomic_init(A *, C)
938 Init,
939 // C __c11_atomic_load(A *, int)
940 Load,
941 // void __atomic_load(A *, CP, int)
942 Copy,
943 // C __c11_atomic_add(A *, M, int)
944 Arithmetic,
945 // C __atomic_exchange_n(A *, CP, int)
946 Xchg,
947 // void __atomic_exchange(A *, C *, CP, int)
948 GNUXchg,
949 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
950 C11CmpXchg,
951 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
952 GNUCmpXchg
953 } Form = Init;
954 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
955 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
956 // where:
957 // C is an appropriate type,
958 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
959 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
960 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
961 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000962
Richard Smithfeea8832012-04-12 05:08:17 +0000963 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
964 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
965 && "need to update code for modified C11 atomics");
966 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
967 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
968 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
969 Op == AtomicExpr::AO__atomic_store_n ||
970 Op == AtomicExpr::AO__atomic_exchange_n ||
971 Op == AtomicExpr::AO__atomic_compare_exchange_n;
972 bool IsAddSub = false;
973
974 switch (Op) {
975 case AtomicExpr::AO__c11_atomic_init:
976 Form = Init;
977 break;
978
979 case AtomicExpr::AO__c11_atomic_load:
980 case AtomicExpr::AO__atomic_load_n:
981 Form = Load;
982 break;
983
984 case AtomicExpr::AO__c11_atomic_store:
985 case AtomicExpr::AO__atomic_load:
986 case AtomicExpr::AO__atomic_store:
987 case AtomicExpr::AO__atomic_store_n:
988 Form = Copy;
989 break;
990
991 case AtomicExpr::AO__c11_atomic_fetch_add:
992 case AtomicExpr::AO__c11_atomic_fetch_sub:
993 case AtomicExpr::AO__atomic_fetch_add:
994 case AtomicExpr::AO__atomic_fetch_sub:
995 case AtomicExpr::AO__atomic_add_fetch:
996 case AtomicExpr::AO__atomic_sub_fetch:
997 IsAddSub = true;
998 // Fall through.
999 case AtomicExpr::AO__c11_atomic_fetch_and:
1000 case AtomicExpr::AO__c11_atomic_fetch_or:
1001 case AtomicExpr::AO__c11_atomic_fetch_xor:
1002 case AtomicExpr::AO__atomic_fetch_and:
1003 case AtomicExpr::AO__atomic_fetch_or:
1004 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001005 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001006 case AtomicExpr::AO__atomic_and_fetch:
1007 case AtomicExpr::AO__atomic_or_fetch:
1008 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001009 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001010 Form = Arithmetic;
1011 break;
1012
1013 case AtomicExpr::AO__c11_atomic_exchange:
1014 case AtomicExpr::AO__atomic_exchange_n:
1015 Form = Xchg;
1016 break;
1017
1018 case AtomicExpr::AO__atomic_exchange:
1019 Form = GNUXchg;
1020 break;
1021
1022 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1023 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1024 Form = C11CmpXchg;
1025 break;
1026
1027 case AtomicExpr::AO__atomic_compare_exchange:
1028 case AtomicExpr::AO__atomic_compare_exchange_n:
1029 Form = GNUCmpXchg;
1030 break;
1031 }
1032
1033 // Check we have the right number of arguments.
1034 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001035 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001036 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001037 << TheCall->getCallee()->getSourceRange();
1038 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001039 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1040 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001041 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001042 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001043 << TheCall->getCallee()->getSourceRange();
1044 return ExprError();
1045 }
1046
Richard Smithfeea8832012-04-12 05:08:17 +00001047 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001048 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001049 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1050 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1051 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001052 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001053 << Ptr->getType() << Ptr->getSourceRange();
1054 return ExprError();
1055 }
1056
Richard Smithfeea8832012-04-12 05:08:17 +00001057 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1058 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1059 QualType ValType = AtomTy; // 'C'
1060 if (IsC11) {
1061 if (!AtomTy->isAtomicType()) {
1062 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1063 << Ptr->getType() << Ptr->getSourceRange();
1064 return ExprError();
1065 }
Richard Smithe00921a2012-09-15 06:09:58 +00001066 if (AtomTy.isConstQualified()) {
1067 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1068 << Ptr->getType() << Ptr->getSourceRange();
1069 return ExprError();
1070 }
Richard Smithfeea8832012-04-12 05:08:17 +00001071 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001072 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001073
Richard Smithfeea8832012-04-12 05:08:17 +00001074 // For an arithmetic operation, the implied arithmetic must be well-formed.
1075 if (Form == Arithmetic) {
1076 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1077 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1078 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1079 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1080 return ExprError();
1081 }
1082 if (!IsAddSub && !ValType->isIntegerType()) {
1083 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1084 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1085 return ExprError();
1086 }
1087 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1088 // For __atomic_*_n operations, the value type must be a scalar integral or
1089 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001090 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001091 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1092 return ExprError();
1093 }
1094
Eli Friedmanaa769812013-09-11 03:49:34 +00001095 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1096 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001097 // For GNU atomics, require a trivially-copyable type. This is not part of
1098 // the GNU atomics specification, but we enforce it for sanity.
1099 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001100 << Ptr->getType() << Ptr->getSourceRange();
1101 return ExprError();
1102 }
1103
Richard Smithfeea8832012-04-12 05:08:17 +00001104 // FIXME: For any builtin other than a load, the ValType must not be
1105 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001106
1107 switch (ValType.getObjCLifetime()) {
1108 case Qualifiers::OCL_None:
1109 case Qualifiers::OCL_ExplicitNone:
1110 // okay
1111 break;
1112
1113 case Qualifiers::OCL_Weak:
1114 case Qualifiers::OCL_Strong:
1115 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001116 // FIXME: Can this happen? By this point, ValType should be known
1117 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001118 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1119 << ValType << Ptr->getSourceRange();
1120 return ExprError();
1121 }
1122
1123 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001124 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001125 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001126 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001127 ResultType = Context.BoolTy;
1128
Richard Smithfeea8832012-04-12 05:08:17 +00001129 // The type of a parameter passed 'by value'. In the GNU atomics, such
1130 // arguments are actually passed as pointers.
1131 QualType ByValType = ValType; // 'CP'
1132 if (!IsC11 && !IsN)
1133 ByValType = Ptr->getType();
1134
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001135 // The first argument --- the pointer --- has a fixed type; we
1136 // deduce the types of the rest of the arguments accordingly. Walk
1137 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001138 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001139 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001140 if (i < NumVals[Form] + 1) {
1141 switch (i) {
1142 case 1:
1143 // The second argument is the non-atomic operand. For arithmetic, this
1144 // is always passed by value, and for a compare_exchange it is always
1145 // passed by address. For the rest, GNU uses by-address and C11 uses
1146 // by-value.
1147 assert(Form != Load);
1148 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1149 Ty = ValType;
1150 else if (Form == Copy || Form == Xchg)
1151 Ty = ByValType;
1152 else if (Form == Arithmetic)
1153 Ty = Context.getPointerDiffType();
1154 else
1155 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1156 break;
1157 case 2:
1158 // The third argument to compare_exchange / GNU exchange is a
1159 // (pointer to a) desired value.
1160 Ty = ByValType;
1161 break;
1162 case 3:
1163 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1164 Ty = Context.BoolTy;
1165 break;
1166 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001167 } else {
1168 // The order(s) are always converted to int.
1169 Ty = Context.IntTy;
1170 }
Richard Smithfeea8832012-04-12 05:08:17 +00001171
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001172 InitializedEntity Entity =
1173 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001174 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001175 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1176 if (Arg.isInvalid())
1177 return true;
1178 TheCall->setArg(i, Arg.get());
1179 }
1180
Richard Smithfeea8832012-04-12 05:08:17 +00001181 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001182 SmallVector<Expr*, 5> SubExprs;
1183 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001184 switch (Form) {
1185 case Init:
1186 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001187 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001188 break;
1189 case Load:
1190 SubExprs.push_back(TheCall->getArg(1)); // Order
1191 break;
1192 case Copy:
1193 case Arithmetic:
1194 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001195 SubExprs.push_back(TheCall->getArg(2)); // Order
1196 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001197 break;
1198 case GNUXchg:
1199 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1200 SubExprs.push_back(TheCall->getArg(3)); // Order
1201 SubExprs.push_back(TheCall->getArg(1)); // Val1
1202 SubExprs.push_back(TheCall->getArg(2)); // Val2
1203 break;
1204 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001205 SubExprs.push_back(TheCall->getArg(3)); // Order
1206 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001207 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001208 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001209 break;
1210 case GNUCmpXchg:
1211 SubExprs.push_back(TheCall->getArg(4)); // Order
1212 SubExprs.push_back(TheCall->getArg(1)); // Val1
1213 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1214 SubExprs.push_back(TheCall->getArg(2)); // Val2
1215 SubExprs.push_back(TheCall->getArg(3)); // Weak
1216 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001217 }
Fariborz Jahanian615de762013-05-28 17:37:39 +00001218
1219 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1220 SubExprs, ResultType, Op,
1221 TheCall->getRParenLoc());
1222
1223 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1224 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1225 Context.AtomicUsesUnsupportedLibcall(AE))
1226 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1227 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001228
Fariborz Jahanian615de762013-05-28 17:37:39 +00001229 return Owned(AE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001230}
1231
1232
John McCall29ad95b2011-08-27 01:09:30 +00001233/// checkBuiltinArgument - Given a call to a builtin function, perform
1234/// normal type-checking on the given argument, updating the call in
1235/// place. This is useful when a builtin function requires custom
1236/// type-checking for some of its arguments but not necessarily all of
1237/// them.
1238///
1239/// Returns true on error.
1240static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1241 FunctionDecl *Fn = E->getDirectCallee();
1242 assert(Fn && "builtin call without direct callee!");
1243
1244 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1245 InitializedEntity Entity =
1246 InitializedEntity::InitializeParameter(S.Context, Param);
1247
1248 ExprResult Arg = E->getArg(0);
1249 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1250 if (Arg.isInvalid())
1251 return true;
1252
1253 E->setArg(ArgIndex, Arg.take());
1254 return false;
1255}
1256
Chris Lattnerdc046542009-05-08 06:58:22 +00001257/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1258/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1259/// type of its first argument. The main ActOnCallExpr routines have already
1260/// promoted the types of arguments because all of these calls are prototyped as
1261/// void(...).
1262///
1263/// This function goes through and does final semantic checking for these
1264/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001265ExprResult
1266Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001267 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001268 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1269 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1270
1271 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001272 if (TheCall->getNumArgs() < 1) {
1273 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1274 << 0 << 1 << TheCall->getNumArgs()
1275 << TheCall->getCallee()->getSourceRange();
1276 return ExprError();
1277 }
Mike Stump11289f42009-09-09 15:08:12 +00001278
Chris Lattnerdc046542009-05-08 06:58:22 +00001279 // Inspect the first argument of the atomic builtin. This should always be
1280 // a pointer type, whose element is an integral scalar or pointer type.
1281 // Because it is a pointer type, we don't have to worry about any implicit
1282 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001283 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001284 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001285 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1286 if (FirstArgResult.isInvalid())
1287 return ExprError();
1288 FirstArg = FirstArgResult.take();
1289 TheCall->setArg(0, FirstArg);
1290
John McCall31168b02011-06-15 23:02:42 +00001291 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1292 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001293 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1294 << FirstArg->getType() << FirstArg->getSourceRange();
1295 return ExprError();
1296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
John McCall31168b02011-06-15 23:02:42 +00001298 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001299 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001300 !ValType->isBlockPointerType()) {
1301 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1302 << FirstArg->getType() << FirstArg->getSourceRange();
1303 return ExprError();
1304 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001305
John McCall31168b02011-06-15 23:02:42 +00001306 switch (ValType.getObjCLifetime()) {
1307 case Qualifiers::OCL_None:
1308 case Qualifiers::OCL_ExplicitNone:
1309 // okay
1310 break;
1311
1312 case Qualifiers::OCL_Weak:
1313 case Qualifiers::OCL_Strong:
1314 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001315 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001316 << ValType << FirstArg->getSourceRange();
1317 return ExprError();
1318 }
1319
John McCallb50451a2011-10-05 07:41:44 +00001320 // Strip any qualifiers off ValType.
1321 ValType = ValType.getUnqualifiedType();
1322
Chandler Carruth3973af72010-07-18 20:54:12 +00001323 // The majority of builtins return a value, but a few have special return
1324 // types, so allow them to override appropriately below.
1325 QualType ResultType = ValType;
1326
Chris Lattnerdc046542009-05-08 06:58:22 +00001327 // We need to figure out which concrete builtin this maps onto. For example,
1328 // __sync_fetch_and_add with a 2 byte object turns into
1329 // __sync_fetch_and_add_2.
1330#define BUILTIN_ROW(x) \
1331 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1332 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Chris Lattnerdc046542009-05-08 06:58:22 +00001334 static const unsigned BuiltinIndices[][5] = {
1335 BUILTIN_ROW(__sync_fetch_and_add),
1336 BUILTIN_ROW(__sync_fetch_and_sub),
1337 BUILTIN_ROW(__sync_fetch_and_or),
1338 BUILTIN_ROW(__sync_fetch_and_and),
1339 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +00001340
Chris Lattnerdc046542009-05-08 06:58:22 +00001341 BUILTIN_ROW(__sync_add_and_fetch),
1342 BUILTIN_ROW(__sync_sub_and_fetch),
1343 BUILTIN_ROW(__sync_and_and_fetch),
1344 BUILTIN_ROW(__sync_or_and_fetch),
1345 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001346
Chris Lattnerdc046542009-05-08 06:58:22 +00001347 BUILTIN_ROW(__sync_val_compare_and_swap),
1348 BUILTIN_ROW(__sync_bool_compare_and_swap),
1349 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001350 BUILTIN_ROW(__sync_lock_release),
1351 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001352 };
Mike Stump11289f42009-09-09 15:08:12 +00001353#undef BUILTIN_ROW
1354
Chris Lattnerdc046542009-05-08 06:58:22 +00001355 // Determine the index of the size.
1356 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001357 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001358 case 1: SizeIndex = 0; break;
1359 case 2: SizeIndex = 1; break;
1360 case 4: SizeIndex = 2; break;
1361 case 8: SizeIndex = 3; break;
1362 case 16: SizeIndex = 4; break;
1363 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001364 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1365 << FirstArg->getType() << FirstArg->getSourceRange();
1366 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001367 }
Mike Stump11289f42009-09-09 15:08:12 +00001368
Chris Lattnerdc046542009-05-08 06:58:22 +00001369 // Each of these builtins has one pointer argument, followed by some number of
1370 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1371 // that we ignore. Find out which row of BuiltinIndices to read from as well
1372 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001373 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001374 unsigned BuiltinIndex, NumFixed = 1;
1375 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001376 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001377 case Builtin::BI__sync_fetch_and_add:
1378 case Builtin::BI__sync_fetch_and_add_1:
1379 case Builtin::BI__sync_fetch_and_add_2:
1380 case Builtin::BI__sync_fetch_and_add_4:
1381 case Builtin::BI__sync_fetch_and_add_8:
1382 case Builtin::BI__sync_fetch_and_add_16:
1383 BuiltinIndex = 0;
1384 break;
1385
1386 case Builtin::BI__sync_fetch_and_sub:
1387 case Builtin::BI__sync_fetch_and_sub_1:
1388 case Builtin::BI__sync_fetch_and_sub_2:
1389 case Builtin::BI__sync_fetch_and_sub_4:
1390 case Builtin::BI__sync_fetch_and_sub_8:
1391 case Builtin::BI__sync_fetch_and_sub_16:
1392 BuiltinIndex = 1;
1393 break;
1394
1395 case Builtin::BI__sync_fetch_and_or:
1396 case Builtin::BI__sync_fetch_and_or_1:
1397 case Builtin::BI__sync_fetch_and_or_2:
1398 case Builtin::BI__sync_fetch_and_or_4:
1399 case Builtin::BI__sync_fetch_and_or_8:
1400 case Builtin::BI__sync_fetch_and_or_16:
1401 BuiltinIndex = 2;
1402 break;
1403
1404 case Builtin::BI__sync_fetch_and_and:
1405 case Builtin::BI__sync_fetch_and_and_1:
1406 case Builtin::BI__sync_fetch_and_and_2:
1407 case Builtin::BI__sync_fetch_and_and_4:
1408 case Builtin::BI__sync_fetch_and_and_8:
1409 case Builtin::BI__sync_fetch_and_and_16:
1410 BuiltinIndex = 3;
1411 break;
Mike Stump11289f42009-09-09 15:08:12 +00001412
Douglas Gregor73722482011-11-28 16:30:08 +00001413 case Builtin::BI__sync_fetch_and_xor:
1414 case Builtin::BI__sync_fetch_and_xor_1:
1415 case Builtin::BI__sync_fetch_and_xor_2:
1416 case Builtin::BI__sync_fetch_and_xor_4:
1417 case Builtin::BI__sync_fetch_and_xor_8:
1418 case Builtin::BI__sync_fetch_and_xor_16:
1419 BuiltinIndex = 4;
1420 break;
1421
1422 case Builtin::BI__sync_add_and_fetch:
1423 case Builtin::BI__sync_add_and_fetch_1:
1424 case Builtin::BI__sync_add_and_fetch_2:
1425 case Builtin::BI__sync_add_and_fetch_4:
1426 case Builtin::BI__sync_add_and_fetch_8:
1427 case Builtin::BI__sync_add_and_fetch_16:
1428 BuiltinIndex = 5;
1429 break;
1430
1431 case Builtin::BI__sync_sub_and_fetch:
1432 case Builtin::BI__sync_sub_and_fetch_1:
1433 case Builtin::BI__sync_sub_and_fetch_2:
1434 case Builtin::BI__sync_sub_and_fetch_4:
1435 case Builtin::BI__sync_sub_and_fetch_8:
1436 case Builtin::BI__sync_sub_and_fetch_16:
1437 BuiltinIndex = 6;
1438 break;
1439
1440 case Builtin::BI__sync_and_and_fetch:
1441 case Builtin::BI__sync_and_and_fetch_1:
1442 case Builtin::BI__sync_and_and_fetch_2:
1443 case Builtin::BI__sync_and_and_fetch_4:
1444 case Builtin::BI__sync_and_and_fetch_8:
1445 case Builtin::BI__sync_and_and_fetch_16:
1446 BuiltinIndex = 7;
1447 break;
1448
1449 case Builtin::BI__sync_or_and_fetch:
1450 case Builtin::BI__sync_or_and_fetch_1:
1451 case Builtin::BI__sync_or_and_fetch_2:
1452 case Builtin::BI__sync_or_and_fetch_4:
1453 case Builtin::BI__sync_or_and_fetch_8:
1454 case Builtin::BI__sync_or_and_fetch_16:
1455 BuiltinIndex = 8;
1456 break;
1457
1458 case Builtin::BI__sync_xor_and_fetch:
1459 case Builtin::BI__sync_xor_and_fetch_1:
1460 case Builtin::BI__sync_xor_and_fetch_2:
1461 case Builtin::BI__sync_xor_and_fetch_4:
1462 case Builtin::BI__sync_xor_and_fetch_8:
1463 case Builtin::BI__sync_xor_and_fetch_16:
1464 BuiltinIndex = 9;
1465 break;
Mike Stump11289f42009-09-09 15:08:12 +00001466
Chris Lattnerdc046542009-05-08 06:58:22 +00001467 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001468 case Builtin::BI__sync_val_compare_and_swap_1:
1469 case Builtin::BI__sync_val_compare_and_swap_2:
1470 case Builtin::BI__sync_val_compare_and_swap_4:
1471 case Builtin::BI__sync_val_compare_and_swap_8:
1472 case Builtin::BI__sync_val_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001473 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +00001474 NumFixed = 2;
1475 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001476
Chris Lattnerdc046542009-05-08 06:58:22 +00001477 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001478 case Builtin::BI__sync_bool_compare_and_swap_1:
1479 case Builtin::BI__sync_bool_compare_and_swap_2:
1480 case Builtin::BI__sync_bool_compare_and_swap_4:
1481 case Builtin::BI__sync_bool_compare_and_swap_8:
1482 case Builtin::BI__sync_bool_compare_and_swap_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001483 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +00001484 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001485 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001486 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001487
1488 case Builtin::BI__sync_lock_test_and_set:
1489 case Builtin::BI__sync_lock_test_and_set_1:
1490 case Builtin::BI__sync_lock_test_and_set_2:
1491 case Builtin::BI__sync_lock_test_and_set_4:
1492 case Builtin::BI__sync_lock_test_and_set_8:
1493 case Builtin::BI__sync_lock_test_and_set_16:
1494 BuiltinIndex = 12;
1495 break;
1496
Chris Lattnerdc046542009-05-08 06:58:22 +00001497 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001498 case Builtin::BI__sync_lock_release_1:
1499 case Builtin::BI__sync_lock_release_2:
1500 case Builtin::BI__sync_lock_release_4:
1501 case Builtin::BI__sync_lock_release_8:
1502 case Builtin::BI__sync_lock_release_16:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +00001503 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001504 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001505 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001506 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001507
1508 case Builtin::BI__sync_swap:
1509 case Builtin::BI__sync_swap_1:
1510 case Builtin::BI__sync_swap_2:
1511 case Builtin::BI__sync_swap_4:
1512 case Builtin::BI__sync_swap_8:
1513 case Builtin::BI__sync_swap_16:
1514 BuiltinIndex = 14;
1515 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Chris Lattnerdc046542009-05-08 06:58:22 +00001518 // Now that we know how many fixed arguments we expect, first check that we
1519 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001520 if (TheCall->getNumArgs() < 1+NumFixed) {
1521 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1522 << 0 << 1+NumFixed << TheCall->getNumArgs()
1523 << TheCall->getCallee()->getSourceRange();
1524 return ExprError();
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Chris Lattner5b9241b2009-05-08 15:36:58 +00001527 // Get the decl for the concrete builtin from this, we can tell what the
1528 // concrete integer type we should convert to is.
1529 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1530 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001531 FunctionDecl *NewBuiltinDecl;
1532 if (NewBuiltinID == BuiltinID)
1533 NewBuiltinDecl = FDecl;
1534 else {
1535 // Perform builtin lookup to avoid redeclaring it.
1536 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1537 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1538 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1539 assert(Res.getFoundDecl());
1540 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1541 if (NewBuiltinDecl == 0)
1542 return ExprError();
1543 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001544
John McCallcf142162010-08-07 06:22:56 +00001545 // The first argument --- the pointer --- has a fixed type; we
1546 // deduce the types of the rest of the arguments accordingly. Walk
1547 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001548 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001549 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001550
Chris Lattnerdc046542009-05-08 06:58:22 +00001551 // GCC does an implicit conversion to the pointer or integer ValType. This
1552 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001553 // Initialize the argument.
1554 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1555 ValType, /*consume*/ false);
1556 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001557 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001558 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001559
Chris Lattnerdc046542009-05-08 06:58:22 +00001560 // Okay, we have something that *can* be converted to the right type. Check
1561 // to see if there is a potentially weird extension going on here. This can
1562 // happen when you do an atomic operation on something like an char* and
1563 // pass in 42. The 42 gets converted to char. This is even more strange
1564 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001565 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +00001566 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +00001567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001569 ASTContext& Context = this->getASTContext();
1570
1571 // Create a new DeclRefExpr to refer to the new decl.
1572 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1573 Context,
1574 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001575 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001576 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001577 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001578 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001579 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001580 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001581
Chris Lattnerdc046542009-05-08 06:58:22 +00001582 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001583 // FIXME: This loses syntactic information.
1584 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1585 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1586 CK_BuiltinFnToFnPtr);
John Wiegley01296292011-04-08 18:41:53 +00001587 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +00001588
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001589 // Change the result type of the call to match the original value type. This
1590 // is arbitrary, but the codegen for these builtins ins design to handle it
1591 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001592 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001593
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001594 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001595}
1596
Chris Lattner6436fb62009-02-18 06:01:06 +00001597/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001598/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001599/// Note: It might also make sense to do the UTF-16 conversion here (would
1600/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00001601bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00001602 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00001603 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1604
Douglas Gregorfb65e592011-07-27 05:40:30 +00001605 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001606 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1607 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00001608 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00001609 }
Mike Stump11289f42009-09-09 15:08:12 +00001610
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001611 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001612 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001613 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001614 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00001615 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00001616 UTF16 *ToPtr = &ToBuf[0];
1617
1618 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1619 &ToPtr, ToPtr + NumBytes,
1620 strictConversion);
1621 // Check for conversion failure.
1622 if (Result != conversionOK)
1623 Diag(Arg->getLocStart(),
1624 diag::warn_cfstring_truncated) << Arg->getSourceRange();
1625 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00001626 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001627}
1628
Chris Lattnere202e6a2007-12-20 00:05:45 +00001629/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1630/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00001631bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1632 Expr *Fn = TheCall->getCallee();
1633 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00001634 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001635 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001636 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1637 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00001638 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001639 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00001640 return true;
1641 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001642
1643 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00001644 return Diag(TheCall->getLocEnd(),
1645 diag::err_typecheck_call_too_few_args_at_least)
1646 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00001647 }
1648
John McCall29ad95b2011-08-27 01:09:30 +00001649 // Type-check the first argument normally.
1650 if (checkBuiltinArgument(*this, TheCall, 0))
1651 return true;
1652
Chris Lattnere202e6a2007-12-20 00:05:45 +00001653 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00001654 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00001655 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00001656 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00001657 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00001658 else if (FunctionDecl *FD = getCurFunctionDecl())
1659 isVariadic = FD->isVariadic();
1660 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001661 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00001662
Chris Lattnere202e6a2007-12-20 00:05:45 +00001663 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001664 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1665 return true;
1666 }
Mike Stump11289f42009-09-09 15:08:12 +00001667
Chris Lattner43be2e62007-12-19 23:59:04 +00001668 // Verify that the second argument to the builtin is the last argument of the
1669 // current function or method.
1670 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00001671 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001672
Nico Weber9eea7642013-05-24 23:31:57 +00001673 // These are valid if SecondArgIsLastNamedArgument is false after the next
1674 // block.
1675 QualType Type;
1676 SourceLocation ParamLoc;
1677
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001678 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1679 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00001680 // FIXME: This isn't correct for methods (results in bogus warning).
1681 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00001682 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00001683 if (CurBlock)
1684 LastArg = *(CurBlock->TheDecl->param_end()-1);
1685 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00001686 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001687 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00001688 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00001689 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00001690
1691 Type = PV->getType();
1692 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00001693 }
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695
Chris Lattner43be2e62007-12-19 23:59:04 +00001696 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00001697 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001698 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00001699 else if (Type->isReferenceType()) {
1700 Diag(Arg->getLocStart(),
1701 diag::warn_va_start_of_reference_type_is_undefined);
1702 Diag(ParamLoc, diag::note_parameter_type) << Type;
1703 }
1704
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00001705 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00001706 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001707}
Chris Lattner43be2e62007-12-19 23:59:04 +00001708
Chris Lattner2da14fb2007-12-20 00:26:33 +00001709/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1710/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001711bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1712 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001713 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001714 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001715 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001716 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001717 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001718 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001719 << SourceRange(TheCall->getArg(2)->getLocStart(),
1720 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001721
John Wiegley01296292011-04-08 18:41:53 +00001722 ExprResult OrigArg0 = TheCall->getArg(0);
1723 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001724
Chris Lattner2da14fb2007-12-20 00:26:33 +00001725 // Do standard promotions between the two arguments, returning their common
1726 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001727 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001728 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1729 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001730
1731 // Make sure any conversions are pushed back into the call; this is
1732 // type safe since unordered compare builtins are declared as "_Bool
1733 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001734 TheCall->setArg(0, OrigArg0.get());
1735 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001736
John Wiegley01296292011-04-08 18:41:53 +00001737 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001738 return false;
1739
Chris Lattner2da14fb2007-12-20 00:26:33 +00001740 // If the common type isn't a real floating type, then the arguments were
1741 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00001742 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001743 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001744 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001745 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1746 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001747
Chris Lattner2da14fb2007-12-20 00:26:33 +00001748 return false;
1749}
1750
Benjamin Kramer634fc102010-02-15 22:42:31 +00001751/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1752/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001753/// to check everything. We expect the last argument to be a floating point
1754/// value.
1755bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1756 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001757 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001758 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001759 if (TheCall->getNumArgs() > NumArgs)
1760 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001761 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001762 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001763 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001764 (*(TheCall->arg_end()-1))->getLocEnd());
1765
Benjamin Kramer64aae502010-02-16 10:07:31 +00001766 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001767
Eli Friedman7e4faac2009-08-31 20:06:00 +00001768 if (OrigArg->isTypeDependent())
1769 return false;
1770
Chris Lattner68784ef2010-05-06 05:50:07 +00001771 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001772 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001773 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001774 diag::err_typecheck_call_invalid_unary_fp)
1775 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001776
Chris Lattner68784ef2010-05-06 05:50:07 +00001777 // If this is an implicit conversion from float -> double, remove it.
1778 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1779 Expr *CastArg = Cast->getSubExpr();
1780 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1781 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1782 "promotion from float to double is the only expected cast here");
1783 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001784 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00001785 }
1786 }
1787
Eli Friedman7e4faac2009-08-31 20:06:00 +00001788 return false;
1789}
1790
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001791/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1792// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001793ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001794 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001795 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001796 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00001797 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1798 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001799
Nate Begemana0110022010-06-08 00:16:34 +00001800 // Determine which of the following types of shufflevector we're checking:
1801 // 1) unary, vector mask: (lhs, mask)
1802 // 2) binary, vector mask: (lhs, rhs, mask)
1803 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1804 QualType resType = TheCall->getArg(0)->getType();
1805 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00001806
Douglas Gregorc25f7662009-05-19 22:10:17 +00001807 if (!TheCall->getArg(0)->isTypeDependent() &&
1808 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001809 QualType LHSType = TheCall->getArg(0)->getType();
1810 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00001811
Craig Topperbaca3892013-07-29 06:47:04 +00001812 if (!LHSType->isVectorType() || !RHSType->isVectorType())
1813 return ExprError(Diag(TheCall->getLocStart(),
1814 diag::err_shufflevector_non_vector)
1815 << SourceRange(TheCall->getArg(0)->getLocStart(),
1816 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001817
Nate Begemana0110022010-06-08 00:16:34 +00001818 numElements = LHSType->getAs<VectorType>()->getNumElements();
1819 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001820
Nate Begemana0110022010-06-08 00:16:34 +00001821 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1822 // with mask. If so, verify that RHS is an integer vector type with the
1823 // same number of elts as lhs.
1824 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00001825 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001826 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00001827 return ExprError(Diag(TheCall->getLocStart(),
1828 diag::err_shufflevector_incompatible_vector)
1829 << SourceRange(TheCall->getArg(1)->getLocStart(),
1830 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00001831 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00001832 return ExprError(Diag(TheCall->getLocStart(),
1833 diag::err_shufflevector_incompatible_vector)
1834 << SourceRange(TheCall->getArg(0)->getLocStart(),
1835 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00001836 } else if (numElements != numResElements) {
1837 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001838 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001839 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001840 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001841 }
1842
1843 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001844 if (TheCall->getArg(i)->isTypeDependent() ||
1845 TheCall->getArg(i)->isValueDependent())
1846 continue;
1847
Nate Begemana0110022010-06-08 00:16:34 +00001848 llvm::APSInt Result(32);
1849 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1850 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001851 diag::err_shufflevector_nonconstant_argument)
1852 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001853
Craig Topper50ad5b72013-08-03 17:40:38 +00001854 // Allow -1 which will be translated to undef in the IR.
1855 if (Result.isSigned() && Result.isAllOnesValue())
1856 continue;
1857
Chris Lattner7ab824e2008-08-10 02:05:13 +00001858 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001859 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00001860 diag::err_shufflevector_argument_too_large)
1861 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001862 }
1863
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001864 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001865
Chris Lattner7ab824e2008-08-10 02:05:13 +00001866 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001867 exprs.push_back(TheCall->getArg(i));
1868 TheCall->setArg(i, 0);
1869 }
1870
Benjamin Kramerc215e762012-08-24 11:54:20 +00001871 return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001872 TheCall->getCallee()->getLocStart(),
1873 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001874}
Chris Lattner43be2e62007-12-19 23:59:04 +00001875
Hal Finkelc4d7c822013-09-18 03:29:45 +00001876/// SemaConvertVectorExpr - Handle __builtin_convertvector
1877ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1878 SourceLocation BuiltinLoc,
1879 SourceLocation RParenLoc) {
1880 ExprValueKind VK = VK_RValue;
1881 ExprObjectKind OK = OK_Ordinary;
1882 QualType DstTy = TInfo->getType();
1883 QualType SrcTy = E->getType();
1884
1885 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1886 return ExprError(Diag(BuiltinLoc,
1887 diag::err_convertvector_non_vector)
1888 << E->getSourceRange());
1889 if (!DstTy->isVectorType() && !DstTy->isDependentType())
1890 return ExprError(Diag(BuiltinLoc,
1891 diag::err_convertvector_non_vector_type));
1892
1893 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1894 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1895 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1896 if (SrcElts != DstElts)
1897 return ExprError(Diag(BuiltinLoc,
1898 diag::err_convertvector_incompatible_vector)
1899 << E->getSourceRange());
1900 }
1901
1902 return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1903 BuiltinLoc, RParenLoc));
1904
1905}
1906
Daniel Dunbarb7257262008-07-21 22:59:13 +00001907/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1908// This is declared to take (const void*, ...) and can take two
1909// optional constant int args.
1910bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001911 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001912
Chris Lattner3b054132008-11-19 05:08:23 +00001913 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001914 return Diag(TheCall->getLocEnd(),
1915 diag::err_typecheck_call_too_many_args_at_most)
1916 << 0 /*function call*/ << 3 << NumArgs
1917 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001918
1919 // Argument 0 is checked for us and the remaining arguments must be
1920 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001921 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001922 Expr *Arg = TheCall->getArg(i);
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001923
1924 // We can't check the value of a dependent argument.
1925 if (Arg->isTypeDependent() || Arg->isValueDependent())
1926 continue;
1927
Eli Friedman5efba262009-12-04 00:30:06 +00001928 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001929 if (SemaBuiltinConstantArg(TheCall, i, Result))
1930 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001931
Daniel Dunbarb7257262008-07-21 22:59:13 +00001932 // FIXME: gcc issues a warning and rewrites these to 0. These
1933 // seems especially odd for the third argument since the default
1934 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001935 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001936 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001937 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001938 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001939 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001940 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001941 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001942 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001943 }
1944 }
1945
Chris Lattner3b054132008-11-19 05:08:23 +00001946 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001947}
1948
Eric Christopher8d0c6212010-04-17 02:26:23 +00001949/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1950/// TheCall is a constant expression.
1951bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1952 llvm::APSInt &Result) {
1953 Expr *Arg = TheCall->getArg(ArgNum);
1954 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1955 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1956
1957 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1958
1959 if (!Arg->isIntegerConstantExpr(Result, Context))
1960 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001961 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001962
Chris Lattnerd545ad12009-09-23 06:06:36 +00001963 return false;
1964}
1965
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001966/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1967/// int type). This simply type checks that type is one of the defined
1968/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001969// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001970bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001971 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00001972
1973 // We can't check the value of a dependent argument.
1974 if (TheCall->getArg(1)->isTypeDependent() ||
1975 TheCall->getArg(1)->isValueDependent())
1976 return false;
1977
Eric Christopher8d0c6212010-04-17 02:26:23 +00001978 // Check constant-ness first.
1979 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1980 return true;
1981
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001982 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001983 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001984 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1985 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001986 }
1987
1988 return false;
1989}
1990
Eli Friedmanc97d0142009-05-03 06:04:26 +00001991/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001992/// This checks that val is a constant 1.
1993bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1994 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001995 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001996
Eric Christopher8d0c6212010-04-17 02:26:23 +00001997 // TODO: This is less than ideal. Overload this to take a value.
1998 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1999 return true;
2000
2001 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002002 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2003 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2004
2005 return false;
2006}
2007
Richard Smithd7293d72013-08-05 18:49:43 +00002008namespace {
2009enum StringLiteralCheckType {
2010 SLCT_NotALiteral,
2011 SLCT_UncheckedLiteral,
2012 SLCT_CheckedLiteral
2013};
2014}
2015
Richard Smith55ce3522012-06-25 20:30:08 +00002016// Determine if an expression is a string literal or constant string.
2017// If this function returns false on the arguments to a function expecting a
2018// format string, we will usually need to emit a warning.
2019// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002020static StringLiteralCheckType
2021checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2022 bool HasVAListArg, unsigned format_idx,
2023 unsigned firstDataArg, Sema::FormatStringType Type,
2024 Sema::VariadicCallType CallType, bool InFunctionCall,
2025 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002026 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002027 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002028 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002029
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002030 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002031
Richard Smithd7293d72013-08-05 18:49:43 +00002032 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002033 // Technically -Wformat-nonliteral does not warn about this case.
2034 // The behavior of printf and friends in this case is implementation
2035 // dependent. Ideally if the format string cannot be null then
2036 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002037 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002038
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002039 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002040 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002041 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002042 // The expression is a literal if both sub-expressions were, and it was
2043 // completely checked only if both sub-expressions were checked.
2044 const AbstractConditionalOperator *C =
2045 cast<AbstractConditionalOperator>(E);
2046 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002047 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002048 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002049 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002050 if (Left == SLCT_NotALiteral)
2051 return SLCT_NotALiteral;
2052 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002053 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002054 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002055 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002056 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002057 }
2058
2059 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002060 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2061 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002062 }
2063
John McCallc07a0c72011-02-17 10:25:35 +00002064 case Stmt::OpaqueValueExprClass:
2065 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2066 E = src;
2067 goto tryAgain;
2068 }
Richard Smith55ce3522012-06-25 20:30:08 +00002069 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002070
Ted Kremeneka8890832011-02-24 23:03:04 +00002071 case Stmt::PredefinedExprClass:
2072 // While __func__, etc., are technically not string literals, they
2073 // cannot contain format specifiers and thus are not a security
2074 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002075 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002076
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002077 case Stmt::DeclRefExprClass: {
2078 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002080 // As an exception, do not flag errors for variables binding to
2081 // const string literals.
2082 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2083 bool isConstant = false;
2084 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002085
Richard Smithd7293d72013-08-05 18:49:43 +00002086 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2087 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002088 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002089 isConstant = T.isConstant(S.Context) &&
2090 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002091 } else if (T->isObjCObjectPointerType()) {
2092 // In ObjC, there is usually no "const ObjectPointer" type,
2093 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002094 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002095 }
Mike Stump11289f42009-09-09 15:08:12 +00002096
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002097 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002098 if (const Expr *Init = VD->getAnyInitializer()) {
2099 // Look through initializers like const char c[] = { "foo" }
2100 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2101 if (InitList->isStringLiteralInit())
2102 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2103 }
Richard Smithd7293d72013-08-05 18:49:43 +00002104 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002105 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002106 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002107 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002108 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002109 }
Mike Stump11289f42009-09-09 15:08:12 +00002110
Anders Carlssonb012ca92009-06-28 19:55:58 +00002111 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2112 // special check to see if the format string is a function parameter
2113 // of the function calling the printf function. If the function
2114 // has an attribute indicating it is a printf-like function, then we
2115 // should suppress warnings concerning non-literals being used in a call
2116 // to a vprintf function. For example:
2117 //
2118 // void
2119 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2120 // va_list ap;
2121 // va_start(ap, fmt);
2122 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2123 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002124 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002125 if (HasVAListArg) {
2126 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2127 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2128 int PVIndex = PV->getFunctionScopeIndex() + 1;
2129 for (specific_attr_iterator<FormatAttr>
2130 i = ND->specific_attr_begin<FormatAttr>(),
2131 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2132 FormatAttr *PVFormat = *i;
2133 // adjust for implicit parameter
2134 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2135 if (MD->isInstance())
2136 ++PVIndex;
2137 // We also check if the formats are compatible.
2138 // We can't pass a 'scanf' string to a 'printf' function.
2139 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002140 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002141 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002142 }
2143 }
2144 }
2145 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002146 }
Mike Stump11289f42009-09-09 15:08:12 +00002147
Richard Smith55ce3522012-06-25 20:30:08 +00002148 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002149 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002150
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002151 case Stmt::CallExprClass:
2152 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002153 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002154 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2155 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2156 unsigned ArgIndex = FA->getFormatIdx();
2157 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2158 if (MD->isInstance())
2159 --ArgIndex;
2160 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002161
Richard Smithd7293d72013-08-05 18:49:43 +00002162 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002163 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002164 Type, CallType, InFunctionCall,
2165 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002166 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2167 unsigned BuiltinID = FD->getBuiltinID();
2168 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2169 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2170 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002171 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002172 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002173 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002174 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002175 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002176 }
2177 }
Mike Stump11289f42009-09-09 15:08:12 +00002178
Richard Smith55ce3522012-06-25 20:30:08 +00002179 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002180 }
Fariborz Jahanian4ba4a5b2013-10-18 21:20:34 +00002181
2182 case Stmt::ObjCMessageExprClass: {
2183 const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2184 if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2185 if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2186 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2187 unsigned ArgIndex = FA->getFormatIdx();
2188 if (ArgIndex <= ME->getNumArgs()) {
2189 const Expr *Arg = ME->getArg(ArgIndex-1);
2190 return checkFormatStringExpr(S, Arg, Args,
2191 HasVAListArg, format_idx,
2192 firstDataArg, Type, CallType,
2193 InFunctionCall, CheckedVarArgs);
2194 }
2195 }
2196 }
2197 }
2198
2199 return SLCT_NotALiteral;
2200 }
2201
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002202 case Stmt::ObjCStringLiteralClass:
2203 case Stmt::StringLiteralClass: {
2204 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002205
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002206 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002207 StrE = ObjCFExpr->getString();
2208 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002209 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002210
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002211 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002212 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2213 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002214 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Richard Smith55ce3522012-06-25 20:30:08 +00002217 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002218 }
Mike Stump11289f42009-09-09 15:08:12 +00002219
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002220 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002221 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002222 }
2223}
2224
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002225Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002226 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002227 .Case("scanf", FST_Scanf)
2228 .Cases("printf", "printf0", FST_Printf)
2229 .Cases("NSString", "CFString", FST_NSString)
2230 .Case("strftime", FST_Strftime)
2231 .Case("strfmon", FST_Strfmon)
2232 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2233 .Default(FST_Unknown);
2234}
2235
Jordan Rose3e0ec582012-07-19 18:10:23 +00002236/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002237/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002238/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002239bool Sema::CheckFormatArguments(const FormatAttr *Format,
2240 ArrayRef<const Expr *> Args,
2241 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002242 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002243 SourceLocation Loc, SourceRange Range,
2244 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002245 FormatStringInfo FSI;
2246 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002247 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002248 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002249 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002250 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002251}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002252
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002253bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002254 bool HasVAListArg, unsigned format_idx,
2255 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002256 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002257 SourceLocation Loc, SourceRange Range,
2258 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002259 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002260 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002261 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002262 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002263 }
Mike Stump11289f42009-09-09 15:08:12 +00002264
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002265 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002266
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002267 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002268 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002269 // Dynamically generated format strings are difficult to
2270 // automatically vet at compile time. Requiring that format strings
2271 // are string literals: (1) permits the checking of format strings by
2272 // the compiler and thereby (2) can practically remove the source of
2273 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002274
Mike Stump11289f42009-09-09 15:08:12 +00002275 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002276 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002277 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002278 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002279 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002280 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2281 format_idx, firstDataArg, Type, CallType,
2282 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002283 if (CT != SLCT_NotALiteral)
2284 // Literal format string found, check done!
2285 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002286
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002287 // Strftime is particular as it always uses a single 'time' argument,
2288 // so it is safe to pass a non-literal string.
2289 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002290 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002291
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002292 // Do not emit diag when the string param is a macro expansion and the
2293 // format is either NSString or CFString. This is a hack to prevent
2294 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2295 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002296 if (Type == FST_NSString &&
2297 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002298 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002299
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002300 // If there are no arguments specified, warn with -Wformat-security, otherwise
2301 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002302 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002303 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002304 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002305 << OrigFormatExpr->getSourceRange();
2306 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002307 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002308 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002309 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002310 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002311}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002312
Ted Kremenekab278de2010-01-28 23:39:18 +00002313namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002314class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2315protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002316 Sema &S;
2317 const StringLiteral *FExpr;
2318 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002319 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002320 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002321 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002322 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002323 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002324 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002325 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002326 bool usesPositionalArgs;
2327 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002328 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002329 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002330 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002331public:
Ted Kremenek02087932010-07-16 02:11:22 +00002332 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002333 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002334 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002335 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002336 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002337 Sema::VariadicCallType callType,
2338 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002339 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002340 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2341 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002342 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002343 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002344 inFunctionCall(inFunctionCall), CallType(callType),
2345 CheckedVarArgs(CheckedVarArgs) {
2346 CoveredArgs.resize(numDataArgs);
2347 CoveredArgs.reset();
2348 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002349
Ted Kremenek019d2242010-01-29 01:50:07 +00002350 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002351
Ted Kremenek02087932010-07-16 02:11:22 +00002352 void HandleIncompleteSpecifier(const char *startSpecifier,
2353 unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002354
Jordan Rose92303592012-09-08 04:00:03 +00002355 void HandleInvalidLengthModifier(
2356 const analyze_format_string::FormatSpecifier &FS,
2357 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002358 const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002359
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002360 void HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002361 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002362 const char *startSpecifier, unsigned specifierLen);
2363
2364 void HandleNonStandardConversionSpecifier(
2365 const analyze_format_string::ConversionSpecifier &CS,
2366 const char *startSpecifier, unsigned specifierLen);
2367
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002368 virtual void HandlePosition(const char *startPos, unsigned posLen);
2369
Ted Kremenekd1668192010-02-27 01:41:03 +00002370 virtual void HandleInvalidPosition(const char *startSpecifier,
2371 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00002372 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00002373
2374 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2375
Ted Kremenekab278de2010-01-28 23:39:18 +00002376 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002377
Richard Trieu03cf7b72011-10-28 00:41:25 +00002378 template <typename Range>
2379 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2380 const Expr *ArgumentExpr,
2381 PartialDiagnostic PDiag,
2382 SourceLocation StringLoc,
2383 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002384 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002385
Ted Kremenek02087932010-07-16 02:11:22 +00002386protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002387 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2388 const char *startSpec,
2389 unsigned specifierLen,
2390 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002391
2392 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2393 const char *startSpec,
2394 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002395
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002396 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002397 CharSourceRange getSpecifierRange(const char *startSpecifier,
2398 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002399 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002400
Ted Kremenek5739de72010-01-29 01:06:55 +00002401 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002402
2403 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2404 const analyze_format_string::ConversionSpecifier &CS,
2405 const char *startSpecifier, unsigned specifierLen,
2406 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002407
2408 template <typename Range>
2409 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2410 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002411 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002412
2413 void CheckPositionalAndNonpositionalArgs(
2414 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00002415};
2416}
2417
Ted Kremenek02087932010-07-16 02:11:22 +00002418SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002419 return OrigFormatExpr->getSourceRange();
2420}
2421
Ted Kremenek02087932010-07-16 02:11:22 +00002422CharSourceRange CheckFormatHandler::
2423getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002424 SourceLocation Start = getLocationOfByte(startSpecifier);
2425 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2426
2427 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002428 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002429
2430 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002431}
2432
Ted Kremenek02087932010-07-16 02:11:22 +00002433SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002434 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002435}
2436
Ted Kremenek02087932010-07-16 02:11:22 +00002437void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2438 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002439 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2440 getLocationOfByte(startSpecifier),
2441 /*IsStringLocation*/true,
2442 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002443}
2444
Jordan Rose92303592012-09-08 04:00:03 +00002445void CheckFormatHandler::HandleInvalidLengthModifier(
2446 const analyze_format_string::FormatSpecifier &FS,
2447 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002448 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002449 using namespace analyze_format_string;
2450
2451 const LengthModifier &LM = FS.getLengthModifier();
2452 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2453
2454 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002455 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002456 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002457 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002458 getLocationOfByte(LM.getStart()),
2459 /*IsStringLocation*/true,
2460 getSpecifierRange(startSpecifier, specifierLen));
2461
2462 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2463 << FixedLM->toString()
2464 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2465
2466 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002467 FixItHint Hint;
2468 if (DiagID == diag::warn_format_nonsensical_length)
2469 Hint = FixItHint::CreateRemoval(LMRange);
2470
2471 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002472 getLocationOfByte(LM.getStart()),
2473 /*IsStringLocation*/true,
2474 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002475 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002476 }
2477}
2478
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002479void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002480 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002481 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002482 using namespace analyze_format_string;
2483
2484 const LengthModifier &LM = FS.getLengthModifier();
2485 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2486
2487 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002488 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002489 if (FixedLM) {
2490 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2491 << LM.toString() << 0,
2492 getLocationOfByte(LM.getStart()),
2493 /*IsStringLocation*/true,
2494 getSpecifierRange(startSpecifier, specifierLen));
2495
2496 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2497 << FixedLM->toString()
2498 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2499
2500 } else {
2501 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2502 << LM.toString() << 0,
2503 getLocationOfByte(LM.getStart()),
2504 /*IsStringLocation*/true,
2505 getSpecifierRange(startSpecifier, specifierLen));
2506 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002507}
2508
2509void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2510 const analyze_format_string::ConversionSpecifier &CS,
2511 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002512 using namespace analyze_format_string;
2513
2514 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002515 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002516 if (FixedCS) {
2517 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2518 << CS.toString() << /*conversion specifier*/1,
2519 getLocationOfByte(CS.getStart()),
2520 /*IsStringLocation*/true,
2521 getSpecifierRange(startSpecifier, specifierLen));
2522
2523 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2524 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2525 << FixedCS->toString()
2526 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2527 } else {
2528 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2529 << CS.toString() << /*conversion specifier*/1,
2530 getLocationOfByte(CS.getStart()),
2531 /*IsStringLocation*/true,
2532 getSpecifierRange(startSpecifier, specifierLen));
2533 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002534}
2535
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002536void CheckFormatHandler::HandlePosition(const char *startPos,
2537 unsigned posLen) {
2538 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2539 getLocationOfByte(startPos),
2540 /*IsStringLocation*/true,
2541 getSpecifierRange(startPos, posLen));
2542}
2543
Ted Kremenekd1668192010-02-27 01:41:03 +00002544void
Ted Kremenek02087932010-07-16 02:11:22 +00002545CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2546 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002547 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2548 << (unsigned) p,
2549 getLocationOfByte(startPos), /*IsStringLocation*/true,
2550 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002551}
2552
Ted Kremenek02087932010-07-16 02:11:22 +00002553void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00002554 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002555 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2556 getLocationOfByte(startPos),
2557 /*IsStringLocation*/true,
2558 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00002559}
2560
Ted Kremenek02087932010-07-16 02:11:22 +00002561void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002562 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002563 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002564 EmitFormatDiagnostic(
2565 S.PDiag(diag::warn_printf_format_string_contains_null_char),
2566 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2567 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00002568 }
Ted Kremenek02087932010-07-16 02:11:22 +00002569}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002570
Jordan Rose58bbe422012-07-19 18:10:08 +00002571// Note that this may return NULL if there was an error parsing or building
2572// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00002573const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002574 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00002575}
2576
2577void CheckFormatHandler::DoneProcessing() {
2578 // Does the number of data arguments exceed the number of
2579 // format conversions in the format string?
2580 if (!HasVAListArg) {
2581 // Find any arguments that weren't covered.
2582 CoveredArgs.flip();
2583 signed notCoveredArg = CoveredArgs.find_first();
2584 if (notCoveredArg >= 0) {
2585 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00002586 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2587 SourceLocation Loc = E->getLocStart();
2588 if (!S.getSourceManager().isInSystemMacro(Loc)) {
2589 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2590 Loc, /*IsStringLocation*/false,
2591 getFormatStringRange());
2592 }
Bob Wilson23cd4342012-05-03 19:47:19 +00002593 }
Ted Kremenek02087932010-07-16 02:11:22 +00002594 }
2595 }
2596}
2597
Ted Kremenekce815422010-07-19 21:25:57 +00002598bool
2599CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2600 SourceLocation Loc,
2601 const char *startSpec,
2602 unsigned specifierLen,
2603 const char *csStart,
2604 unsigned csLen) {
2605
2606 bool keepGoing = true;
2607 if (argIndex < NumDataArgs) {
2608 // Consider the argument coverered, even though the specifier doesn't
2609 // make sense.
2610 CoveredArgs.set(argIndex);
2611 }
2612 else {
2613 // If argIndex exceeds the number of data arguments we
2614 // don't issue a warning because that is just a cascade of warnings (and
2615 // they may have intended '%%' anyway). We don't want to continue processing
2616 // the format string after this point, however, as we will like just get
2617 // gibberish when trying to match arguments.
2618 keepGoing = false;
2619 }
2620
Richard Trieu03cf7b72011-10-28 00:41:25 +00002621 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2622 << StringRef(csStart, csLen),
2623 Loc, /*IsStringLocation*/true,
2624 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00002625
2626 return keepGoing;
2627}
2628
Richard Trieu03cf7b72011-10-28 00:41:25 +00002629void
2630CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2631 const char *startSpec,
2632 unsigned specifierLen) {
2633 EmitFormatDiagnostic(
2634 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2635 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2636}
2637
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002638bool
2639CheckFormatHandler::CheckNumArgs(
2640 const analyze_format_string::FormatSpecifier &FS,
2641 const analyze_format_string::ConversionSpecifier &CS,
2642 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2643
2644 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002645 PartialDiagnostic PDiag = FS.usesPositionalArg()
2646 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2647 << (argIndex+1) << NumDataArgs)
2648 : S.PDiag(diag::warn_printf_insufficient_data_args);
2649 EmitFormatDiagnostic(
2650 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2651 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002652 return false;
2653 }
2654 return true;
2655}
2656
Richard Trieu03cf7b72011-10-28 00:41:25 +00002657template<typename Range>
2658void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2659 SourceLocation Loc,
2660 bool IsStringLocation,
2661 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002662 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002663 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002664 Loc, IsStringLocation, StringRange, FixIt);
2665}
2666
2667/// \brief If the format string is not within the funcion call, emit a note
2668/// so that the function call and string are in diagnostic messages.
2669///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002670/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00002671/// call and only one diagnostic message will be produced. Otherwise, an
2672/// extra note will be emitted pointing to location of the format string.
2673///
2674/// \param ArgumentExpr the expression that is passed as the format string
2675/// argument in the function call. Used for getting locations when two
2676/// diagnostics are emitted.
2677///
2678/// \param PDiag the callee should already have provided any strings for the
2679/// diagnostic message. This function only adds locations and fixits
2680/// to diagnostics.
2681///
2682/// \param Loc primary location for diagnostic. If two diagnostics are
2683/// required, one will be at Loc and a new SourceLocation will be created for
2684/// the other one.
2685///
2686/// \param IsStringLocation if true, Loc points to the format string should be
2687/// used for the note. Otherwise, Loc points to the argument list and will
2688/// be used with PDiag.
2689///
2690/// \param StringRange some or all of the string to highlight. This is
2691/// templated so it can accept either a CharSourceRange or a SourceRange.
2692///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00002693/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002694template<typename Range>
2695void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2696 const Expr *ArgumentExpr,
2697 PartialDiagnostic PDiag,
2698 SourceLocation Loc,
2699 bool IsStringLocation,
2700 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00002701 ArrayRef<FixItHint> FixIt) {
2702 if (InFunctionCall) {
2703 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2704 D << StringRange;
2705 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2706 I != E; ++I) {
2707 D << *I;
2708 }
2709 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002710 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2711 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00002712
2713 const Sema::SemaDiagnosticBuilder &Note =
2714 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2715 diag::note_format_string_defined);
2716
2717 Note << StringRange;
2718 for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2719 I != E; ++I) {
2720 Note << *I;
2721 }
Richard Trieu03cf7b72011-10-28 00:41:25 +00002722 }
2723}
2724
Ted Kremenek02087932010-07-16 02:11:22 +00002725//===--- CHECK: Printf format string checking ------------------------------===//
2726
2727namespace {
2728class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002729 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00002730public:
2731 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2732 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002733 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00002734 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002735 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002736 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002737 Sema::VariadicCallType CallType,
2738 llvm::SmallBitVector &CheckedVarArgs)
2739 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2740 numDataArgs, beg, hasVAListArg, Args,
2741 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2742 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00002743 {}
2744
Ted Kremenek02087932010-07-16 02:11:22 +00002745
2746 bool HandleInvalidPrintfConversionSpecifier(
2747 const analyze_printf::PrintfSpecifier &FS,
2748 const char *startSpecifier,
2749 unsigned specifierLen);
2750
2751 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2752 const char *startSpecifier,
2753 unsigned specifierLen);
Richard Smith55ce3522012-06-25 20:30:08 +00002754 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2755 const char *StartSpecifier,
2756 unsigned SpecifierLen,
2757 const Expr *E);
2758
Ted Kremenek02087932010-07-16 02:11:22 +00002759 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2760 const char *startSpecifier, unsigned specifierLen);
2761 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2762 const analyze_printf::OptionalAmount &Amt,
2763 unsigned type,
2764 const char *startSpecifier, unsigned specifierLen);
2765 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2766 const analyze_printf::OptionalFlag &flag,
2767 const char *startSpecifier, unsigned specifierLen);
2768 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2769 const analyze_printf::OptionalFlag &ignoredFlag,
2770 const analyze_printf::OptionalFlag &flag,
2771 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002772 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith55ce3522012-06-25 20:30:08 +00002773 const Expr *E, const CharSourceRange &CSR);
2774
Ted Kremenek02087932010-07-16 02:11:22 +00002775};
2776}
2777
2778bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2779 const analyze_printf::PrintfSpecifier &FS,
2780 const char *startSpecifier,
2781 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002782 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002783 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002784
Ted Kremenekce815422010-07-19 21:25:57 +00002785 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2786 getLocationOfByte(CS.getStart()),
2787 startSpecifier, specifierLen,
2788 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00002789}
2790
Ted Kremenek02087932010-07-16 02:11:22 +00002791bool CheckPrintfHandler::HandleAmount(
2792 const analyze_format_string::OptionalAmount &Amt,
2793 unsigned k, const char *startSpecifier,
2794 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002795
2796 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002797 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00002798 unsigned argIndex = Amt.getArgIndex();
2799 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2801 << k,
2802 getLocationOfByte(Amt.getStart()),
2803 /*IsStringLocation*/true,
2804 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002805 // Don't do any more checking. We will just emit
2806 // spurious errors.
2807 return false;
2808 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002809
Ted Kremenek5739de72010-01-29 01:06:55 +00002810 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00002811 // Although not in conformance with C99, we also allow the argument to be
2812 // an 'unsigned int' as that is a reasonably safe case. GCC also
2813 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00002814 CoveredArgs.set(argIndex);
2815 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00002816 if (!Arg)
2817 return false;
2818
Ted Kremenek5739de72010-01-29 01:06:55 +00002819 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002820
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002821 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2822 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002823
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002824 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002825 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002826 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00002827 << T << Arg->getSourceRange(),
2828 getLocationOfByte(Amt.getStart()),
2829 /*IsStringLocation*/true,
2830 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00002831 // Don't do any more checking. We will just emit
2832 // spurious errors.
2833 return false;
2834 }
2835 }
2836 }
2837 return true;
2838}
Ted Kremenek5739de72010-01-29 01:06:55 +00002839
Tom Careb49ec692010-06-17 19:00:27 +00002840void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00002841 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002842 const analyze_printf::OptionalAmount &Amt,
2843 unsigned type,
2844 const char *startSpecifier,
2845 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002846 const analyze_printf::PrintfConversionSpecifier &CS =
2847 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00002848
Richard Trieu03cf7b72011-10-28 00:41:25 +00002849 FixItHint fixit =
2850 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2851 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2852 Amt.getConstantLength()))
2853 : FixItHint();
2854
2855 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2856 << type << CS.toString(),
2857 getLocationOfByte(Amt.getStart()),
2858 /*IsStringLocation*/true,
2859 getSpecifierRange(startSpecifier, specifierLen),
2860 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00002861}
2862
Ted Kremenek02087932010-07-16 02:11:22 +00002863void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002864 const analyze_printf::OptionalFlag &flag,
2865 const char *startSpecifier,
2866 unsigned specifierLen) {
2867 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002868 const analyze_printf::PrintfConversionSpecifier &CS =
2869 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00002870 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2871 << flag.toString() << CS.toString(),
2872 getLocationOfByte(flag.getPosition()),
2873 /*IsStringLocation*/true,
2874 getSpecifierRange(startSpecifier, specifierLen),
2875 FixItHint::CreateRemoval(
2876 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002877}
2878
2879void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00002880 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00002881 const analyze_printf::OptionalFlag &ignoredFlag,
2882 const analyze_printf::OptionalFlag &flag,
2883 const char *startSpecifier,
2884 unsigned specifierLen) {
2885 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002886 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2887 << ignoredFlag.toString() << flag.toString(),
2888 getLocationOfByte(ignoredFlag.getPosition()),
2889 /*IsStringLocation*/true,
2890 getSpecifierRange(startSpecifier, specifierLen),
2891 FixItHint::CreateRemoval(
2892 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00002893}
2894
Richard Smith55ce3522012-06-25 20:30:08 +00002895// Determines if the specified is a C++ class or struct containing
2896// a member with the specified name and kind (e.g. a CXXMethodDecl named
2897// "c_str()").
2898template<typename MemberKind>
2899static llvm::SmallPtrSet<MemberKind*, 1>
2900CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2901 const RecordType *RT = Ty->getAs<RecordType>();
2902 llvm::SmallPtrSet<MemberKind*, 1> Results;
2903
2904 if (!RT)
2905 return Results;
2906 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2907 if (!RD)
2908 return Results;
2909
2910 LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2911 Sema::LookupMemberName);
2912
2913 // We just need to include all members of the right kind turned up by the
2914 // filter, at this point.
2915 if (S.LookupQualifiedName(R, RT->getDecl()))
2916 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2917 NamedDecl *decl = (*I)->getUnderlyingDecl();
2918 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2919 Results.insert(FK);
2920 }
2921 return Results;
2922}
2923
2924// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002925// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00002926// Returns true when a c_str() conversion method is found.
2927bool CheckPrintfHandler::checkForCStrMembers(
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002928 const analyze_printf::ArgType &AT, const Expr *E,
Richard Smith55ce3522012-06-25 20:30:08 +00002929 const CharSourceRange &CSR) {
2930 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2931
2932 MethodSet Results =
2933 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2934
2935 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2936 MI != ME; ++MI) {
2937 const CXXMethodDecl *Method = *MI;
2938 if (Method->getNumParams() == 0 &&
Hans Wennborgc3b3da02012-08-07 08:11:26 +00002939 AT.matchesType(S.Context, Method->getResultType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00002940 // FIXME: Suggest parens if the expression needs them.
2941 SourceLocation EndLoc =
2942 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2943 S.Diag(E->getLocStart(), diag::note_printf_c_str)
2944 << "c_str()"
2945 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2946 return true;
2947 }
2948 }
2949
2950 return false;
2951}
2952
Ted Kremenekab278de2010-01-28 23:39:18 +00002953bool
Ted Kremenek02087932010-07-16 02:11:22 +00002954CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00002955 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00002956 const char *startSpecifier,
2957 unsigned specifierLen) {
2958
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002959 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00002960 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002961 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00002962
Ted Kremenek6cd69422010-07-19 22:01:06 +00002963 if (FS.consumesDataArgument()) {
2964 if (atFirstArg) {
2965 atFirstArg = false;
2966 usesPositionalArgs = FS.usesPositionalArg();
2967 }
2968 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002969 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2970 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002971 return false;
2972 }
Ted Kremenek5739de72010-01-29 01:06:55 +00002973 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002974
Ted Kremenekd1668192010-02-27 01:41:03 +00002975 // First check if the field width, precision, and conversion specifier
2976 // have matching data arguments.
2977 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2978 startSpecifier, specifierLen)) {
2979 return false;
2980 }
2981
2982 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2983 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00002984 return false;
2985 }
2986
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002987 if (!CS.consumesDataArgument()) {
2988 // FIXME: Technically specifying a precision or field width here
2989 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00002990 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002991 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002992
Ted Kremenek4a49d982010-02-26 19:18:41 +00002993 // Consume the argument.
2994 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00002995 if (argIndex < NumDataArgs) {
2996 // The check to see if the argIndex is valid will come later.
2997 // We set the bit here because we may exit early from this
2998 // function if we encounter some other error.
2999 CoveredArgs.set(argIndex);
3000 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003001
3002 // Check for using an Objective-C specific conversion specifier
3003 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003004 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003005 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3006 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003007 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003008
Tom Careb49ec692010-06-17 19:00:27 +00003009 // Check for invalid use of field width
3010 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003011 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003012 startSpecifier, specifierLen);
3013 }
3014
3015 // Check for invalid use of precision
3016 if (!FS.hasValidPrecision()) {
3017 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3018 startSpecifier, specifierLen);
3019 }
3020
3021 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003022 if (!FS.hasValidThousandsGroupingPrefix())
3023 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003024 if (!FS.hasValidLeadingZeros())
3025 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3026 if (!FS.hasValidPlusPrefix())
3027 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003028 if (!FS.hasValidSpacePrefix())
3029 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003030 if (!FS.hasValidAlternativeForm())
3031 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3032 if (!FS.hasValidLeftJustified())
3033 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3034
3035 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003036 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3037 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3038 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003039 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3040 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3041 startSpecifier, specifierLen);
3042
3043 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003044 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003045 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3046 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003047 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003048 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003049 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003050 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3051 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003052
Jordan Rose92303592012-09-08 04:00:03 +00003053 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3054 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3055
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003056 // The remaining checks depend on the data arguments.
3057 if (HasVAListArg)
3058 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003059
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003060 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003061 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003062
Jordan Rose58bbe422012-07-19 18:10:08 +00003063 const Expr *Arg = getDataArg(argIndex);
3064 if (!Arg)
3065 return true;
3066
3067 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003068}
3069
Jordan Roseaee34382012-09-05 22:56:26 +00003070static bool requiresParensToAddCast(const Expr *E) {
3071 // FIXME: We should have a general way to reason about operator
3072 // precedence and whether parens are actually needed here.
3073 // Take care of a few common cases where they aren't.
3074 const Expr *Inside = E->IgnoreImpCasts();
3075 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3076 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3077
3078 switch (Inside->getStmtClass()) {
3079 case Stmt::ArraySubscriptExprClass:
3080 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003081 case Stmt::CharacterLiteralClass:
3082 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003083 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003084 case Stmt::FloatingLiteralClass:
3085 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003086 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003087 case Stmt::ObjCArrayLiteralClass:
3088 case Stmt::ObjCBoolLiteralExprClass:
3089 case Stmt::ObjCBoxedExprClass:
3090 case Stmt::ObjCDictionaryLiteralClass:
3091 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003092 case Stmt::ObjCIvarRefExprClass:
3093 case Stmt::ObjCMessageExprClass:
3094 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003095 case Stmt::ObjCStringLiteralClass:
3096 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003097 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003098 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003099 case Stmt::UnaryOperatorClass:
3100 return false;
3101 default:
3102 return true;
3103 }
3104}
3105
Richard Smith55ce3522012-06-25 20:30:08 +00003106bool
3107CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3108 const char *StartSpecifier,
3109 unsigned SpecifierLen,
3110 const Expr *E) {
3111 using namespace analyze_format_string;
3112 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003113 // Now type check the data expression that matches the
3114 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003115 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3116 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003117 if (!AT.isValid())
3118 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003119
Jordan Rose598ec092012-12-05 18:44:40 +00003120 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003121 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3122 ExprTy = TET->getUnderlyingExpr()->getType();
3123 }
3124
Jordan Rose598ec092012-12-05 18:44:40 +00003125 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003126 return true;
Jordan Rose98709982012-06-04 22:48:57 +00003127
Jordan Rose22b74712012-09-05 22:56:19 +00003128 // Look through argument promotions for our error message's reported type.
3129 // This includes the integral and floating promotions, but excludes array
3130 // and function pointer decay; seeing that an argument intended to be a
3131 // string has type 'char [6]' is probably more confusing than 'char *'.
3132 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3133 if (ICE->getCastKind() == CK_IntegralCast ||
3134 ICE->getCastKind() == CK_FloatingCast) {
3135 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003136 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003137
3138 // Check if we didn't match because of an implicit cast from a 'char'
3139 // or 'short' to an 'int'. This is done because printf is a varargs
3140 // function.
3141 if (ICE->getType() == S.Context.IntTy ||
3142 ICE->getType() == S.Context.UnsignedIntTy) {
3143 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003144 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003145 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003146 }
Jordan Rose98709982012-06-04 22:48:57 +00003147 }
Jordan Rose598ec092012-12-05 18:44:40 +00003148 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3149 // Special case for 'a', which has type 'int' in C.
3150 // Note, however, that we do /not/ want to treat multibyte constants like
3151 // 'MooV' as characters! This form is deprecated but still exists.
3152 if (ExprTy == S.Context.IntTy)
3153 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3154 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003155 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003156
Jordan Rose0e5badd2012-12-05 18:44:49 +00003157 // %C in an Objective-C context prints a unichar, not a wchar_t.
3158 // If the argument is an integer of some kind, believe the %C and suggest
3159 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003160 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003161 if (ObjCContext &&
3162 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3163 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3164 !ExprTy->isCharType()) {
3165 // 'unichar' is defined as a typedef of unsigned short, but we should
3166 // prefer using the typedef if it is visible.
3167 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003168
3169 // While we are here, check if the value is an IntegerLiteral that happens
3170 // to be within the valid range.
3171 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3172 const llvm::APInt &V = IL->getValue();
3173 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3174 return true;
3175 }
3176
Jordan Rose0e5badd2012-12-05 18:44:49 +00003177 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3178 Sema::LookupOrdinaryName);
3179 if (S.LookupName(Result, S.getCurScope())) {
3180 NamedDecl *ND = Result.getFoundDecl();
3181 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3182 if (TD->getUnderlyingType() == IntendedTy)
3183 IntendedTy = S.Context.getTypedefType(TD);
3184 }
3185 }
3186 }
3187
3188 // Special-case some of Darwin's platform-independence types by suggesting
3189 // casts to primitive types that are known to be large enough.
3190 bool ShouldNotPrintDirectly = false;
Jordan Roseaee34382012-09-05 22:56:26 +00003191 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003192 // Use a 'while' to peel off layers of typedefs.
3193 QualType TyTy = IntendedTy;
3194 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
Jordan Roseaee34382012-09-05 22:56:26 +00003195 StringRef Name = UserTy->getDecl()->getName();
Jordan Rose0e5badd2012-12-05 18:44:49 +00003196 QualType CastTy = llvm::StringSwitch<QualType>(Name)
Jordan Roseaee34382012-09-05 22:56:26 +00003197 .Case("NSInteger", S.Context.LongTy)
3198 .Case("NSUInteger", S.Context.UnsignedLongTy)
3199 .Case("SInt32", S.Context.IntTy)
3200 .Case("UInt32", S.Context.UnsignedIntTy)
Jordan Rose0e5badd2012-12-05 18:44:49 +00003201 .Default(QualType());
3202
3203 if (!CastTy.isNull()) {
3204 ShouldNotPrintDirectly = true;
3205 IntendedTy = CastTy;
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003206 break;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003207 }
Ted Kremenekcd3d4402013-03-25 22:28:37 +00003208 TyTy = UserTy->desugar();
Jordan Roseaee34382012-09-05 22:56:26 +00003209 }
3210 }
3211
Jordan Rose22b74712012-09-05 22:56:19 +00003212 // We may be able to offer a FixItHint if it is a supported type.
3213 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003214 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003215 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003216
Jordan Rose22b74712012-09-05 22:56:19 +00003217 if (success) {
3218 // Get the fix string from the fixed format specifier
3219 SmallString<16> buf;
3220 llvm::raw_svector_ostream os(buf);
3221 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003222
Jordan Roseaee34382012-09-05 22:56:26 +00003223 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3224
Jordan Rose0e5badd2012-12-05 18:44:49 +00003225 if (IntendedTy == ExprTy) {
3226 // In this case, the specifier is wrong and should be changed to match
3227 // the argument.
3228 EmitFormatDiagnostic(
3229 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3230 << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3231 << E->getSourceRange(),
3232 E->getLocStart(),
3233 /*IsStringLocation*/false,
3234 SpecRange,
3235 FixItHint::CreateReplacement(SpecRange, os.str()));
3236
3237 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003238 // The canonical type for formatting this value is different from the
3239 // actual type of the expression. (This occurs, for example, with Darwin's
3240 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3241 // should be printed as 'long' for 64-bit compatibility.)
3242 // Rather than emitting a normal format/argument mismatch, we want to
3243 // add a cast to the recommended type (and correct the format string
3244 // if necessary).
3245 SmallString<16> CastBuf;
3246 llvm::raw_svector_ostream CastFix(CastBuf);
3247 CastFix << "(";
3248 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3249 CastFix << ")";
3250
3251 SmallVector<FixItHint,4> Hints;
3252 if (!AT.matchesType(S.Context, IntendedTy))
3253 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3254
3255 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3256 // If there's already a cast present, just replace it.
3257 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3258 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3259
3260 } else if (!requiresParensToAddCast(E)) {
3261 // If the expression has high enough precedence,
3262 // just write the C-style cast.
3263 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3264 CastFix.str()));
3265 } else {
3266 // Otherwise, add parens around the expression as well as the cast.
3267 CastFix << "(";
3268 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3269 CastFix.str()));
3270
3271 SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3272 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3273 }
3274
Jordan Rose0e5badd2012-12-05 18:44:49 +00003275 if (ShouldNotPrintDirectly) {
3276 // The expression has a type that should not be printed directly.
3277 // We extract the name from the typedef because we don't want to show
3278 // the underlying type in the diagnostic.
3279 StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
Jordan Roseaee34382012-09-05 22:56:26 +00003280
Jordan Rose0e5badd2012-12-05 18:44:49 +00003281 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3282 << Name << IntendedTy
3283 << E->getSourceRange(),
3284 E->getLocStart(), /*IsStringLocation=*/false,
3285 SpecRange, Hints);
3286 } else {
3287 // In this case, the expression could be printed using a different
3288 // specifier, but we've decided that the specifier is probably correct
3289 // and we should cast instead. Just use the normal warning message.
3290 EmitFormatDiagnostic(
3291 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3292 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3293 << E->getSourceRange(),
3294 E->getLocStart(), /*IsStringLocation*/false,
3295 SpecRange, Hints);
3296 }
Jordan Roseaee34382012-09-05 22:56:26 +00003297 }
Jordan Rose22b74712012-09-05 22:56:19 +00003298 } else {
3299 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3300 SpecifierLen);
3301 // Since the warning for passing non-POD types to variadic functions
3302 // was deferred until now, we emit a warning for non-POD
3303 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003304 switch (S.isValidVarArgType(ExprTy)) {
3305 case Sema::VAK_Valid:
3306 case Sema::VAK_ValidInCXX11:
Jordan Rose22b74712012-09-05 22:56:19 +00003307 EmitFormatDiagnostic(
Richard Smithd7293d72013-08-05 18:49:43 +00003308 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3309 << AT.getRepresentativeTypeName(S.Context) << ExprTy
3310 << CSR
3311 << E->getSourceRange(),
3312 E->getLocStart(), /*IsStringLocation*/false, CSR);
3313 break;
3314
3315 case Sema::VAK_Undefined:
3316 EmitFormatDiagnostic(
3317 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003318 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003319 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003320 << CallType
3321 << AT.getRepresentativeTypeName(S.Context)
3322 << CSR
3323 << E->getSourceRange(),
3324 E->getLocStart(), /*IsStringLocation*/false, CSR);
Jordan Rose22b74712012-09-05 22:56:19 +00003325 checkForCStrMembers(AT, E, CSR);
Richard Smithd7293d72013-08-05 18:49:43 +00003326 break;
3327
3328 case Sema::VAK_Invalid:
3329 if (ExprTy->isObjCObjectType())
3330 EmitFormatDiagnostic(
3331 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3332 << S.getLangOpts().CPlusPlus11
3333 << ExprTy
3334 << CallType
3335 << AT.getRepresentativeTypeName(S.Context)
3336 << CSR
3337 << E->getSourceRange(),
3338 E->getLocStart(), /*IsStringLocation*/false, CSR);
3339 else
3340 // FIXME: If this is an initializer list, suggest removing the braces
3341 // or inserting a cast to the target type.
3342 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3343 << isa<InitListExpr>(E) << ExprTy << CallType
3344 << AT.getRepresentativeTypeName(S.Context)
3345 << E->getSourceRange();
3346 break;
3347 }
3348
3349 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3350 "format string specifier index out of range");
3351 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003352 }
3353
Ted Kremenekab278de2010-01-28 23:39:18 +00003354 return true;
3355}
3356
Ted Kremenek02087932010-07-16 02:11:22 +00003357//===--- CHECK: Scanf format string checking ------------------------------===//
3358
3359namespace {
3360class CheckScanfHandler : public CheckFormatHandler {
3361public:
3362 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3363 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003364 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003365 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003366 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003367 Sema::VariadicCallType CallType,
3368 llvm::SmallBitVector &CheckedVarArgs)
3369 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3370 numDataArgs, beg, hasVAListArg,
3371 Args, formatIdx, inFunctionCall, CallType,
3372 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003373 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003374
3375 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3376 const char *startSpecifier,
3377 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003378
3379 bool HandleInvalidScanfConversionSpecifier(
3380 const analyze_scanf::ScanfSpecifier &FS,
3381 const char *startSpecifier,
3382 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003383
3384 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00003385};
Ted Kremenek019d2242010-01-29 01:50:07 +00003386}
Ted Kremenekab278de2010-01-28 23:39:18 +00003387
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003388void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3389 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003390 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3391 getLocationOfByte(end), /*IsStringLocation*/true,
3392 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003393}
3394
Ted Kremenekce815422010-07-19 21:25:57 +00003395bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3396 const analyze_scanf::ScanfSpecifier &FS,
3397 const char *startSpecifier,
3398 unsigned specifierLen) {
3399
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003400 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003401 FS.getConversionSpecifier();
3402
3403 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3404 getLocationOfByte(CS.getStart()),
3405 startSpecifier, specifierLen,
3406 CS.getStart(), CS.getLength());
3407}
3408
Ted Kremenek02087932010-07-16 02:11:22 +00003409bool CheckScanfHandler::HandleScanfSpecifier(
3410 const analyze_scanf::ScanfSpecifier &FS,
3411 const char *startSpecifier,
3412 unsigned specifierLen) {
3413
3414 using namespace analyze_scanf;
3415 using namespace analyze_format_string;
3416
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003417 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003418
Ted Kremenek6cd69422010-07-19 22:01:06 +00003419 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3420 // be used to decide if we are using positional arguments consistently.
3421 if (FS.consumesDataArgument()) {
3422 if (atFirstArg) {
3423 atFirstArg = false;
3424 usesPositionalArgs = FS.usesPositionalArg();
3425 }
3426 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003427 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3428 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003429 return false;
3430 }
Ted Kremenek02087932010-07-16 02:11:22 +00003431 }
3432
3433 // Check if the field with is non-zero.
3434 const OptionalAmount &Amt = FS.getFieldWidth();
3435 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3436 if (Amt.getConstantAmount() == 0) {
3437 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3438 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00003439 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3440 getLocationOfByte(Amt.getStart()),
3441 /*IsStringLocation*/true, R,
3442 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00003443 }
3444 }
3445
3446 if (!FS.consumesDataArgument()) {
3447 // FIXME: Technically specifying a precision or field width here
3448 // makes no sense. Worth issuing a warning at some point.
3449 return true;
3450 }
3451
3452 // Consume the argument.
3453 unsigned argIndex = FS.getArgIndex();
3454 if (argIndex < NumDataArgs) {
3455 // The check to see if the argIndex is valid will come later.
3456 // We set the bit here because we may exit early from this
3457 // function if we encounter some other error.
3458 CoveredArgs.set(argIndex);
3459 }
3460
Ted Kremenek4407ea42010-07-20 20:04:47 +00003461 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003462 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003463 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3464 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003465 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003466 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003467 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003468 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3469 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003470
Jordan Rose92303592012-09-08 04:00:03 +00003471 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3472 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3473
Ted Kremenek02087932010-07-16 02:11:22 +00003474 // The remaining checks depend on the data arguments.
3475 if (HasVAListArg)
3476 return true;
3477
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003478 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00003479 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00003480
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003481 // Check that the argument type matches the format specifier.
3482 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003483 if (!Ex)
3484 return true;
3485
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003486 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3487 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003488 ScanfSpecifier fixedFS = FS;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003489 bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
Hans Wennborgd99d6882012-02-15 09:59:46 +00003490 S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003491
3492 if (success) {
3493 // Get the fix string from the fixed format specifier.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003494 SmallString<128> buf;
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003495 llvm::raw_svector_ostream os(buf);
3496 fixedFS.toString(os);
3497
3498 EmitFormatDiagnostic(
3499 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003500 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003501 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003502 Ex->getLocStart(),
3503 /*IsStringLocation*/false,
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003504 getSpecifierRange(startSpecifier, specifierLen),
3505 FixItHint::CreateReplacement(
3506 getSpecifierRange(startSpecifier, specifierLen),
3507 os.str()));
3508 } else {
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003509 EmitFormatDiagnostic(
3510 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00003511 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003512 << Ex->getSourceRange(),
Matt Beaumont-Gay32d825a2012-05-17 00:03:16 +00003513 Ex->getLocStart(),
3514 /*IsStringLocation*/false,
Jean-Daniel Dupascb197b02012-01-31 18:12:08 +00003515 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00003516 }
3517 }
3518
Ted Kremenek02087932010-07-16 02:11:22 +00003519 return true;
3520}
3521
3522void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00003523 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003524 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003525 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003526 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00003527 bool inFunctionCall, VariadicCallType CallType,
3528 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003529
Ted Kremenekab278de2010-01-28 23:39:18 +00003530 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00003531 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003532 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003533 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003534 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3535 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003536 return;
3537 }
Ted Kremenek02087932010-07-16 02:11:22 +00003538
Ted Kremenekab278de2010-01-28 23:39:18 +00003539 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003540 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00003541 const char *Str = StrRef.data();
3542 unsigned StrLen = StrRef.size();
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003543 const unsigned numDataArgs = Args.size() - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00003544
Ted Kremenekab278de2010-01-28 23:39:18 +00003545 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00003546 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003547 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003548 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00003549 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3550 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00003551 return;
3552 }
Ted Kremenek02087932010-07-16 02:11:22 +00003553
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003554 if (Type == FST_Printf || Type == FST_NSString) {
Ted Kremenek02087932010-07-16 02:11:22 +00003555 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003556 numDataArgs, (Type == FST_NSString),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003557 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003558 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003559
Hans Wennborg23926bd2011-12-15 10:25:47 +00003560 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003561 getLangOpts(),
3562 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003563 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003564 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003565 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003566 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00003567 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00003568
Hans Wennborg23926bd2011-12-15 10:25:47 +00003569 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00003570 getLangOpts(),
3571 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00003572 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003573 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00003574}
3575
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003576//===--- CHECK: Standard memory functions ---------------------------------===//
3577
Nico Weber0e6daef2013-12-26 23:38:39 +00003578/// \brief Takes the expression passed to the size_t parameter of functions
3579/// such as memcmp, strncat, etc and warns if it's a comparison.
3580///
3581/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
3582static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
3583 IdentifierInfo *FnName,
3584 SourceLocation FnLoc,
3585 SourceLocation RParenLoc) {
3586 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
3587 if (!Size)
3588 return false;
3589
3590 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
3591 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
3592 return false;
3593
3594 Preprocessor &PP = S.getPreprocessor();
3595 SourceRange SizeRange = Size->getSourceRange();
3596 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
3597 << SizeRange << FnName;
3598 S.Diag(FnLoc, diag::warn_memsize_comparison_paren_note)
3599 << FnName
3600 << FixItHint::CreateInsertion(
3601 PP.getLocForEndOfToken(Size->getLHS()->getLocEnd()),
3602 ")")
3603 << FixItHint::CreateRemoval(RParenLoc);
3604 S.Diag(SizeRange.getBegin(), diag::warn_memsize_comparison_cast_note)
3605 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
3606 << FixItHint::CreateInsertion(
3607 PP.getLocForEndOfToken(SizeRange.getEnd()), ")");
3608
3609 return true;
3610}
3611
Douglas Gregora74926b2011-05-03 20:05:22 +00003612/// \brief Determine whether the given type is a dynamic class type (e.g.,
3613/// whether it has a vtable).
3614static bool isDynamicClassType(QualType T) {
3615 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3616 if (CXXRecordDecl *Definition = Record->getDefinition())
3617 if (Definition->isDynamicClass())
3618 return true;
3619
3620 return false;
3621}
3622
Chandler Carruth889ed862011-06-21 23:04:20 +00003623/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003624/// otherwise returns NULL.
3625static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00003626 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003627 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3628 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3629 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003630
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003631 return 0;
3632}
3633
Chandler Carruth889ed862011-06-21 23:04:20 +00003634/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003635static QualType getSizeOfArgType(const Expr* E) {
3636 if (const UnaryExprOrTypeTraitExpr *SizeOf =
3637 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3638 if (SizeOf->getKind() == clang::UETT_SizeOf)
3639 return SizeOf->getTypeOfArgument();
3640
3641 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00003642}
3643
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003644/// \brief Check for dangerous or invalid arguments to memset().
3645///
Chandler Carruthac687262011-06-03 06:23:57 +00003646/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003647/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3648/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003649///
3650/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003651void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00003652 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00003653 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00003654 assert(BId != 0);
3655
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003656 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00003657 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00003658 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00003659 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00003660 return;
3661
Anna Zaks22122702012-01-17 00:37:07 +00003662 unsigned LastArg = (BId == Builtin::BImemset ||
3663 BId == Builtin::BIstrndup ? 1 : 2);
3664 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00003665 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003666
Nico Weber0e6daef2013-12-26 23:38:39 +00003667 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
3668 Call->getLocStart(), Call->getRParenLoc()))
3669 return;
3670
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003671 // We have special checking when the length is a sizeof expression.
3672 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3673 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3674 llvm::FoldingSetNodeID SizeOfArgID;
3675
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003676 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3677 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00003678 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003679
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003680 QualType DestTy = Dest->getType();
3681 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3682 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00003683
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003684 // Never warn about void type pointers. This can be used to suppress
3685 // false positives.
3686 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003687 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003688
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003689 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3690 // actually comparing the expressions for equality. Because computing the
3691 // expression IDs can be expensive, we only do this if the diagnostic is
3692 // enabled.
3693 if (SizeOfArg &&
3694 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3695 SizeOfArg->getExprLoc())) {
3696 // We only compute IDs for expressions if the warning is enabled, and
3697 // cache the sizeof arg's ID.
3698 if (SizeOfArgID == llvm::FoldingSetNodeID())
3699 SizeOfArg->Profile(SizeOfArgID, Context, true);
3700 llvm::FoldingSetNodeID DestID;
3701 Dest->Profile(DestID, Context, true);
3702 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00003703 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3704 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003705 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00003706 StringRef ReadableName = FnName->getName();
3707
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003708 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00003709 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003710 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00003711 if (!PointeeTy->isIncompleteType() &&
3712 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003713 ActionIdx = 2; // If the pointee's size is sizeof(char),
3714 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00003715
3716 // If the function is defined as a builtin macro, do not show macro
3717 // expansion.
3718 SourceLocation SL = SizeOfArg->getExprLoc();
3719 SourceRange DSR = Dest->getSourceRange();
3720 SourceRange SSR = SizeOfArg->getSourceRange();
3721 SourceManager &SM = PP.getSourceManager();
3722
3723 if (SM.isMacroArgExpansion(SL)) {
3724 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3725 SL = SM.getSpellingLoc(SL);
3726 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3727 SM.getSpellingLoc(DSR.getEnd()));
3728 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3729 SM.getSpellingLoc(SSR.getEnd()));
3730 }
3731
Anna Zaksd08d9152012-05-30 23:14:52 +00003732 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003733 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00003734 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00003735 << PointeeTy
3736 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00003737 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00003738 << SSR);
3739 DiagRuntimeBehavior(SL, SizeOfArg,
3740 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3741 << ActionIdx
3742 << SSR);
3743
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00003744 break;
3745 }
3746 }
3747
3748 // Also check for cases where the sizeof argument is the exact same
3749 // type as the memory argument, and where it points to a user-defined
3750 // record type.
3751 if (SizeOfArgTy != QualType()) {
3752 if (PointeeTy->isRecordType() &&
3753 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3754 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3755 PDiag(diag::warn_sizeof_pointer_type_memaccess)
3756 << FnName << SizeOfArgTy << ArgIdx
3757 << PointeeTy << Dest->getSourceRange()
3758 << LenExpr->getSourceRange());
3759 break;
3760 }
Nico Weberc5e73862011-06-14 16:14:58 +00003761 }
3762
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003763 // Always complain about dynamic classes.
Anna Zaks22122702012-01-17 00:37:07 +00003764 if (isDynamicClassType(PointeeTy)) {
3765
3766 unsigned OperationType = 0;
3767 // "overwritten" if we're warning about the destination for any call
3768 // but memcmp; otherwise a verb appropriate to the call.
3769 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3770 if (BId == Builtin::BImemcpy)
3771 OperationType = 1;
3772 else if(BId == Builtin::BImemmove)
3773 OperationType = 2;
3774 else if (BId == Builtin::BImemcmp)
3775 OperationType = 3;
3776 }
3777
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003778 DiagRuntimeBehavior(
3779 Dest->getExprLoc(), Dest,
3780 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00003781 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Anna Zaks201d4892012-01-13 21:52:01 +00003782 << FnName << PointeeTy
Anna Zaks22122702012-01-17 00:37:07 +00003783 << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003784 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00003785 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3786 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00003787 DiagRuntimeBehavior(
3788 Dest->getExprLoc(), Dest,
3789 PDiag(diag::warn_arc_object_memaccess)
3790 << ArgIdx << FnName << PointeeTy
3791 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00003792 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003793 continue;
John McCall31168b02011-06-15 23:02:42 +00003794
3795 DiagRuntimeBehavior(
3796 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00003797 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00003798 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3799 break;
3800 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00003801 }
3802}
3803
Ted Kremenek6865f772011-08-18 20:55:45 +00003804// A little helper routine: ignore addition and subtraction of integer literals.
3805// This intentionally does not ignore all integer constant expressions because
3806// we don't want to remove sizeof().
3807static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3808 Ex = Ex->IgnoreParenCasts();
3809
3810 for (;;) {
3811 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3812 if (!BO || !BO->isAdditiveOp())
3813 break;
3814
3815 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3816 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3817
3818 if (isa<IntegerLiteral>(RHS))
3819 Ex = LHS;
3820 else if (isa<IntegerLiteral>(LHS))
3821 Ex = RHS;
3822 else
3823 break;
3824 }
3825
3826 return Ex;
3827}
3828
Anna Zaks13b08572012-08-08 21:42:23 +00003829static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3830 ASTContext &Context) {
3831 // Only handle constant-sized or VLAs, but not flexible members.
3832 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3833 // Only issue the FIXIT for arrays of size > 1.
3834 if (CAT->getSize().getSExtValue() <= 1)
3835 return false;
3836 } else if (!Ty->isVariableArrayType()) {
3837 return false;
3838 }
3839 return true;
3840}
3841
Ted Kremenek6865f772011-08-18 20:55:45 +00003842// Warn if the user has made the 'size' argument to strlcpy or strlcat
3843// be the size of the source, instead of the destination.
3844void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3845 IdentifierInfo *FnName) {
3846
3847 // Don't crash if the user has the wrong number of arguments
3848 if (Call->getNumArgs() != 3)
3849 return;
3850
3851 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3852 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3853 const Expr *CompareWithSrc = NULL;
Nico Weber0e6daef2013-12-26 23:38:39 +00003854
3855 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
3856 Call->getLocStart(), Call->getRParenLoc()))
3857 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00003858
3859 // Look for 'strlcpy(dst, x, sizeof(x))'
3860 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3861 CompareWithSrc = Ex;
3862 else {
3863 // Look for 'strlcpy(dst, x, strlen(x))'
3864 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00003865 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
3866 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00003867 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3868 }
3869 }
3870
3871 if (!CompareWithSrc)
3872 return;
3873
3874 // Determine if the argument to sizeof/strlen is equal to the source
3875 // argument. In principle there's all kinds of things you could do
3876 // here, for instance creating an == expression and evaluating it with
3877 // EvaluateAsBooleanCondition, but this uses a more direct technique:
3878 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3879 if (!SrcArgDRE)
3880 return;
3881
3882 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3883 if (!CompareWithSrcDRE ||
3884 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3885 return;
3886
3887 const Expr *OriginalSizeArg = Call->getArg(2);
3888 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3889 << OriginalSizeArg->getSourceRange() << FnName;
3890
3891 // Output a FIXIT hint if the destination is an array (rather than a
3892 // pointer to an array). This could be enhanced to handle some
3893 // pointers if we know the actual size, like if DstArg is 'array+2'
3894 // we could say 'sizeof(array)-2'.
3895 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00003896 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00003897 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003898
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00003899 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00003900 llvm::raw_svector_ostream OS(sizeString);
3901 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00003902 DstArg->printPretty(OS, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00003903 OS << ")";
3904
3905 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3906 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3907 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00003908}
3909
Anna Zaks314cd092012-02-01 19:08:57 +00003910/// Check if two expressions refer to the same declaration.
3911static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3912 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3913 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3914 return D1->getDecl() == D2->getDecl();
3915 return false;
3916}
3917
3918static const Expr *getStrlenExprArg(const Expr *E) {
3919 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3920 const FunctionDecl *FD = CE->getDirectCallee();
3921 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3922 return 0;
3923 return CE->getArg(0)->IgnoreParenCasts();
3924 }
3925 return 0;
3926}
3927
3928// Warn on anti-patterns as the 'size' argument to strncat.
3929// The correct size argument should look like following:
3930// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3931void Sema::CheckStrncatArguments(const CallExpr *CE,
3932 IdentifierInfo *FnName) {
3933 // Don't crash if the user has the wrong number of arguments.
3934 if (CE->getNumArgs() < 3)
3935 return;
3936 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3937 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3938 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3939
Nico Weber0e6daef2013-12-26 23:38:39 +00003940 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
3941 CE->getRParenLoc()))
3942 return;
3943
Anna Zaks314cd092012-02-01 19:08:57 +00003944 // Identify common expressions, which are wrongly used as the size argument
3945 // to strncat and may lead to buffer overflows.
3946 unsigned PatternType = 0;
3947 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3948 // - sizeof(dst)
3949 if (referToTheSameDecl(SizeOfArg, DstArg))
3950 PatternType = 1;
3951 // - sizeof(src)
3952 else if (referToTheSameDecl(SizeOfArg, SrcArg))
3953 PatternType = 2;
3954 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3955 if (BE->getOpcode() == BO_Sub) {
3956 const Expr *L = BE->getLHS()->IgnoreParenCasts();
3957 const Expr *R = BE->getRHS()->IgnoreParenCasts();
3958 // - sizeof(dst) - strlen(dst)
3959 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3960 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3961 PatternType = 1;
3962 // - sizeof(src) - (anything)
3963 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3964 PatternType = 2;
3965 }
3966 }
3967
3968 if (PatternType == 0)
3969 return;
3970
Anna Zaks5069aa32012-02-03 01:27:37 +00003971 // Generate the diagnostic.
3972 SourceLocation SL = LenArg->getLocStart();
3973 SourceRange SR = LenArg->getSourceRange();
3974 SourceManager &SM = PP.getSourceManager();
3975
3976 // If the function is defined as a builtin macro, do not show macro expansion.
3977 if (SM.isMacroArgExpansion(SL)) {
3978 SL = SM.getSpellingLoc(SL);
3979 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3980 SM.getSpellingLoc(SR.getEnd()));
3981 }
3982
Anna Zaks13b08572012-08-08 21:42:23 +00003983 // Check if the destination is an array (rather than a pointer to an array).
3984 QualType DstTy = DstArg->getType();
3985 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3986 Context);
3987 if (!isKnownSizeArray) {
3988 if (PatternType == 1)
3989 Diag(SL, diag::warn_strncat_wrong_size) << SR;
3990 else
3991 Diag(SL, diag::warn_strncat_src_size) << SR;
3992 return;
3993 }
3994
Anna Zaks314cd092012-02-01 19:08:57 +00003995 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00003996 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003997 else
Anna Zaks5069aa32012-02-03 01:27:37 +00003998 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00003999
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004000 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00004001 llvm::raw_svector_ostream OS(sizeString);
4002 OS << "sizeof(";
Richard Smith235341b2012-08-16 03:56:14 +00004003 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004004 OS << ") - ";
4005 OS << "strlen(";
Richard Smith235341b2012-08-16 03:56:14 +00004006 DstArg->printPretty(OS, 0, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00004007 OS << ") - 1";
4008
Anna Zaks5069aa32012-02-03 01:27:37 +00004009 Diag(SL, diag::note_strncat_wrong_size)
4010 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00004011}
4012
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004013//===--- CHECK: Return Address of Stack Variable --------------------------===//
4014
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004015static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4016 Decl *ParentDecl);
4017static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
4018 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004019
4020/// CheckReturnStackAddr - Check if a return statement returns the address
4021/// of a stack variable.
4022void
4023Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
4024 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00004025
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004026 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004027 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004028
4029 // Perform checking for returned stack addresses, local blocks,
4030 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00004031 if (lhsType->isPointerType() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00004032 (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004033 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
Mike Stump12b8ce12009-08-04 21:02:39 +00004034 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004035 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004036 }
4037
4038 if (stackE == 0)
4039 return; // Nothing suspicious was found.
4040
4041 SourceLocation diagLoc;
4042 SourceRange diagRange;
4043 if (refVars.empty()) {
4044 diagLoc = stackE->getLocStart();
4045 diagRange = stackE->getSourceRange();
4046 } else {
4047 // We followed through a reference variable. 'stackE' contains the
4048 // problematic expression but we will warn at the return statement pointing
4049 // at the reference variable. We will later display the "trail" of
4050 // reference variables using notes.
4051 diagLoc = refVars[0]->getLocStart();
4052 diagRange = refVars[0]->getSourceRange();
4053 }
4054
4055 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
4056 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
4057 : diag::warn_ret_stack_addr)
4058 << DR->getDecl()->getDeclName() << diagRange;
4059 } else if (isa<BlockExpr>(stackE)) { // local block.
4060 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
4061 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
4062 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
4063 } else { // local temporary.
4064 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4065 : diag::warn_ret_local_temp_addr)
4066 << diagRange;
4067 }
4068
4069 // Display the "trail" of reference variables that we followed until we
4070 // found the problematic expression using notes.
4071 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4072 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4073 // If this var binds to another reference var, show the range of the next
4074 // var, otherwise the var binds to the problematic expression, in which case
4075 // show the range of the expression.
4076 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4077 : stackE->getSourceRange();
4078 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4079 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004080 }
4081}
4082
4083/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4084/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004085/// to a location on the stack, a local block, an address of a label, or a
4086/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004087/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004088/// encounter a subexpression that (1) clearly does not lead to one of the
4089/// above problematic expressions (2) is something we cannot determine leads to
4090/// a problematic expression based on such local checking.
4091///
4092/// Both EvalAddr and EvalVal follow through reference variables to evaluate
4093/// the expression that they point to. Such variables are added to the
4094/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004095///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004096/// EvalAddr processes expressions that are pointers that are used as
4097/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004098/// At the base case of the recursion is a check for the above problematic
4099/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004100///
4101/// This implementation handles:
4102///
4103/// * pointer-to-pointer casts
4104/// * implicit conversions from array references to pointers
4105/// * taking the address of fields
4106/// * arbitrary interplay between "&" and "*" operators
4107/// * pointer arithmetic from an address of a stack variable
4108/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004109static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4110 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004111 if (E->isTypeDependent())
Craig Topper47005942013-08-02 05:10:31 +00004112 return NULL;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004113
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004114 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00004115 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00004116 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004117 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00004118 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00004119
Peter Collingbourne91147592011-04-15 00:35:48 +00004120 E = E->IgnoreParens();
4121
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004122 // Our "symbolic interpreter" is just a dispatch off the currently
4123 // viewed AST node. We then recursively traverse the AST by calling
4124 // EvalAddr and EvalVal appropriately.
4125 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004126 case Stmt::DeclRefExprClass: {
4127 DeclRefExpr *DR = cast<DeclRefExpr>(E);
4128
4129 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4130 // If this is a reference variable, follow through to the expression that
4131 // it points to.
4132 if (V->hasLocalStorage() &&
4133 V->getType()->isReferenceType() && V->hasInit()) {
4134 // Add the reference variable to the "trail".
4135 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004136 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004137 }
4138
4139 return NULL;
4140 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004141
Chris Lattner934edb22007-12-28 05:31:15 +00004142 case Stmt::UnaryOperatorClass: {
4143 // The only unary operator that make sense to handle here
4144 // is AddrOf. All others don't make sense as pointers.
4145 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004146
John McCalle3027922010-08-25 11:45:40 +00004147 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004148 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004149 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004150 return NULL;
4151 }
Mike Stump11289f42009-09-09 15:08:12 +00004152
Chris Lattner934edb22007-12-28 05:31:15 +00004153 case Stmt::BinaryOperatorClass: {
4154 // Handle pointer arithmetic. All other binary operators are not valid
4155 // in this context.
4156 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00004157 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00004158
John McCalle3027922010-08-25 11:45:40 +00004159 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00004160 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00004161
Chris Lattner934edb22007-12-28 05:31:15 +00004162 Expr *Base = B->getLHS();
4163
4164 // Determine which argument is the real pointer base. It could be
4165 // the RHS argument instead of the LHS.
4166 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00004167
Chris Lattner934edb22007-12-28 05:31:15 +00004168 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004169 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004170 }
Steve Naroff2752a172008-09-10 19:17:48 +00004171
Chris Lattner934edb22007-12-28 05:31:15 +00004172 // For conditional operators we need to see if either the LHS or RHS are
4173 // valid DeclRefExpr*s. If one of them is valid, we return it.
4174 case Stmt::ConditionalOperatorClass: {
4175 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004176
Chris Lattner934edb22007-12-28 05:31:15 +00004177 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004178 if (Expr *lhsExpr = C->getLHS()) {
4179 // In C++, we can have a throw-expression, which has 'void' type.
4180 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004181 if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004182 return LHS;
4183 }
Chris Lattner934edb22007-12-28 05:31:15 +00004184
Douglas Gregor270b2ef2010-10-21 16:21:08 +00004185 // In C++, we can have a throw-expression, which has 'void' type.
4186 if (C->getRHS()->getType()->isVoidType())
4187 return NULL;
4188
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004189 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00004190 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004191
4192 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00004193 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004194 return E; // local block.
4195 return NULL;
4196
4197 case Stmt::AddrLabelExprClass:
4198 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00004199
John McCall28fc7092011-11-10 05:35:25 +00004200 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004201 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4202 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004203
Ted Kremenekc3b4c522008-08-07 00:49:01 +00004204 // For casts, we need to handle conversions from arrays to
4205 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00004206 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00004207 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00004208 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00004209 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00004210 case Stmt::CXXStaticCastExprClass:
4211 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00004212 case Stmt::CXXConstCastExprClass:
4213 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00004214 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4215 switch (cast<CastExpr>(E)->getCastKind()) {
4216 case CK_BitCast:
4217 case CK_LValueToRValue:
4218 case CK_NoOp:
4219 case CK_BaseToDerived:
4220 case CK_DerivedToBase:
4221 case CK_UncheckedDerivedToBase:
4222 case CK_Dynamic:
4223 case CK_CPointerToObjCPointerCast:
4224 case CK_BlockPointerToObjCPointerCast:
4225 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004226 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004227
4228 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004229 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00004230
4231 default:
4232 return 0;
4233 }
Chris Lattner934edb22007-12-28 05:31:15 +00004234 }
Mike Stump11289f42009-09-09 15:08:12 +00004235
Douglas Gregorfe314812011-06-21 17:03:29 +00004236 case Stmt::MaterializeTemporaryExprClass:
4237 if (Expr *Result = EvalAddr(
4238 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004239 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004240 return Result;
4241
4242 return E;
4243
Chris Lattner934edb22007-12-28 05:31:15 +00004244 // Everything else: we simply don't reason about them.
4245 default:
4246 return NULL;
4247 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004248}
Mike Stump11289f42009-09-09 15:08:12 +00004249
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004250
4251/// EvalVal - This function is complements EvalAddr in the mutual recursion.
4252/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004253static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4254 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004255do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00004256 // We should only be called for evaluating non-pointer expressions, or
4257 // expressions with a pointer type that are not used as references but instead
4258 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00004259
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004260 // Our "symbolic interpreter" is just a dispatch off the currently
4261 // viewed AST node. We then recursively traverse the AST by calling
4262 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00004263
4264 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004265 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004266 case Stmt::ImplicitCastExprClass: {
4267 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00004268 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00004269 E = IE->getSubExpr();
4270 continue;
4271 }
4272 return NULL;
4273 }
4274
John McCall28fc7092011-11-10 05:35:25 +00004275 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004276 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00004277
Douglas Gregor4bd90e52009-10-23 18:54:35 +00004278 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004279 // When we hit a DeclRefExpr we are looking at code that refers to a
4280 // variable's name. If it's not a reference variable we check if it has
4281 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004282 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004283
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004284 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4285 // Check if it refers to itself, e.g. "int& i = i;".
4286 if (V == ParentDecl)
4287 return DR;
4288
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004289 if (V->hasLocalStorage()) {
4290 if (!V->getType()->isReferenceType())
4291 return DR;
4292
4293 // Reference variable, follow through to the expression that
4294 // it points to.
4295 if (V->hasInit()) {
4296 // Add the reference variable to the "trail".
4297 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004298 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004299 }
4300 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004303 return NULL;
4304 }
Mike Stump11289f42009-09-09 15:08:12 +00004305
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004306 case Stmt::UnaryOperatorClass: {
4307 // The only unary operator that make sense to handle here
4308 // is Deref. All others don't resolve to a "name." This includes
4309 // handling all sorts of rvalues passed to a unary operator.
4310 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004311
John McCalle3027922010-08-25 11:45:40 +00004312 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004313 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004314
4315 return NULL;
4316 }
Mike Stump11289f42009-09-09 15:08:12 +00004317
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004318 case Stmt::ArraySubscriptExprClass: {
4319 // Array subscripts are potential references to data on the stack. We
4320 // retrieve the DeclRefExpr* for the array variable if it indeed
4321 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004322 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004323 }
Mike Stump11289f42009-09-09 15:08:12 +00004324
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004325 case Stmt::ConditionalOperatorClass: {
4326 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004327 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004328 ConditionalOperator *C = cast<ConditionalOperator>(E);
4329
Anders Carlsson801c5c72007-11-30 19:04:31 +00004330 // Handle the GNU extension for missing LHS.
4331 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004332 if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
Anders Carlsson801c5c72007-11-30 19:04:31 +00004333 return LHS;
4334
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004335 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004338 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00004339 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004340 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00004341
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004342 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004343 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004344 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00004345
4346 // Check whether the member type is itself a reference, in which case
4347 // we're not going to refer to the member, but to what the member refers to.
4348 if (M->getMemberDecl()->getType()->isReferenceType())
4349 return NULL;
4350
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004351 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004352 }
Mike Stump11289f42009-09-09 15:08:12 +00004353
Douglas Gregorfe314812011-06-21 17:03:29 +00004354 case Stmt::MaterializeTemporaryExprClass:
4355 if (Expr *Result = EvalVal(
4356 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00004357 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00004358 return Result;
4359
4360 return E;
4361
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004362 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00004363 // Check that we don't return or take the address of a reference to a
4364 // temporary. This is only useful in C++.
4365 if (!E->isTypeDependent() && E->isRValue())
4366 return E;
4367
4368 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004369 return NULL;
4370 }
Ted Kremenekb7861562010-08-04 20:01:07 +00004371} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00004372}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004373
4374//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4375
4376/// Check for comparisons of floating point operands using != and ==.
4377/// Issue a warning if these are no self-comparisons, as they are not likely
4378/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00004379void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00004380 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4381 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004382
4383 // Special case: check for x == x (which is OK).
4384 // Do not emit warnings for such cases.
4385 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4386 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4387 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00004388 return;
Mike Stump11289f42009-09-09 15:08:12 +00004389
4390
Ted Kremenekeda40e22007-11-29 00:59:04 +00004391 // Special case: check for comparisons against literals that can be exactly
4392 // represented by APFloat. In such cases, do not emit a warning. This
4393 // is a heuristic: often comparison against such literals are used to
4394 // detect if a value in a variable has not changed. This clearly can
4395 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00004396 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4397 if (FLL->isExact())
4398 return;
4399 } else
4400 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4401 if (FLR->isExact())
4402 return;
Mike Stump11289f42009-09-09 15:08:12 +00004403
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004404 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00004405 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004406 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004407 return;
Mike Stump11289f42009-09-09 15:08:12 +00004408
David Blaikie1f4ff152012-07-16 20:47:22 +00004409 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00004410 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00004411 return;
Mike Stump11289f42009-09-09 15:08:12 +00004412
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004413 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00004414 Diag(Loc, diag::warn_floatingpoint_eq)
4415 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00004416}
John McCallca01b222010-01-04 23:21:16 +00004417
John McCall70aa5392010-01-06 05:24:50 +00004418//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4419//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00004420
John McCall70aa5392010-01-06 05:24:50 +00004421namespace {
John McCallca01b222010-01-04 23:21:16 +00004422
John McCall70aa5392010-01-06 05:24:50 +00004423/// Structure recording the 'active' range of an integer-valued
4424/// expression.
4425struct IntRange {
4426 /// The number of bits active in the int.
4427 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00004428
John McCall70aa5392010-01-06 05:24:50 +00004429 /// True if the int is known not to have negative values.
4430 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00004431
John McCall70aa5392010-01-06 05:24:50 +00004432 IntRange(unsigned Width, bool NonNegative)
4433 : Width(Width), NonNegative(NonNegative)
4434 {}
John McCallca01b222010-01-04 23:21:16 +00004435
John McCall817d4af2010-11-10 23:38:19 +00004436 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00004437 static IntRange forBoolType() {
4438 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00004439 }
4440
John McCall817d4af2010-11-10 23:38:19 +00004441 /// Returns the range of an opaque value of the given integral type.
4442 static IntRange forValueOfType(ASTContext &C, QualType T) {
4443 return forValueOfCanonicalType(C,
4444 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00004445 }
4446
John McCall817d4af2010-11-10 23:38:19 +00004447 /// Returns the range of an opaque value of a canonical integral type.
4448 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00004449 assert(T->isCanonicalUnqualified());
4450
4451 if (const VectorType *VT = dyn_cast<VectorType>(T))
4452 T = VT->getElementType().getTypePtr();
4453 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4454 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00004455
David Majnemer6a426652013-06-07 22:07:20 +00004456 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00004457 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00004458 EnumDecl *Enum = ET->getDecl();
4459 if (!Enum->isCompleteDefinition())
4460 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00004461
David Majnemer6a426652013-06-07 22:07:20 +00004462 unsigned NumPositive = Enum->getNumPositiveBits();
4463 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00004464
David Majnemer6a426652013-06-07 22:07:20 +00004465 if (NumNegative == 0)
4466 return IntRange(NumPositive, true/*NonNegative*/);
4467 else
4468 return IntRange(std::max(NumPositive + 1, NumNegative),
4469 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00004470 }
John McCall70aa5392010-01-06 05:24:50 +00004471
4472 const BuiltinType *BT = cast<BuiltinType>(T);
4473 assert(BT->isInteger());
4474
4475 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4476 }
4477
John McCall817d4af2010-11-10 23:38:19 +00004478 /// Returns the "target" range of a canonical integral type, i.e.
4479 /// the range of values expressible in the type.
4480 ///
4481 /// This matches forValueOfCanonicalType except that enums have the
4482 /// full range of their type, not the range of their enumerators.
4483 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4484 assert(T->isCanonicalUnqualified());
4485
4486 if (const VectorType *VT = dyn_cast<VectorType>(T))
4487 T = VT->getElementType().getTypePtr();
4488 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4489 T = CT->getElementType().getTypePtr();
4490 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00004491 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00004492
4493 const BuiltinType *BT = cast<BuiltinType>(T);
4494 assert(BT->isInteger());
4495
4496 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4497 }
4498
4499 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00004500 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00004501 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00004502 L.NonNegative && R.NonNegative);
4503 }
4504
John McCall817d4af2010-11-10 23:38:19 +00004505 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00004506 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00004507 return IntRange(std::min(L.Width, R.Width),
4508 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00004509 }
4510};
4511
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004512static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4513 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004514 if (value.isSigned() && value.isNegative())
4515 return IntRange(value.getMinSignedBits(), false);
4516
4517 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00004518 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004519
4520 // isNonNegative() just checks the sign bit without considering
4521 // signedness.
4522 return IntRange(value.getActiveBits(), true);
4523}
4524
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004525static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4526 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004527 if (result.isInt())
4528 return GetValueRange(C, result.getInt(), MaxWidth);
4529
4530 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00004531 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4532 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4533 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4534 R = IntRange::join(R, El);
4535 }
John McCall70aa5392010-01-06 05:24:50 +00004536 return R;
4537 }
4538
4539 if (result.isComplexInt()) {
4540 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4541 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4542 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00004543 }
4544
4545 // This can happen with lossless casts to intptr_t of "based" lvalues.
4546 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00004547 // FIXME: The only reason we need to pass the type in here is to get
4548 // the sign right on this one case. It would be nice if APValue
4549 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004550 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00004551 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00004552}
John McCall70aa5392010-01-06 05:24:50 +00004553
Eli Friedmane6d33952013-07-08 20:20:06 +00004554static QualType GetExprType(Expr *E) {
4555 QualType Ty = E->getType();
4556 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4557 Ty = AtomicRHS->getValueType();
4558 return Ty;
4559}
4560
John McCall70aa5392010-01-06 05:24:50 +00004561/// Pseudo-evaluate the given integer expression, estimating the
4562/// range of values it might take.
4563///
4564/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004565static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00004566 E = E->IgnoreParens();
4567
4568 // Try a full evaluation first.
4569 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00004570 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00004571 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00004572
4573 // I think we only want to look through implicit casts here; if the
4574 // user has an explicit widening cast, we should treat the value as
4575 // being of the new, wider type.
4576 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00004577 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00004578 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4579
Eli Friedmane6d33952013-07-08 20:20:06 +00004580 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00004581
John McCalle3027922010-08-25 11:45:40 +00004582 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00004583
John McCall70aa5392010-01-06 05:24:50 +00004584 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00004585 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00004586 return OutputTypeRange;
4587
4588 IntRange SubRange
4589 = GetExprRange(C, CE->getSubExpr(),
4590 std::min(MaxWidth, OutputTypeRange.Width));
4591
4592 // Bail out if the subexpr's range is as wide as the cast type.
4593 if (SubRange.Width >= OutputTypeRange.Width)
4594 return OutputTypeRange;
4595
4596 // Otherwise, we take the smaller width, and we're non-negative if
4597 // either the output type or the subexpr is.
4598 return IntRange(SubRange.Width,
4599 SubRange.NonNegative || OutputTypeRange.NonNegative);
4600 }
4601
4602 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4603 // If we can fold the condition, just take that operand.
4604 bool CondResult;
4605 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4606 return GetExprRange(C, CondResult ? CO->getTrueExpr()
4607 : CO->getFalseExpr(),
4608 MaxWidth);
4609
4610 // Otherwise, conservatively merge.
4611 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4612 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4613 return IntRange::join(L, R);
4614 }
4615
4616 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4617 switch (BO->getOpcode()) {
4618
4619 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00004620 case BO_LAnd:
4621 case BO_LOr:
4622 case BO_LT:
4623 case BO_GT:
4624 case BO_LE:
4625 case BO_GE:
4626 case BO_EQ:
4627 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00004628 return IntRange::forBoolType();
4629
John McCallc3688382011-07-13 06:35:24 +00004630 // The type of the assignments is the type of the LHS, so the RHS
4631 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00004632 case BO_MulAssign:
4633 case BO_DivAssign:
4634 case BO_RemAssign:
4635 case BO_AddAssign:
4636 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00004637 case BO_XorAssign:
4638 case BO_OrAssign:
4639 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00004640 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00004641
John McCallc3688382011-07-13 06:35:24 +00004642 // Simple assignments just pass through the RHS, which will have
4643 // been coerced to the LHS type.
4644 case BO_Assign:
4645 // TODO: bitfields?
4646 return GetExprRange(C, BO->getRHS(), MaxWidth);
4647
John McCall70aa5392010-01-06 05:24:50 +00004648 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004649 case BO_PtrMemD:
4650 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00004651 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004652
John McCall2ce81ad2010-01-06 22:07:33 +00004653 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00004654 case BO_And:
4655 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00004656 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4657 GetExprRange(C, BO->getRHS(), MaxWidth));
4658
John McCall70aa5392010-01-06 05:24:50 +00004659 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00004660 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00004661 // ...except that we want to treat '1 << (blah)' as logically
4662 // positive. It's an important idiom.
4663 if (IntegerLiteral *I
4664 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4665 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004666 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00004667 return IntRange(R.Width, /*NonNegative*/ true);
4668 }
4669 }
4670 // fallthrough
4671
John McCalle3027922010-08-25 11:45:40 +00004672 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00004673 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004674
John McCall2ce81ad2010-01-06 22:07:33 +00004675 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00004676 case BO_Shr:
4677 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00004678 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4679
4680 // If the shift amount is a positive constant, drop the width by
4681 // that much.
4682 llvm::APSInt shift;
4683 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4684 shift.isNonNegative()) {
4685 unsigned zext = shift.getZExtValue();
4686 if (zext >= L.Width)
4687 L.Width = (L.NonNegative ? 0 : 1);
4688 else
4689 L.Width -= zext;
4690 }
4691
4692 return L;
4693 }
4694
4695 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00004696 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00004697 return GetExprRange(C, BO->getRHS(), MaxWidth);
4698
John McCall2ce81ad2010-01-06 22:07:33 +00004699 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00004700 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00004701 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00004702 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004703 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004704
John McCall51431812011-07-14 22:39:48 +00004705 // The width of a division result is mostly determined by the size
4706 // of the LHS.
4707 case BO_Div: {
4708 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004709 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004710 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4711
4712 // If the divisor is constant, use that.
4713 llvm::APSInt divisor;
4714 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4715 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4716 if (log2 >= L.Width)
4717 L.Width = (L.NonNegative ? 0 : 1);
4718 else
4719 L.Width = std::min(L.Width - log2, MaxWidth);
4720 return L;
4721 }
4722
4723 // Otherwise, just use the LHS's width.
4724 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4725 return IntRange(L.Width, L.NonNegative && R.NonNegative);
4726 }
4727
4728 // The result of a remainder can't be larger than the result of
4729 // either side.
4730 case BO_Rem: {
4731 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00004732 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00004733 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4734 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4735
4736 IntRange meet = IntRange::meet(L, R);
4737 meet.Width = std::min(meet.Width, MaxWidth);
4738 return meet;
4739 }
4740
4741 // The default behavior is okay for these.
4742 case BO_Mul:
4743 case BO_Add:
4744 case BO_Xor:
4745 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00004746 break;
4747 }
4748
John McCall51431812011-07-14 22:39:48 +00004749 // The default case is to treat the operation as if it were closed
4750 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00004751 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4752 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4753 return IntRange::join(L, R);
4754 }
4755
4756 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4757 switch (UO->getOpcode()) {
4758 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00004759 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00004760 return IntRange::forBoolType();
4761
4762 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00004763 case UO_Deref:
4764 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00004765 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004766
4767 default:
4768 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4769 }
4770 }
4771
Ted Kremeneka553fbf2013-10-14 18:55:27 +00004772 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4773 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4774
John McCalld25db7e2013-05-06 21:39:12 +00004775 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00004776 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00004777 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00004778
Eli Friedmane6d33952013-07-08 20:20:06 +00004779 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00004780}
John McCall263a48b2010-01-04 23:31:57 +00004781
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004782static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00004783 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00004784}
4785
John McCall263a48b2010-01-04 23:31:57 +00004786/// Checks whether the given value, which currently has the given
4787/// source semantics, has the same value when coerced through the
4788/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004789static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4790 const llvm::fltSemantics &Src,
4791 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004792 llvm::APFloat truncated = value;
4793
4794 bool ignored;
4795 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4796 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4797
4798 return truncated.bitwiseIsEqual(value);
4799}
4800
4801/// Checks whether the given value, which currently has the given
4802/// source semantics, has the same value when coerced through the
4803/// target semantics.
4804///
4805/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004806static bool IsSameFloatAfterCast(const APValue &value,
4807 const llvm::fltSemantics &Src,
4808 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00004809 if (value.isFloat())
4810 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4811
4812 if (value.isVector()) {
4813 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4814 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4815 return false;
4816 return true;
4817 }
4818
4819 assert(value.isComplexFloat());
4820 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4821 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4822}
4823
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004824static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00004825
Ted Kremenek6274be42010-09-23 21:43:44 +00004826static bool IsZero(Sema &S, Expr *E) {
4827 // Suppress cases where we are comparing against an enum constant.
4828 if (const DeclRefExpr *DR =
4829 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4830 if (isa<EnumConstantDecl>(DR->getDecl()))
4831 return false;
4832
4833 // Suppress cases where the '0' value is expanded from a macro.
4834 if (E->getLocStart().isMacroID())
4835 return false;
4836
John McCallcc7e5bf2010-05-06 08:58:33 +00004837 llvm::APSInt Value;
4838 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4839}
4840
John McCall2551c1b2010-10-06 00:25:24 +00004841static bool HasEnumType(Expr *E) {
4842 // Strip off implicit integral promotions.
4843 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004844 if (ICE->getCastKind() != CK_IntegralCast &&
4845 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00004846 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00004847 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00004848 }
4849
4850 return E->getType()->isEnumeralType();
4851}
4852
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004853static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00004854 // Disable warning in template instantiations.
4855 if (!S.ActiveTemplateInstantiations.empty())
4856 return;
4857
John McCalle3027922010-08-25 11:45:40 +00004858 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00004859 if (E->isValueDependent())
4860 return;
4861
John McCalle3027922010-08-25 11:45:40 +00004862 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004863 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004864 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004865 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004866 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004867 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004868 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004869 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004870 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004871 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004872 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004873 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00004874 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00004875 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00004876 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00004877 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4878 }
4879}
4880
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004881static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004882 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004883 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004884 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00004885 // Disable warning in template instantiations.
4886 if (!S.ActiveTemplateInstantiations.empty())
4887 return;
4888
Richard Trieu560910c2012-11-14 22:50:24 +00004889 // 0 values are handled later by CheckTrivialUnsignedComparison().
4890 if (Value == 0)
4891 return;
4892
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004893 BinaryOperatorKind op = E->getOpcode();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004894 QualType OtherT = Other->getType();
4895 QualType ConstantT = Constant->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00004896 QualType CommonT = E->getLHS()->getType();
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004897 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004898 return;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004899 assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004900 && "comparison with non-integer type");
Richard Trieu560910c2012-11-14 22:50:24 +00004901
4902 bool ConstantSigned = ConstantT->isSignedIntegerType();
Richard Trieu560910c2012-11-14 22:50:24 +00004903 bool CommonSigned = CommonT->isSignedIntegerType();
4904
4905 bool EqualityOnly = false;
4906
4907 // TODO: Investigate using GetExprRange() to get tighter bounds on
4908 // on the bit ranges.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004909 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
Richard Trieu560910c2012-11-14 22:50:24 +00004910 unsigned OtherWidth = OtherRange.Width;
4911
4912 if (CommonSigned) {
4913 // The common type is signed, therefore no signed to unsigned conversion.
Eli Friedman5ac98752012-11-30 23:09:29 +00004914 if (!OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004915 // Check that the constant is representable in type OtherT.
4916 if (ConstantSigned) {
4917 if (OtherWidth >= Value.getMinSignedBits())
4918 return;
4919 } else { // !ConstantSigned
4920 if (OtherWidth >= Value.getActiveBits() + 1)
4921 return;
4922 }
4923 } else { // !OtherSigned
4924 // Check that the constant is representable in type OtherT.
4925 // Negative values are out of range.
4926 if (ConstantSigned) {
4927 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4928 return;
4929 } else { // !ConstantSigned
4930 if (OtherWidth >= Value.getActiveBits())
4931 return;
4932 }
4933 }
4934 } else { // !CommonSigned
Eli Friedman5ac98752012-11-30 23:09:29 +00004935 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00004936 if (OtherWidth >= Value.getActiveBits())
4937 return;
Eli Friedman5ac98752012-11-30 23:09:29 +00004938 } else if (!OtherRange.NonNegative && !ConstantSigned) {
Richard Trieu560910c2012-11-14 22:50:24 +00004939 // Check to see if the constant is representable in OtherT.
4940 if (OtherWidth > Value.getActiveBits())
4941 return;
4942 // Check to see if the constant is equivalent to a negative value
4943 // cast to CommonT.
4944 if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
Richard Trieu03c3a2f2012-11-15 03:43:50 +00004945 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
Richard Trieu560910c2012-11-14 22:50:24 +00004946 return;
4947 // The constant value rests between values that OtherT can represent after
4948 // conversion. Relational comparison still works, but equality
4949 // comparisons will be tautological.
4950 EqualityOnly = true;
4951 } else { // OtherSigned && ConstantSigned
4952 assert(0 && "Two signed types converted to unsigned types.");
4953 }
4954 }
4955
4956 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4957
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004958 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00004959 if (op == BO_EQ || op == BO_NE) {
4960 IsTrue = op == BO_NE;
4961 } else if (EqualityOnly) {
4962 return;
4963 } else if (RhsConstant) {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004964 if (op == BO_GT || op == BO_GE)
Richard Trieu560910c2012-11-14 22:50:24 +00004965 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004966 else // op == BO_LT || op == BO_LE
Richard Trieu560910c2012-11-14 22:50:24 +00004967 IsTrue = PositiveConstant;
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00004968 } else {
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004969 if (op == BO_LT || op == BO_LE)
Richard Trieu560910c2012-11-14 22:50:24 +00004970 IsTrue = !PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004971 else // op == BO_GT || op == BO_GE
Richard Trieu560910c2012-11-14 22:50:24 +00004972 IsTrue = PositiveConstant;
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004973 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00004974
4975 // If this is a comparison to an enum constant, include that
4976 // constant in the diagnostic.
4977 const EnumConstantDecl *ED = 0;
4978 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4979 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4980
4981 SmallString<64> PrettySourceValue;
4982 llvm::raw_svector_ostream OS(PrettySourceValue);
4983 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00004984 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00004985 else
4986 OS << Value;
4987
Richard Trieuc38786b2014-01-10 04:38:09 +00004988 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
4989 S.PDiag(diag::warn_out_of_range_compare)
4990 << OS.str() << OtherT << IsTrue
4991 << E->getLHS()->getSourceRange()
4992 << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00004993}
4994
John McCallcc7e5bf2010-05-06 08:58:33 +00004995/// Analyze the operands of the given comparison. Implements the
4996/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00004997static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00004998 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4999 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00005000}
John McCall263a48b2010-01-04 23:31:57 +00005001
John McCallca01b222010-01-04 23:21:16 +00005002/// \brief Implements -Wsign-compare.
5003///
Richard Trieu82402a02011-09-15 21:56:47 +00005004/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005005static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005006 // The type the comparison is being performed in.
5007 QualType T = E->getLHS()->getType();
5008 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
5009 && "comparison with mismatched types");
Fariborz Jahanian282071e2012-09-18 17:46:26 +00005010 if (E->isValueDependent())
5011 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005012
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005013 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
5014 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005015
5016 bool IsComparisonConstant = false;
5017
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005018 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005019 // of 'true' or 'false'.
5020 if (T->isIntegralType(S.Context)) {
5021 llvm::APSInt RHSValue;
5022 bool IsRHSIntegralLiteral =
5023 RHS->isIntegerConstantExpr(RHSValue, S.Context);
5024 llvm::APSInt LHSValue;
5025 bool IsLHSIntegralLiteral =
5026 LHS->isIntegerConstantExpr(LHSValue, S.Context);
5027 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
5028 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
5029 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
5030 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
5031 else
5032 IsComparisonConstant =
5033 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005034 } else if (!T->hasUnsignedIntegerRepresentation())
5035 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005036
John McCallcc7e5bf2010-05-06 08:58:33 +00005037 // We don't do anything special if this isn't an unsigned integral
5038 // comparison: we're only interested in integral comparisons, and
5039 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00005040 //
5041 // We also don't care about value-dependent expressions or expressions
5042 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005043 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00005044 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005045
John McCallcc7e5bf2010-05-06 08:58:33 +00005046 // Check to see if one of the (unmodified) operands is of different
5047 // signedness.
5048 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00005049 if (LHS->getType()->hasSignedIntegerRepresentation()) {
5050 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00005051 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00005052 signedOperand = LHS;
5053 unsignedOperand = RHS;
5054 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
5055 signedOperand = RHS;
5056 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00005057 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00005058 CheckTrivialUnsignedComparison(S, E);
5059 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005060 }
5061
John McCallcc7e5bf2010-05-06 08:58:33 +00005062 // Otherwise, calculate the effective range of the signed operand.
5063 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00005064
John McCallcc7e5bf2010-05-06 08:58:33 +00005065 // Go ahead and analyze implicit conversions in the operands. Note
5066 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00005067 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5068 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00005069
John McCallcc7e5bf2010-05-06 08:58:33 +00005070 // If the signed range is non-negative, -Wsign-compare won't fire,
5071 // but we should still check for comparisons which are always true
5072 // or false.
5073 if (signedRange.NonNegative)
5074 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00005075
5076 // For (in)equality comparisons, if the unsigned operand is a
5077 // constant which cannot collide with a overflowed signed operand,
5078 // then reinterpreting the signed operand as unsigned will not
5079 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00005080 if (E->isEqualityOp()) {
5081 unsigned comparisonWidth = S.Context.getIntWidth(T);
5082 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00005083
John McCallcc7e5bf2010-05-06 08:58:33 +00005084 // We should never be unable to prove that the unsigned operand is
5085 // non-negative.
5086 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5087
5088 if (unsignedRange.Width < comparisonWidth)
5089 return;
5090 }
5091
Douglas Gregorbfb4a212012-05-01 01:53:49 +00005092 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5093 S.PDiag(diag::warn_mixed_sign_comparison)
5094 << LHS->getType() << RHS->getType()
5095 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00005096}
5097
John McCall1f425642010-11-11 03:21:53 +00005098/// Analyzes an attempt to assign the given value to a bitfield.
5099///
5100/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005101static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5102 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00005103 assert(Bitfield->isBitField());
5104 if (Bitfield->isInvalidDecl())
5105 return false;
5106
John McCalldeebbcf2010-11-11 05:33:51 +00005107 // White-list bool bitfields.
5108 if (Bitfield->getType()->isBooleanType())
5109 return false;
5110
Douglas Gregor789adec2011-02-04 13:09:01 +00005111 // Ignore value- or type-dependent expressions.
5112 if (Bitfield->getBitWidth()->isValueDependent() ||
5113 Bitfield->getBitWidth()->isTypeDependent() ||
5114 Init->isValueDependent() ||
5115 Init->isTypeDependent())
5116 return false;
5117
John McCall1f425642010-11-11 03:21:53 +00005118 Expr *OriginalInit = Init->IgnoreParenImpCasts();
5119
Richard Smith5fab0c92011-12-28 19:48:30 +00005120 llvm::APSInt Value;
5121 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00005122 return false;
5123
John McCall1f425642010-11-11 03:21:53 +00005124 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00005125 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00005126
5127 if (OriginalWidth <= FieldWidth)
5128 return false;
5129
Eli Friedmanc267a322012-01-26 23:11:39 +00005130 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00005131 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00005132 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00005133
Eli Friedmanc267a322012-01-26 23:11:39 +00005134 // Check whether the stored value is equal to the original value.
5135 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00005136 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00005137 return false;
5138
Eli Friedmanc267a322012-01-26 23:11:39 +00005139 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00005140 // therefore don't strictly fit into a signed bitfield of width 1.
5141 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00005142 return false;
5143
John McCall1f425642010-11-11 03:21:53 +00005144 std::string PrettyValue = Value.toString(10);
5145 std::string PrettyTrunc = TruncatedValue.toString(10);
5146
5147 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5148 << PrettyValue << PrettyTrunc << OriginalInit->getType()
5149 << Init->getSourceRange();
5150
5151 return true;
5152}
5153
John McCalld2a53122010-11-09 23:24:47 +00005154/// Analyze the given simple or compound assignment for warning-worthy
5155/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005156static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00005157 // Just recurse on the LHS.
5158 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5159
5160 // We want to recurse on the RHS as normal unless we're assigning to
5161 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00005162 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005163 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00005164 E->getOperatorLoc())) {
5165 // Recurse, ignoring any implicit conversions on the RHS.
5166 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5167 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00005168 }
5169 }
5170
5171 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5172}
5173
John McCall263a48b2010-01-04 23:31:57 +00005174/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005175static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005176 SourceLocation CContext, unsigned diag,
5177 bool pruneControlFlow = false) {
5178 if (pruneControlFlow) {
5179 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5180 S.PDiag(diag)
5181 << SourceType << T << E->getSourceRange()
5182 << SourceRange(CContext));
5183 return;
5184 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00005185 S.Diag(E->getExprLoc(), diag)
5186 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5187}
5188
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005189/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005190static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00005191 SourceLocation CContext, unsigned diag,
5192 bool pruneControlFlow = false) {
5193 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00005194}
5195
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005196/// Diagnose an implicit cast from a literal expression. Does not warn when the
5197/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00005198void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5199 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005200 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00005201 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005202 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00005203 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5204 T->hasUnsignedIntegerRepresentation());
5205 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00005206 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005207 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00005208 return;
5209
Eli Friedman07185912013-08-29 23:44:43 +00005210 // FIXME: Force the precision of the source value down so we don't print
5211 // digits which are usually useless (we don't really care here if we
5212 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
5213 // would automatically print the shortest representation, but it's a bit
5214 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00005215 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00005216 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5217 precision = (precision * 59 + 195) / 196;
5218 Value.toString(PrettySourceValue, precision);
5219
David Blaikie9b88cc02012-05-15 17:18:27 +00005220 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00005221 if (T->isSpecificBuiltinType(BuiltinType::Bool))
5222 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5223 else
David Blaikie9b88cc02012-05-15 17:18:27 +00005224 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00005225
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00005226 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00005227 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5228 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00005229}
5230
John McCall18a2c2c2010-11-09 22:22:12 +00005231std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5232 if (!Range.Width) return "0";
5233
5234 llvm::APSInt ValueInRange = Value;
5235 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00005236 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00005237 return ValueInRange.toString(10);
5238}
5239
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005240static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5241 if (!isa<ImplicitCastExpr>(Ex))
5242 return false;
5243
5244 Expr *InnerE = Ex->IgnoreParenImpCasts();
5245 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5246 const Type *Source =
5247 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5248 if (Target->isDependentType())
5249 return false;
5250
5251 const BuiltinType *FloatCandidateBT =
5252 dyn_cast<BuiltinType>(ToBool ? Source : Target);
5253 const Type *BoolCandidateType = ToBool ? Target : Source;
5254
5255 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5256 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5257}
5258
5259void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5260 SourceLocation CC) {
5261 unsigned NumArgs = TheCall->getNumArgs();
5262 for (unsigned i = 0; i < NumArgs; ++i) {
5263 Expr *CurrA = TheCall->getArg(i);
5264 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5265 continue;
5266
5267 bool IsSwapped = ((i > 0) &&
5268 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5269 IsSwapped |= ((i < (NumArgs - 1)) &&
5270 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5271 if (IsSwapped) {
5272 // Warn on this floating-point to bool conversion.
5273 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5274 CurrA->getType(), CC,
5275 diag::warn_impcast_floating_point_to_bool);
5276 }
5277 }
5278}
5279
John McCallcc7e5bf2010-05-06 08:58:33 +00005280void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005281 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005282 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00005283
John McCallcc7e5bf2010-05-06 08:58:33 +00005284 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5285 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5286 if (Source == Target) return;
5287 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00005288
Chandler Carruthc22845a2011-07-26 05:40:03 +00005289 // If the conversion context location is invalid don't complain. We also
5290 // don't want to emit a warning if the issue occurs from the expansion of
5291 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5292 // delay this check as long as possible. Once we detect we are in that
5293 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005294 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00005295 return;
5296
Richard Trieu021baa32011-09-23 20:10:00 +00005297 // Diagnose implicit casts to bool.
5298 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5299 if (isa<StringLiteral>(E))
5300 // Warn on string literal to bool. Checks for string literals in logical
Nico Weber0e6daef2013-12-26 23:38:39 +00005301 // expressions, for instances, assert(0 && "error here"), are prevented
Richard Trieu021baa32011-09-23 20:10:00 +00005302 // by a check in AnalyzeImplicitConversions().
5303 return DiagnoseImpCast(S, E, T, CC,
5304 diag::warn_impcast_string_literal_to_bool);
Lang Hamesdf5c1212011-12-05 20:49:50 +00005305 if (Source->isFunctionType()) {
5306 // Warn on function to bool. Checks free functions and static member
5307 // functions. Weakly imported functions are excluded from the check,
5308 // since it's common to test their value to check whether the linker
5309 // found a definition for them.
5310 ValueDecl *D = 0;
5311 if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5312 D = R->getDecl();
5313 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5314 D = M->getMemberDecl();
5315 }
5316
5317 if (D && !D->isWeak()) {
Richard Trieu5f623222011-12-06 04:48:01 +00005318 if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5319 S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5320 << F << E->getSourceRange() << SourceRange(CC);
David Blaikie10eb4b62011-12-09 21:42:37 +00005321 S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5322 << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5323 QualType ReturnType;
5324 UnresolvedSet<4> NonTemplateOverloads;
David Blaikiee5323aa2013-06-21 23:54:45 +00005325 S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
David Blaikie10eb4b62011-12-09 21:42:37 +00005326 if (!ReturnType.isNull()
5327 && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5328 S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5329 << FixItHint::CreateInsertion(
5330 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu5f623222011-12-06 04:48:01 +00005331 return;
5332 }
Lang Hamesdf5c1212011-12-05 20:49:50 +00005333 }
5334 }
Richard Trieu021baa32011-09-23 20:10:00 +00005335 }
John McCall263a48b2010-01-04 23:31:57 +00005336
5337 // Strip vector types.
5338 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005339 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005340 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005341 return;
John McCallacf0ee52010-10-08 02:01:28 +00005342 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005343 }
Chris Lattneree7286f2011-06-14 04:51:15 +00005344
5345 // If the vector cast is cast between two vectors of the same size, it is
5346 // a bitcast, not a conversion.
5347 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5348 return;
John McCall263a48b2010-01-04 23:31:57 +00005349
5350 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5351 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5352 }
5353
5354 // Strip complex types.
5355 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005356 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005357 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005358 return;
5359
John McCallacf0ee52010-10-08 02:01:28 +00005360 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005361 }
John McCall263a48b2010-01-04 23:31:57 +00005362
5363 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5364 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5365 }
5366
5367 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5368 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5369
5370 // If the source is floating point...
5371 if (SourceBT && SourceBT->isFloatingPoint()) {
5372 // ...and the target is floating point...
5373 if (TargetBT && TargetBT->isFloatingPoint()) {
5374 // ...then warn if we're dropping FP rank.
5375
5376 // Builtin FP kinds are ordered by increasing FP rank.
5377 if (SourceBT->getKind() > TargetBT->getKind()) {
5378 // Don't warn about float constants that are precisely
5379 // representable in the target type.
5380 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005381 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00005382 // Value might be a float, a float vector, or a float complex.
5383 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00005384 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5385 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00005386 return;
5387 }
5388
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005389 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005390 return;
5391
John McCallacf0ee52010-10-08 02:01:28 +00005392 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00005393 }
5394 return;
5395 }
5396
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005397 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00005398 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005399 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005400 return;
5401
Chandler Carruth22c7a792011-02-17 11:05:49 +00005402 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00005403 // We also want to warn on, e.g., "int i = -1.234"
5404 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5405 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5406 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5407
Chandler Carruth016ef402011-04-10 08:36:24 +00005408 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5409 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00005410 } else {
5411 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5412 }
5413 }
John McCall263a48b2010-01-04 23:31:57 +00005414
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005415 // If the target is bool, warn if expr is a function or method call.
5416 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5417 isa<CallExpr>(E)) {
5418 // Check last argument of function call to see if it is an
5419 // implicit cast from a type matching the type the result
5420 // is being cast to.
5421 CallExpr *CEx = cast<CallExpr>(E);
5422 unsigned NumArgs = CEx->getNumArgs();
5423 if (NumArgs > 0) {
5424 Expr *LastA = CEx->getArg(NumArgs - 1);
5425 Expr *InnerE = LastA->IgnoreParenImpCasts();
5426 const Type *InnerType =
5427 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5428 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5429 // Warn on this floating-point to bool conversion
5430 DiagnoseImpCast(S, E, T, CC,
5431 diag::warn_impcast_floating_point_to_bool);
5432 }
5433 }
5434 }
John McCall263a48b2010-01-04 23:31:57 +00005435 return;
5436 }
5437
Richard Trieubeaf3452011-05-29 19:59:02 +00005438 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
David Blaikie9366d2b2012-06-19 21:19:06 +00005439 == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
David Blaikiea1edff02012-11-08 00:41:20 +00005440 && !Target->isBlockPointerType() && !Target->isMemberPointerType()
David Blaikiebcd4b552013-02-16 00:56:22 +00005441 && Target->isScalarType() && !Target->isNullPtrType()) {
David Blaikieae12b182012-03-16 20:30:12 +00005442 SourceLocation Loc = E->getSourceRange().getBegin();
5443 if (Loc.isMacroID())
5444 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
David Blaikie18e9ac72012-05-15 21:57:38 +00005445 if (!Loc.isMacroID() || CC.isMacroID())
5446 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5447 << T << clang::SourceRange(CC)
Richard Smithf7ec86a2013-09-20 00:27:40 +00005448 << FixItHint::CreateReplacement(Loc,
5449 S.getFixItZeroLiteralForType(T, Loc));
Richard Trieubeaf3452011-05-29 19:59:02 +00005450 }
5451
David Blaikie9366d2b2012-06-19 21:19:06 +00005452 if (!Source->isIntegerType() || !Target->isIntegerType())
5453 return;
5454
David Blaikie7555b6a2012-05-15 16:56:36 +00005455 // TODO: remove this early return once the false positives for constant->bool
5456 // in templates, macros, etc, are reduced or removed.
5457 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5458 return;
5459
John McCallcc7e5bf2010-05-06 08:58:33 +00005460 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00005461 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00005462
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005463 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00005464 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005465 // TODO: this should happen for bitfield stores, too.
5466 llvm::APSInt Value(32);
5467 if (E->isIntegerConstantExpr(Value, S.Context)) {
5468 if (S.SourceMgr.isInSystemMacro(CC))
5469 return;
5470
John McCall18a2c2c2010-11-09 22:22:12 +00005471 std::string PrettySourceValue = Value.toString(10);
5472 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005473
Ted Kremenek33ba9952011-10-22 02:37:33 +00005474 S.DiagRuntimeBehavior(E->getExprLoc(), E,
5475 S.PDiag(diag::warn_impcast_integer_precision_constant)
5476 << PrettySourceValue << PrettyTargetValue
5477 << E->getType() << T << E->getSourceRange()
5478 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00005479 return;
5480 }
5481
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005482 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5483 if (S.SourceMgr.isInSystemMacro(CC))
5484 return;
5485
David Blaikie9455da02012-04-12 22:40:54 +00005486 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00005487 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5488 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00005489 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00005490 }
5491
5492 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5493 (!TargetRange.NonNegative && SourceRange.NonNegative &&
5494 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005495
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005496 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005497 return;
5498
John McCallcc7e5bf2010-05-06 08:58:33 +00005499 unsigned DiagID = diag::warn_impcast_integer_sign;
5500
5501 // Traditionally, gcc has warned about this under -Wsign-compare.
5502 // We also want to warn about it in -Wconversion.
5503 // So if -Wconversion is off, use a completely identical diagnostic
5504 // in the sign-compare group.
5505 // The conditional-checking code will
5506 if (ICContext) {
5507 DiagID = diag::warn_impcast_integer_sign_conditional;
5508 *ICContext = true;
5509 }
5510
John McCallacf0ee52010-10-08 02:01:28 +00005511 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00005512 }
5513
Douglas Gregora78f1932011-02-22 02:45:07 +00005514 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00005515 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5516 // type, to give us better diagnostics.
5517 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005518 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00005519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5520 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5521 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5522 SourceType = S.Context.getTypeDeclType(Enum);
5523 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5524 }
5525 }
5526
Douglas Gregora78f1932011-02-22 02:45:07 +00005527 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5528 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00005529 if (SourceEnum->getDecl()->hasNameForLinkage() &&
5530 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005531 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00005532 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005533 return;
5534
Douglas Gregor364f7db2011-03-12 00:14:31 +00005535 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00005536 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00005537 }
Douglas Gregora78f1932011-02-22 02:45:07 +00005538
John McCall263a48b2010-01-04 23:31:57 +00005539 return;
5540}
5541
David Blaikie18e9ac72012-05-15 21:57:38 +00005542void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5543 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005544
5545void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00005546 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005547 E = E->IgnoreParenImpCasts();
5548
5549 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00005550 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005551
John McCallacf0ee52010-10-08 02:01:28 +00005552 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005553 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005554 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00005555 return;
5556}
5557
David Blaikie18e9ac72012-05-15 21:57:38 +00005558void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5559 SourceLocation CC, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00005560 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005561
5562 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00005563 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5564 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005565
5566 // If -Wconversion would have warned about either of the candidates
5567 // for a signedness conversion to the context type...
5568 if (!Suspicious) return;
5569
5570 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00005571 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5572 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00005573 return;
5574
John McCallcc7e5bf2010-05-06 08:58:33 +00005575 // ...then check whether it would have warned about either of the
5576 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00005577 if (E->getType() == T) return;
5578
5579 Suspicious = false;
5580 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5581 E->getType(), CC, &Suspicious);
5582 if (!Suspicious)
5583 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00005584 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00005585}
5586
5587/// AnalyzeImplicitConversions - Find and report any interesting
5588/// implicit conversions in the given expression. There are a couple
5589/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005590void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005591 QualType T = OrigE->getType();
5592 Expr *E = OrigE->IgnoreParenImpCasts();
5593
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00005594 if (E->isTypeDependent() || E->isValueDependent())
5595 return;
5596
John McCallcc7e5bf2010-05-06 08:58:33 +00005597 // For conditional operators, we analyze the arguments as if they
5598 // were being fed directly into the output.
5599 if (isa<ConditionalOperator>(E)) {
5600 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00005601 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00005602 return;
5603 }
5604
Hans Wennborgf4ad2322012-08-28 15:44:30 +00005605 // Check implicit argument conversions for function calls.
5606 if (CallExpr *Call = dyn_cast<CallExpr>(E))
5607 CheckImplicitArgumentConversions(S, Call, CC);
5608
John McCallcc7e5bf2010-05-06 08:58:33 +00005609 // Go ahead and check any implicit conversions we might have skipped.
5610 // The non-canonical typecheck is just an optimization;
5611 // CheckImplicitConversion will filter out dead implicit conversions.
5612 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00005613 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005614
5615 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005616
5617 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005618 if (POE->getResultExpr())
5619 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00005620 }
5621
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00005622 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5623 return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5624
John McCallcc7e5bf2010-05-06 08:58:33 +00005625 // Skip past explicit casts.
5626 if (isa<ExplicitCastExpr>(E)) {
5627 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00005628 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005629 }
5630
John McCalld2a53122010-11-09 23:24:47 +00005631 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5632 // Do a somewhat different check with comparison operators.
5633 if (BO->isComparisonOp())
5634 return AnalyzeComparison(S, BO);
5635
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00005636 // And with simple assignments.
5637 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00005638 return AnalyzeAssignment(S, BO);
5639 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005640
5641 // These break the otherwise-useful invariant below. Fortunately,
5642 // we don't really need to recurse into them, because any internal
5643 // expressions should have been analyzed already when they were
5644 // built into statements.
5645 if (isa<StmtExpr>(E)) return;
5646
5647 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00005648 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00005649
5650 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00005651 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00005652 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5653 bool IsLogicalOperator = BO && BO->isLogicalOp();
5654 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00005655 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00005656 if (!ChildExpr)
5657 continue;
5658
Richard Trieu021baa32011-09-23 20:10:00 +00005659 if (IsLogicalOperator &&
5660 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5661 // Ignore checking string literals that are in logical operators.
5662 continue;
5663 AnalyzeImplicitConversions(S, ChildExpr, CC);
5664 }
John McCallcc7e5bf2010-05-06 08:58:33 +00005665}
5666
5667} // end anonymous namespace
5668
5669/// Diagnoses "dangerous" implicit conversions within the given
5670/// expression (which is a full expression). Implements -Wconversion
5671/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00005672///
5673/// \param CC the "context" location of the implicit conversion, i.e.
5674/// the most location of the syntactic entity requiring the implicit
5675/// conversion
5676void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005677 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00005678 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00005679 return;
5680
5681 // Don't diagnose for value- or type-dependent expressions.
5682 if (E->isTypeDependent() || E->isValueDependent())
5683 return;
5684
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00005685 // Check for array bounds violations in cases where the check isn't triggered
5686 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5687 // ArraySubscriptExpr is on the RHS of a variable initialization.
5688 CheckArrayAccess(E);
5689
John McCallacf0ee52010-10-08 02:01:28 +00005690 // This is not the right CC for (e.g.) a variable initialization.
5691 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005692}
5693
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005694/// Diagnose when expression is an integer constant expression and its evaluation
5695/// results in integer overflow
5696void Sema::CheckForIntOverflow (Expr *E) {
Richard Smithe9ff7702013-11-05 22:23:30 +00005697 if (isa<BinaryOperator>(E->IgnoreParens()))
5698 E->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00005699}
5700
Richard Smithc406cb72013-01-17 01:17:56 +00005701namespace {
5702/// \brief Visitor for expressions which looks for unsequenced operations on the
5703/// same object.
5704class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00005705 typedef EvaluatedExprVisitor<SequenceChecker> Base;
5706
Richard Smithc406cb72013-01-17 01:17:56 +00005707 /// \brief A tree of sequenced regions within an expression. Two regions are
5708 /// unsequenced if one is an ancestor or a descendent of the other. When we
5709 /// finish processing an expression with sequencing, such as a comma
5710 /// expression, we fold its tree nodes into its parent, since they are
5711 /// unsequenced with respect to nodes we will visit later.
5712 class SequenceTree {
5713 struct Value {
5714 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5715 unsigned Parent : 31;
5716 bool Merged : 1;
5717 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005718 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00005719
5720 public:
5721 /// \brief A region within an expression which may be sequenced with respect
5722 /// to some other region.
5723 class Seq {
5724 explicit Seq(unsigned N) : Index(N) {}
5725 unsigned Index;
5726 friend class SequenceTree;
5727 public:
5728 Seq() : Index(0) {}
5729 };
5730
5731 SequenceTree() { Values.push_back(Value(0)); }
5732 Seq root() const { return Seq(0); }
5733
5734 /// \brief Create a new sequence of operations, which is an unsequenced
5735 /// subset of \p Parent. This sequence of operations is sequenced with
5736 /// respect to other children of \p Parent.
5737 Seq allocate(Seq Parent) {
5738 Values.push_back(Value(Parent.Index));
5739 return Seq(Values.size() - 1);
5740 }
5741
5742 /// \brief Merge a sequence of operations into its parent.
5743 void merge(Seq S) {
5744 Values[S.Index].Merged = true;
5745 }
5746
5747 /// \brief Determine whether two operations are unsequenced. This operation
5748 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5749 /// should have been merged into its parent as appropriate.
5750 bool isUnsequenced(Seq Cur, Seq Old) {
5751 unsigned C = representative(Cur.Index);
5752 unsigned Target = representative(Old.Index);
5753 while (C >= Target) {
5754 if (C == Target)
5755 return true;
5756 C = Values[C].Parent;
5757 }
5758 return false;
5759 }
5760
5761 private:
5762 /// \brief Pick a representative for a sequence.
5763 unsigned representative(unsigned K) {
5764 if (Values[K].Merged)
5765 // Perform path compression as we go.
5766 return Values[K].Parent = representative(Values[K].Parent);
5767 return K;
5768 }
5769 };
5770
5771 /// An object for which we can track unsequenced uses.
5772 typedef NamedDecl *Object;
5773
5774 /// Different flavors of object usage which we track. We only track the
5775 /// least-sequenced usage of each kind.
5776 enum UsageKind {
5777 /// A read of an object. Multiple unsequenced reads are OK.
5778 UK_Use,
5779 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00005780 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00005781 UK_ModAsValue,
5782 /// A modification of an object which is not sequenced before the value
5783 /// computation of the expression, such as n++.
5784 UK_ModAsSideEffect,
5785
5786 UK_Count = UK_ModAsSideEffect + 1
5787 };
5788
5789 struct Usage {
5790 Usage() : Use(0), Seq() {}
5791 Expr *Use;
5792 SequenceTree::Seq Seq;
5793 };
5794
5795 struct UsageInfo {
5796 UsageInfo() : Diagnosed(false) {}
5797 Usage Uses[UK_Count];
5798 /// Have we issued a diagnostic for this variable already?
5799 bool Diagnosed;
5800 };
5801 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5802
5803 Sema &SemaRef;
5804 /// Sequenced regions within the expression.
5805 SequenceTree Tree;
5806 /// Declaration modifications and references which we have seen.
5807 UsageInfoMap UsageMap;
5808 /// The region we are currently within.
5809 SequenceTree::Seq Region;
5810 /// Filled in with declarations which were modified as a side-effect
5811 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005812 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00005813 /// Expressions to check later. We defer checking these to reduce
5814 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005815 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00005816
5817 /// RAII object wrapping the visitation of a sequenced subexpression of an
5818 /// expression. At the end of this process, the side-effects of the evaluation
5819 /// become sequenced with respect to the value computation of the result, so
5820 /// we downgrade any UK_ModAsSideEffect within the evaluation to
5821 /// UK_ModAsValue.
5822 struct SequencedSubexpression {
5823 SequencedSubexpression(SequenceChecker &Self)
5824 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5825 Self.ModAsSideEffect = &ModAsSideEffect;
5826 }
5827 ~SequencedSubexpression() {
5828 for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5829 UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5830 U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5831 Self.addUsage(U, ModAsSideEffect[I].first,
5832 ModAsSideEffect[I].second.Use, UK_ModAsValue);
5833 }
5834 Self.ModAsSideEffect = OldModAsSideEffect;
5835 }
5836
5837 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005838 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5839 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00005840 };
5841
Richard Smith40238f02013-06-20 22:21:56 +00005842 /// RAII object wrapping the visitation of a subexpression which we might
5843 /// choose to evaluate as a constant. If any subexpression is evaluated and
5844 /// found to be non-constant, this allows us to suppress the evaluation of
5845 /// the outer expression.
5846 class EvaluationTracker {
5847 public:
5848 EvaluationTracker(SequenceChecker &Self)
5849 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5850 Self.EvalTracker = this;
5851 }
5852 ~EvaluationTracker() {
5853 Self.EvalTracker = Prev;
5854 if (Prev)
5855 Prev->EvalOK &= EvalOK;
5856 }
5857
5858 bool evaluate(const Expr *E, bool &Result) {
5859 if (!EvalOK || E->isValueDependent())
5860 return false;
5861 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5862 return EvalOK;
5863 }
5864
5865 private:
5866 SequenceChecker &Self;
5867 EvaluationTracker *Prev;
5868 bool EvalOK;
5869 } *EvalTracker;
5870
Richard Smithc406cb72013-01-17 01:17:56 +00005871 /// \brief Find the object which is produced by the specified expression,
5872 /// if any.
5873 Object getObject(Expr *E, bool Mod) const {
5874 E = E->IgnoreParenCasts();
5875 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5876 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5877 return getObject(UO->getSubExpr(), Mod);
5878 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5879 if (BO->getOpcode() == BO_Comma)
5880 return getObject(BO->getRHS(), Mod);
5881 if (Mod && BO->isAssignmentOp())
5882 return getObject(BO->getLHS(), Mod);
5883 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5884 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5885 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5886 return ME->getMemberDecl();
5887 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5888 // FIXME: If this is a reference, map through to its value.
5889 return DRE->getDecl();
5890 return 0;
5891 }
5892
5893 /// \brief Note that an object was modified or used by an expression.
5894 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5895 Usage &U = UI.Uses[UK];
5896 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5897 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5898 ModAsSideEffect->push_back(std::make_pair(O, U));
5899 U.Use = Ref;
5900 U.Seq = Region;
5901 }
5902 }
5903 /// \brief Check whether a modification or use conflicts with a prior usage.
5904 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5905 bool IsModMod) {
5906 if (UI.Diagnosed)
5907 return;
5908
5909 const Usage &U = UI.Uses[OtherKind];
5910 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5911 return;
5912
5913 Expr *Mod = U.Use;
5914 Expr *ModOrUse = Ref;
5915 if (OtherKind == UK_Use)
5916 std::swap(Mod, ModOrUse);
5917
5918 SemaRef.Diag(Mod->getExprLoc(),
5919 IsModMod ? diag::warn_unsequenced_mod_mod
5920 : diag::warn_unsequenced_mod_use)
5921 << O << SourceRange(ModOrUse->getExprLoc());
5922 UI.Diagnosed = true;
5923 }
5924
5925 void notePreUse(Object O, Expr *Use) {
5926 UsageInfo &U = UsageMap[O];
5927 // Uses conflict with other modifications.
5928 checkUsage(O, U, Use, UK_ModAsValue, false);
5929 }
5930 void notePostUse(Object O, Expr *Use) {
5931 UsageInfo &U = UsageMap[O];
5932 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5933 addUsage(U, O, Use, UK_Use);
5934 }
5935
5936 void notePreMod(Object O, Expr *Mod) {
5937 UsageInfo &U = UsageMap[O];
5938 // Modifications conflict with other modifications and with uses.
5939 checkUsage(O, U, Mod, UK_ModAsValue, true);
5940 checkUsage(O, U, Mod, UK_Use, false);
5941 }
5942 void notePostMod(Object O, Expr *Use, UsageKind UK) {
5943 UsageInfo &U = UsageMap[O];
5944 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5945 addUsage(U, O, Use, UK);
5946 }
5947
5948public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00005949 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5950 : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5951 WorkList(WorkList), EvalTracker(0) {
Richard Smithc406cb72013-01-17 01:17:56 +00005952 Visit(E);
5953 }
5954
5955 void VisitStmt(Stmt *S) {
5956 // Skip all statements which aren't expressions for now.
5957 }
5958
5959 void VisitExpr(Expr *E) {
5960 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00005961 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00005962 }
5963
5964 void VisitCastExpr(CastExpr *E) {
5965 Object O = Object();
5966 if (E->getCastKind() == CK_LValueToRValue)
5967 O = getObject(E->getSubExpr(), false);
5968
5969 if (O)
5970 notePreUse(O, E);
5971 VisitExpr(E);
5972 if (O)
5973 notePostUse(O, E);
5974 }
5975
5976 void VisitBinComma(BinaryOperator *BO) {
5977 // C++11 [expr.comma]p1:
5978 // Every value computation and side effect associated with the left
5979 // expression is sequenced before every value computation and side
5980 // effect associated with the right expression.
5981 SequenceTree::Seq LHS = Tree.allocate(Region);
5982 SequenceTree::Seq RHS = Tree.allocate(Region);
5983 SequenceTree::Seq OldRegion = Region;
5984
5985 {
5986 SequencedSubexpression SeqLHS(*this);
5987 Region = LHS;
5988 Visit(BO->getLHS());
5989 }
5990
5991 Region = RHS;
5992 Visit(BO->getRHS());
5993
5994 Region = OldRegion;
5995
5996 // Forget that LHS and RHS are sequenced. They are both unsequenced
5997 // with respect to other stuff.
5998 Tree.merge(LHS);
5999 Tree.merge(RHS);
6000 }
6001
6002 void VisitBinAssign(BinaryOperator *BO) {
6003 // The modification is sequenced after the value computation of the LHS
6004 // and RHS, so check it before inspecting the operands and update the
6005 // map afterwards.
6006 Object O = getObject(BO->getLHS(), true);
6007 if (!O)
6008 return VisitExpr(BO);
6009
6010 notePreMod(O, BO);
6011
6012 // C++11 [expr.ass]p7:
6013 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
6014 // only once.
6015 //
6016 // Therefore, for a compound assignment operator, O is considered used
6017 // everywhere except within the evaluation of E1 itself.
6018 if (isa<CompoundAssignOperator>(BO))
6019 notePreUse(O, BO);
6020
6021 Visit(BO->getLHS());
6022
6023 if (isa<CompoundAssignOperator>(BO))
6024 notePostUse(O, BO);
6025
6026 Visit(BO->getRHS());
6027
Richard Smith83e37bee2013-06-26 23:16:51 +00006028 // C++11 [expr.ass]p1:
6029 // the assignment is sequenced [...] before the value computation of the
6030 // assignment expression.
6031 // C11 6.5.16/3 has no such rule.
6032 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6033 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006034 }
6035 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
6036 VisitBinAssign(CAO);
6037 }
6038
6039 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6040 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
6041 void VisitUnaryPreIncDec(UnaryOperator *UO) {
6042 Object O = getObject(UO->getSubExpr(), true);
6043 if (!O)
6044 return VisitExpr(UO);
6045
6046 notePreMod(O, UO);
6047 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00006048 // C++11 [expr.pre.incr]p1:
6049 // the expression ++x is equivalent to x+=1
6050 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
6051 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00006052 }
6053
6054 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6055 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
6056 void VisitUnaryPostIncDec(UnaryOperator *UO) {
6057 Object O = getObject(UO->getSubExpr(), true);
6058 if (!O)
6059 return VisitExpr(UO);
6060
6061 notePreMod(O, UO);
6062 Visit(UO->getSubExpr());
6063 notePostMod(O, UO, UK_ModAsSideEffect);
6064 }
6065
6066 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6067 void VisitBinLOr(BinaryOperator *BO) {
6068 // The side-effects of the LHS of an '&&' are sequenced before the
6069 // value computation of the RHS, and hence before the value computation
6070 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6071 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00006072 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006073 {
6074 SequencedSubexpression Sequenced(*this);
6075 Visit(BO->getLHS());
6076 }
6077
6078 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006079 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006080 if (!Result)
6081 Visit(BO->getRHS());
6082 } else {
6083 // Check for unsequenced operations in the RHS, treating it as an
6084 // entirely separate evaluation.
6085 //
6086 // FIXME: If there are operations in the RHS which are unsequenced
6087 // with respect to operations outside the RHS, and those operations
6088 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00006089 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006090 }
Richard Smithc406cb72013-01-17 01:17:56 +00006091 }
6092 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00006093 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00006094 {
6095 SequencedSubexpression Sequenced(*this);
6096 Visit(BO->getLHS());
6097 }
6098
6099 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006100 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00006101 if (Result)
6102 Visit(BO->getRHS());
6103 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00006104 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00006105 }
Richard Smithc406cb72013-01-17 01:17:56 +00006106 }
6107
6108 // Only visit the condition, unless we can be sure which subexpression will
6109 // be chosen.
6110 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00006111 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00006112 {
6113 SequencedSubexpression Sequenced(*this);
6114 Visit(CO->getCond());
6115 }
Richard Smithc406cb72013-01-17 01:17:56 +00006116
6117 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00006118 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00006119 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006120 else {
Richard Smithd33f5202013-01-17 23:18:09 +00006121 WorkList.push_back(CO->getTrueExpr());
6122 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00006123 }
Richard Smithc406cb72013-01-17 01:17:56 +00006124 }
6125
Richard Smithe3dbfe02013-06-30 10:40:20 +00006126 void VisitCallExpr(CallExpr *CE) {
6127 // C++11 [intro.execution]p15:
6128 // When calling a function [...], every value computation and side effect
6129 // associated with any argument expression, or with the postfix expression
6130 // designating the called function, is sequenced before execution of every
6131 // expression or statement in the body of the function [and thus before
6132 // the value computation of its result].
6133 SequencedSubexpression Sequenced(*this);
6134 Base::VisitCallExpr(CE);
6135
6136 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6137 }
6138
Richard Smithc406cb72013-01-17 01:17:56 +00006139 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00006140 // This is a call, so all subexpressions are sequenced before the result.
6141 SequencedSubexpression Sequenced(*this);
6142
Richard Smithc406cb72013-01-17 01:17:56 +00006143 if (!CCE->isListInitialization())
6144 return VisitExpr(CCE);
6145
6146 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006147 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006148 SequenceTree::Seq Parent = Region;
6149 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6150 E = CCE->arg_end();
6151 I != E; ++I) {
6152 Region = Tree.allocate(Parent);
6153 Elts.push_back(Region);
6154 Visit(*I);
6155 }
6156
6157 // Forget that the initializers are sequenced.
6158 Region = Parent;
6159 for (unsigned I = 0; I < Elts.size(); ++I)
6160 Tree.merge(Elts[I]);
6161 }
6162
6163 void VisitInitListExpr(InitListExpr *ILE) {
6164 if (!SemaRef.getLangOpts().CPlusPlus11)
6165 return VisitExpr(ILE);
6166
6167 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006168 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00006169 SequenceTree::Seq Parent = Region;
6170 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6171 Expr *E = ILE->getInit(I);
6172 if (!E) continue;
6173 Region = Tree.allocate(Parent);
6174 Elts.push_back(Region);
6175 Visit(E);
6176 }
6177
6178 // Forget that the initializers are sequenced.
6179 Region = Parent;
6180 for (unsigned I = 0; I < Elts.size(); ++I)
6181 Tree.merge(Elts[I]);
6182 }
6183};
6184}
6185
6186void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00006187 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00006188 WorkList.push_back(E);
6189 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00006190 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00006191 SequenceChecker(*this, Item, WorkList);
6192 }
Richard Smithc406cb72013-01-17 01:17:56 +00006193}
6194
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006195void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6196 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00006197 CheckImplicitConversions(E, CheckLoc);
6198 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006199 if (!IsConstexpr && !E->isValueDependent())
6200 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00006201}
6202
John McCall1f425642010-11-11 03:21:53 +00006203void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6204 FieldDecl *BitField,
6205 Expr *Init) {
6206 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6207}
6208
Mike Stump0c2ec772010-01-21 03:59:47 +00006209/// CheckParmsForFunctionDef - Check that the parameters of the given
6210/// function are appropriate for the definition of a function. This
6211/// takes care of any checks that cannot be performed on the
6212/// declaration itself, e.g., that the types of each of the function
6213/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00006214bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6215 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00006216 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006217 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00006218 for (; P != PEnd; ++P) {
6219 ParmVarDecl *Param = *P;
6220
Mike Stump0c2ec772010-01-21 03:59:47 +00006221 // C99 6.7.5.3p4: the parameters in a parameter type list in a
6222 // function declarator that is part of a function definition of
6223 // that function shall not have incomplete type.
6224 //
6225 // This is also C++ [dcl.fct]p6.
6226 if (!Param->isInvalidDecl() &&
6227 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006228 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00006229 Param->setInvalidDecl();
6230 HasInvalidParm = true;
6231 }
6232
6233 // C99 6.9.1p5: If the declarator includes a parameter type list, the
6234 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00006235 if (CheckParameterNames &&
6236 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00006237 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00006238 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00006239 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00006240
6241 // C99 6.7.5.3p12:
6242 // If the function declarator is not part of a definition of that
6243 // function, parameters may have incomplete type and may use the [*]
6244 // notation in their sequences of declarator specifiers to specify
6245 // variable length array types.
6246 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006247 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00006248 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00006249 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00006250 // information is added for it.
6251 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006252 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00006253 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00006254 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00006255 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006256
6257 // MSVC destroys objects passed by value in the callee. Therefore a
6258 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006259 // object's destructor. However, we don't perform any direct access check
6260 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00006261 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
6262 .getCXXABI()
6263 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00006264 if (!Param->isInvalidDecl()) {
6265 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
6266 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
6267 if (!ClassDecl->isInvalidDecl() &&
6268 !ClassDecl->hasIrrelevantDestructor() &&
6269 !ClassDecl->isDependentContext()) {
6270 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
6271 MarkFunctionReferenced(Param->getLocation(), Destructor);
6272 DiagnoseUseOfDecl(Destructor, Param->getLocation());
6273 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00006274 }
6275 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00006276 }
Mike Stump0c2ec772010-01-21 03:59:47 +00006277 }
6278
6279 return HasInvalidParm;
6280}
John McCall2b5c1b22010-08-12 21:44:57 +00006281
6282/// CheckCastAlign - Implements -Wcast-align, which warns when a
6283/// pointer cast increases the alignment requirements.
6284void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6285 // This is actually a lot of work to potentially be doing on every
6286 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00006287 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6288 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00006289 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00006290 return;
6291
6292 // Ignore dependent types.
6293 if (T->isDependentType() || Op->getType()->isDependentType())
6294 return;
6295
6296 // Require that the destination be a pointer type.
6297 const PointerType *DestPtr = T->getAs<PointerType>();
6298 if (!DestPtr) return;
6299
6300 // If the destination has alignment 1, we're done.
6301 QualType DestPointee = DestPtr->getPointeeType();
6302 if (DestPointee->isIncompleteType()) return;
6303 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6304 if (DestAlign.isOne()) return;
6305
6306 // Require that the source be a pointer type.
6307 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6308 if (!SrcPtr) return;
6309 QualType SrcPointee = SrcPtr->getPointeeType();
6310
6311 // Whitelist casts from cv void*. We already implicitly
6312 // whitelisted casts to cv void*, since they have alignment 1.
6313 // Also whitelist casts involving incomplete types, which implicitly
6314 // includes 'void'.
6315 if (SrcPointee->isIncompleteType()) return;
6316
6317 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6318 if (SrcAlign >= DestAlign) return;
6319
6320 Diag(TRange.getBegin(), diag::warn_cast_align)
6321 << Op->getType() << T
6322 << static_cast<unsigned>(SrcAlign.getQuantity())
6323 << static_cast<unsigned>(DestAlign.getQuantity())
6324 << TRange << Op->getSourceRange();
6325}
6326
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006327static const Type* getElementType(const Expr *BaseExpr) {
6328 const Type* EltType = BaseExpr->getType().getTypePtr();
6329 if (EltType->isAnyPointerType())
6330 return EltType->getPointeeType().getTypePtr();
6331 else if (EltType->isArrayType())
6332 return EltType->getBaseElementTypeUnsafe();
6333 return EltType;
6334}
6335
Chandler Carruth28389f02011-08-05 09:10:50 +00006336/// \brief Check whether this array fits the idiom of a size-one tail padded
6337/// array member of a struct.
6338///
6339/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6340/// commonly used to emulate flexible arrays in C89 code.
6341static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6342 const NamedDecl *ND) {
6343 if (Size != 1 || !ND) return false;
6344
6345 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6346 if (!FD) return false;
6347
6348 // Don't consider sizes resulting from macro expansions or template argument
6349 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00006350
6351 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006352 while (TInfo) {
6353 TypeLoc TL = TInfo->getTypeLoc();
6354 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00006355 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6356 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006357 TInfo = TDL->getTypeSourceInfo();
6358 continue;
6359 }
David Blaikie6adc78e2013-02-18 22:06:02 +00006360 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6361 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00006362 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6363 return false;
6364 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00006365 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00006366 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006367
6368 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00006369 if (!RD) return false;
6370 if (RD->isUnion()) return false;
6371 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6372 if (!CRD->isStandardLayout()) return false;
6373 }
Chandler Carruth28389f02011-08-05 09:10:50 +00006374
Benjamin Kramer8c543672011-08-06 03:04:42 +00006375 // See if this is the last field decl in the record.
6376 const Decl *D = FD;
6377 while ((D = D->getNextDeclInContext()))
6378 if (isa<FieldDecl>(D))
6379 return false;
6380 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00006381}
6382
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006383void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006384 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00006385 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006386 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006387 if (IndexExpr->isValueDependent())
6388 return;
6389
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00006390 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006391 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006392 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006393 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006394 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00006395 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00006396
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006397 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006398 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00006399 return;
Richard Smith13f67182011-12-16 19:31:14 +00006400 if (IndexNegated)
6401 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00006402
Chandler Carruth126b1552011-08-05 08:07:29 +00006403 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00006404 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6405 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00006406 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00006407 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00006408
Ted Kremeneke4b316c2011-02-23 23:06:04 +00006409 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006410 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00006411 if (!size.isStrictlyPositive())
6412 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006413
6414 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00006415 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006416 // Make sure we're comparing apples to apples when comparing index to size
6417 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6418 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00006419 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00006420 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006421 if (ptrarith_typesize != array_typesize) {
6422 // There's a cast to a different size type involved
6423 uint64_t ratio = array_typesize / ptrarith_typesize;
6424 // TODO: Be smarter about handling cases where array_typesize is not a
6425 // multiple of ptrarith_typesize
6426 if (ptrarith_typesize * ratio == array_typesize)
6427 size *= llvm::APInt(size.getBitWidth(), ratio);
6428 }
6429 }
6430
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006431 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006432 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006433 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006434 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00006435
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006436 // For array subscripting the index must be less than size, but for pointer
6437 // arithmetic also allow the index (offset) to be equal to size since
6438 // computing the next address after the end of the array is legal and
6439 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00006440 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00006441 return;
6442
6443 // Also don't warn for arrays of size 1 which are members of some
6444 // structure. These are often used to approximate flexible arrays in C89
6445 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006446 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00006447 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006448
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006449 // Suppress the warning if the subscript expression (as identified by the
6450 // ']' location) and the index expression are both from macro expansions
6451 // within a system header.
6452 if (ASE) {
6453 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6454 ASE->getRBracketLoc());
6455 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6456 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6457 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00006458 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006459 return;
6460 }
6461 }
6462
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006463 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006464 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006465 DiagID = diag::warn_array_index_exceeds_bounds;
6466
6467 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6468 PDiag(DiagID) << index.toString(10, true)
6469 << size.toString(10, true)
6470 << (unsigned)size.getLimitedValue(~0U)
6471 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00006472 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006473 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006474 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006475 DiagID = diag::warn_ptr_arith_precedes_bounds;
6476 if (index.isNegative()) index = -index;
6477 }
6478
6479 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6480 PDiag(DiagID) << index.toString(10, true)
6481 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00006482 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00006483
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00006484 if (!ND) {
6485 // Try harder to find a NamedDecl to point at in the note.
6486 while (const ArraySubscriptExpr *ASE =
6487 dyn_cast<ArraySubscriptExpr>(BaseExpr))
6488 BaseExpr = ASE->getBase()->IgnoreParenCasts();
6489 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6490 ND = dyn_cast<NamedDecl>(DRE->getDecl());
6491 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6492 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6493 }
6494
Chandler Carruth1af88f12011-02-17 21:10:52 +00006495 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006496 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6497 PDiag(diag::note_array_index_out_of_bounds)
6498 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00006499}
6500
Ted Kremenekdf26df72011-03-01 18:41:00 +00006501void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006502 int AllowOnePastEnd = 0;
6503 while (expr) {
6504 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00006505 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006506 case Stmt::ArraySubscriptExprClass: {
6507 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00006508 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006509 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00006510 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006511 }
6512 case Stmt::UnaryOperatorClass: {
6513 // Only unwrap the * and & unary operators
6514 const UnaryOperator *UO = cast<UnaryOperator>(expr);
6515 expr = UO->getSubExpr();
6516 switch (UO->getOpcode()) {
6517 case UO_AddrOf:
6518 AllowOnePastEnd++;
6519 break;
6520 case UO_Deref:
6521 AllowOnePastEnd--;
6522 break;
6523 default:
6524 return;
6525 }
6526 break;
6527 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006528 case Stmt::ConditionalOperatorClass: {
6529 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6530 if (const Expr *lhs = cond->getLHS())
6531 CheckArrayAccess(lhs);
6532 if (const Expr *rhs = cond->getRHS())
6533 CheckArrayAccess(rhs);
6534 return;
6535 }
6536 default:
6537 return;
6538 }
Peter Collingbourne91147592011-04-15 00:35:48 +00006539 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00006540}
John McCall31168b02011-06-15 23:02:42 +00006541
6542//===--- CHECK: Objective-C retain cycles ----------------------------------//
6543
6544namespace {
6545 struct RetainCycleOwner {
6546 RetainCycleOwner() : Variable(0), Indirect(false) {}
6547 VarDecl *Variable;
6548 SourceRange Range;
6549 SourceLocation Loc;
6550 bool Indirect;
6551
6552 void setLocsFrom(Expr *e) {
6553 Loc = e->getExprLoc();
6554 Range = e->getSourceRange();
6555 }
6556 };
6557}
6558
6559/// Consider whether capturing the given variable can possibly lead to
6560/// a retain cycle.
6561static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00006562 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00006563 // lifetime. In MRR, it's captured strongly if the variable is
6564 // __block and has an appropriate type.
6565 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6566 return false;
6567
6568 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006569 if (ref)
6570 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00006571 return true;
6572}
6573
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006574static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00006575 while (true) {
6576 e = e->IgnoreParens();
6577 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6578 switch (cast->getCastKind()) {
6579 case CK_BitCast:
6580 case CK_LValueBitCast:
6581 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00006582 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00006583 e = cast->getSubExpr();
6584 continue;
6585
John McCall31168b02011-06-15 23:02:42 +00006586 default:
6587 return false;
6588 }
6589 }
6590
6591 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6592 ObjCIvarDecl *ivar = ref->getDecl();
6593 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6594 return false;
6595
6596 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006597 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00006598 return false;
6599
6600 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6601 owner.Indirect = true;
6602 return true;
6603 }
6604
6605 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6606 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6607 if (!var) return false;
6608 return considerVariable(var, ref, owner);
6609 }
6610
John McCall31168b02011-06-15 23:02:42 +00006611 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6612 if (member->isArrow()) return false;
6613
6614 // Don't count this as an indirect ownership.
6615 e = member->getBase();
6616 continue;
6617 }
6618
John McCallfe96e0b2011-11-06 09:01:30 +00006619 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6620 // Only pay attention to pseudo-objects on property references.
6621 ObjCPropertyRefExpr *pre
6622 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6623 ->IgnoreParens());
6624 if (!pre) return false;
6625 if (pre->isImplicitProperty()) return false;
6626 ObjCPropertyDecl *property = pre->getExplicitProperty();
6627 if (!property->isRetaining() &&
6628 !(property->getPropertyIvarDecl() &&
6629 property->getPropertyIvarDecl()->getType()
6630 .getObjCLifetime() == Qualifiers::OCL_Strong))
6631 return false;
6632
6633 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006634 if (pre->isSuperReceiver()) {
6635 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6636 if (!owner.Variable)
6637 return false;
6638 owner.Loc = pre->getLocation();
6639 owner.Range = pre->getSourceRange();
6640 return true;
6641 }
John McCallfe96e0b2011-11-06 09:01:30 +00006642 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6643 ->getSourceExpr());
6644 continue;
6645 }
6646
John McCall31168b02011-06-15 23:02:42 +00006647 // Array ivars?
6648
6649 return false;
6650 }
6651}
6652
6653namespace {
6654 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6655 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6656 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6657 Variable(variable), Capturer(0) {}
6658
6659 VarDecl *Variable;
6660 Expr *Capturer;
6661
6662 void VisitDeclRefExpr(DeclRefExpr *ref) {
6663 if (ref->getDecl() == Variable && !Capturer)
6664 Capturer = ref;
6665 }
6666
John McCall31168b02011-06-15 23:02:42 +00006667 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6668 if (Capturer) return;
6669 Visit(ref->getBase());
6670 if (Capturer && ref->isFreeIvar())
6671 Capturer = ref;
6672 }
6673
6674 void VisitBlockExpr(BlockExpr *block) {
6675 // Look inside nested blocks
6676 if (block->getBlockDecl()->capturesVariable(Variable))
6677 Visit(block->getBlockDecl()->getBody());
6678 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00006679
6680 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6681 if (Capturer) return;
6682 if (OVE->getSourceExpr())
6683 Visit(OVE->getSourceExpr());
6684 }
John McCall31168b02011-06-15 23:02:42 +00006685 };
6686}
6687
6688/// Check whether the given argument is a block which captures a
6689/// variable.
6690static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6691 assert(owner.Variable && owner.Loc.isValid());
6692
6693 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00006694
6695 // Look through [^{...} copy] and Block_copy(^{...}).
6696 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6697 Selector Cmd = ME->getSelector();
6698 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6699 e = ME->getInstanceReceiver();
6700 if (!e)
6701 return 0;
6702 e = e->IgnoreParenCasts();
6703 }
6704 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6705 if (CE->getNumArgs() == 1) {
6706 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00006707 if (Fn) {
6708 const IdentifierInfo *FnI = Fn->getIdentifier();
6709 if (FnI && FnI->isStr("_Block_copy")) {
6710 e = CE->getArg(0)->IgnoreParenCasts();
6711 }
6712 }
Jordan Rose67e887c2012-09-17 17:54:30 +00006713 }
6714 }
6715
John McCall31168b02011-06-15 23:02:42 +00006716 BlockExpr *block = dyn_cast<BlockExpr>(e);
6717 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6718 return 0;
6719
6720 FindCaptureVisitor visitor(S.Context, owner.Variable);
6721 visitor.Visit(block->getBlockDecl()->getBody());
6722 return visitor.Capturer;
6723}
6724
6725static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6726 RetainCycleOwner &owner) {
6727 assert(capturer);
6728 assert(owner.Variable && owner.Loc.isValid());
6729
6730 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6731 << owner.Variable << capturer->getSourceRange();
6732 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6733 << owner.Indirect << owner.Range;
6734}
6735
6736/// Check for a keyword selector that starts with the word 'add' or
6737/// 'set'.
6738static bool isSetterLikeSelector(Selector sel) {
6739 if (sel.isUnarySelector()) return false;
6740
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006741 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00006742 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006743 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00006744 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00006745 else if (str.startswith("add")) {
6746 // Specially whitelist 'addOperationWithBlock:'.
6747 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6748 return false;
6749 str = str.substr(3);
6750 }
John McCall31168b02011-06-15 23:02:42 +00006751 else
6752 return false;
6753
6754 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00006755 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00006756}
6757
6758/// Check a message send to see if it's likely to cause a retain cycle.
6759void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6760 // Only check instance methods whose selector looks like a setter.
6761 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6762 return;
6763
6764 // Try to find a variable that the receiver is strongly owned by.
6765 RetainCycleOwner owner;
6766 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006767 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00006768 return;
6769 } else {
6770 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6771 owner.Variable = getCurMethodDecl()->getSelfDecl();
6772 owner.Loc = msg->getSuperLoc();
6773 owner.Range = msg->getSuperLoc();
6774 }
6775
6776 // Check whether the receiver is captured by any of the arguments.
6777 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6778 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6779 return diagnoseRetainCycle(*this, capturer, owner);
6780}
6781
6782/// Check a property assign to see if it's likely to cause a retain cycle.
6783void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6784 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00006785 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00006786 return;
6787
6788 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6789 diagnoseRetainCycle(*this, capturer, owner);
6790}
6791
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00006792void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6793 RetainCycleOwner Owner;
6794 if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6795 return;
6796
6797 // Because we don't have an expression for the variable, we have to set the
6798 // location explicitly here.
6799 Owner.Loc = Var->getLocation();
6800 Owner.Range = Var->getSourceRange();
6801
6802 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6803 diagnoseRetainCycle(*this, Capturer, Owner);
6804}
6805
Ted Kremenek9304da92012-12-21 08:04:28 +00006806static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6807 Expr *RHS, bool isProperty) {
6808 // Check if RHS is an Objective-C object literal, which also can get
6809 // immediately zapped in a weak reference. Note that we explicitly
6810 // allow ObjCStringLiterals, since those are designed to never really die.
6811 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006812
Ted Kremenek64873352012-12-21 22:46:35 +00006813 // This enum needs to match with the 'select' in
6814 // warn_objc_arc_literal_assign (off-by-1).
6815 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6816 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6817 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006818
6819 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00006820 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00006821 << (isProperty ? 0 : 1)
6822 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00006823
6824 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00006825}
6826
Ted Kremenekc1f014a2012-12-21 19:45:30 +00006827static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6828 Qualifiers::ObjCLifetime LT,
6829 Expr *RHS, bool isProperty) {
6830 // Strip off any implicit cast added to get to the one ARC-specific.
6831 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6832 if (cast->getCastKind() == CK_ARCConsumeObject) {
6833 S.Diag(Loc, diag::warn_arc_retained_assign)
6834 << (LT == Qualifiers::OCL_ExplicitNone)
6835 << (isProperty ? 0 : 1)
6836 << RHS->getSourceRange();
6837 return true;
6838 }
6839 RHS = cast->getSubExpr();
6840 }
6841
6842 if (LT == Qualifiers::OCL_Weak &&
6843 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6844 return true;
6845
6846 return false;
6847}
6848
Ted Kremenekb36234d2012-12-21 08:04:20 +00006849bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6850 QualType LHS, Expr *RHS) {
6851 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6852
6853 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6854 return false;
6855
6856 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6857 return true;
6858
6859 return false;
6860}
6861
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006862void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6863 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006864 QualType LHSType;
6865 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006866 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006867 ObjCPropertyRefExpr *PRE
6868 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6869 if (PRE && !PRE->isImplicitProperty()) {
6870 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6871 if (PD)
6872 LHSType = PD->getType();
6873 }
6874
6875 if (LHSType.isNull())
6876 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00006877
6878 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6879
6880 if (LT == Qualifiers::OCL_Weak) {
6881 DiagnosticsEngine::Level Level =
6882 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6883 if (Level != DiagnosticsEngine::Ignored)
6884 getCurFunction()->markSafeWeakUse(LHS);
6885 }
6886
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006887 if (checkUnsafeAssigns(Loc, LHSType, RHS))
6888 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00006889
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006890 // FIXME. Check for other life times.
6891 if (LT != Qualifiers::OCL_None)
6892 return;
6893
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006894 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006895 if (PRE->isImplicitProperty())
6896 return;
6897 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6898 if (!PD)
6899 return;
6900
Bill Wendling44426052012-12-20 19:22:21 +00006901 unsigned Attributes = PD->getPropertyAttributes();
6902 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006903 // when 'assign' attribute was not explicitly specified
6904 // by user, ignore it and rely on property type itself
6905 // for lifetime info.
6906 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6907 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6908 LHSType->isObjCRetainableType())
6909 return;
6910
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006911 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00006912 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006913 Diag(Loc, diag::warn_arc_retained_property_assign)
6914 << RHS->getSourceRange();
6915 return;
6916 }
6917 RHS = cast->getSubExpr();
6918 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00006919 }
Bill Wendling44426052012-12-20 19:22:21 +00006920 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00006921 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6922 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00006923 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00006924 }
6925}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00006926
6927//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6928
6929namespace {
6930bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6931 SourceLocation StmtLoc,
6932 const NullStmt *Body) {
6933 // Do not warn if the body is a macro that expands to nothing, e.g:
6934 //
6935 // #define CALL(x)
6936 // if (condition)
6937 // CALL(0);
6938 //
6939 if (Body->hasLeadingEmptyMacro())
6940 return false;
6941
6942 // Get line numbers of statement and body.
6943 bool StmtLineInvalid;
6944 unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6945 &StmtLineInvalid);
6946 if (StmtLineInvalid)
6947 return false;
6948
6949 bool BodyLineInvalid;
6950 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6951 &BodyLineInvalid);
6952 if (BodyLineInvalid)
6953 return false;
6954
6955 // Warn if null statement and body are on the same line.
6956 if (StmtLine != BodyLine)
6957 return false;
6958
6959 return true;
6960}
6961} // Unnamed namespace
6962
6963void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6964 const Stmt *Body,
6965 unsigned DiagID) {
6966 // Since this is a syntactic check, don't emit diagnostic for template
6967 // instantiations, this just adds noise.
6968 if (CurrentInstantiationScope)
6969 return;
6970
6971 // The body should be a null statement.
6972 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6973 if (!NBody)
6974 return;
6975
6976 // Do the usual checks.
6977 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6978 return;
6979
6980 Diag(NBody->getSemiLoc(), DiagID);
6981 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6982}
6983
6984void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6985 const Stmt *PossibleBody) {
6986 assert(!CurrentInstantiationScope); // Ensured by caller
6987
6988 SourceLocation StmtLoc;
6989 const Stmt *Body;
6990 unsigned DiagID;
6991 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6992 StmtLoc = FS->getRParenLoc();
6993 Body = FS->getBody();
6994 DiagID = diag::warn_empty_for_body;
6995 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6996 StmtLoc = WS->getCond()->getSourceRange().getEnd();
6997 Body = WS->getBody();
6998 DiagID = diag::warn_empty_while_body;
6999 } else
7000 return; // Neither `for' nor `while'.
7001
7002 // The body should be a null statement.
7003 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
7004 if (!NBody)
7005 return;
7006
7007 // Skip expensive checks if diagnostic is disabled.
7008 if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
7009 DiagnosticsEngine::Ignored)
7010 return;
7011
7012 // Do the usual checks.
7013 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
7014 return;
7015
7016 // `for(...);' and `while(...);' are popular idioms, so in order to keep
7017 // noise level low, emit diagnostics only if for/while is followed by a
7018 // CompoundStmt, e.g.:
7019 // for (int i = 0; i < n; i++);
7020 // {
7021 // a(i);
7022 // }
7023 // or if for/while is followed by a statement with more indentation
7024 // than for/while itself:
7025 // for (int i = 0; i < n; i++);
7026 // a(i);
7027 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
7028 if (!ProbableTypo) {
7029 bool BodyColInvalid;
7030 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
7031 PossibleBody->getLocStart(),
7032 &BodyColInvalid);
7033 if (BodyColInvalid)
7034 return;
7035
7036 bool StmtColInvalid;
7037 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
7038 S->getLocStart(),
7039 &StmtColInvalid);
7040 if (StmtColInvalid)
7041 return;
7042
7043 if (BodyCol > StmtCol)
7044 ProbableTypo = true;
7045 }
7046
7047 if (ProbableTypo) {
7048 Diag(NBody->getSemiLoc(), DiagID);
7049 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
7050 }
7051}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007052
7053//===--- Layout compatibility ----------------------------------------------//
7054
7055namespace {
7056
7057bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
7058
7059/// \brief Check if two enumeration types are layout-compatible.
7060bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
7061 // C++11 [dcl.enum] p8:
7062 // Two enumeration types are layout-compatible if they have the same
7063 // underlying type.
7064 return ED1->isComplete() && ED2->isComplete() &&
7065 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
7066}
7067
7068/// \brief Check if two fields are layout-compatible.
7069bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
7070 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
7071 return false;
7072
7073 if (Field1->isBitField() != Field2->isBitField())
7074 return false;
7075
7076 if (Field1->isBitField()) {
7077 // Make sure that the bit-fields are the same length.
7078 unsigned Bits1 = Field1->getBitWidthValue(C);
7079 unsigned Bits2 = Field2->getBitWidthValue(C);
7080
7081 if (Bits1 != Bits2)
7082 return false;
7083 }
7084
7085 return true;
7086}
7087
7088/// \brief Check if two standard-layout structs are layout-compatible.
7089/// (C++11 [class.mem] p17)
7090bool isLayoutCompatibleStruct(ASTContext &C,
7091 RecordDecl *RD1,
7092 RecordDecl *RD2) {
7093 // If both records are C++ classes, check that base classes match.
7094 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7095 // If one of records is a CXXRecordDecl we are in C++ mode,
7096 // thus the other one is a CXXRecordDecl, too.
7097 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7098 // Check number of base classes.
7099 if (D1CXX->getNumBases() != D2CXX->getNumBases())
7100 return false;
7101
7102 // Check the base classes.
7103 for (CXXRecordDecl::base_class_const_iterator
7104 Base1 = D1CXX->bases_begin(),
7105 BaseEnd1 = D1CXX->bases_end(),
7106 Base2 = D2CXX->bases_begin();
7107 Base1 != BaseEnd1;
7108 ++Base1, ++Base2) {
7109 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7110 return false;
7111 }
7112 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7113 // If only RD2 is a C++ class, it should have zero base classes.
7114 if (D2CXX->getNumBases() > 0)
7115 return false;
7116 }
7117
7118 // Check the fields.
7119 RecordDecl::field_iterator Field2 = RD2->field_begin(),
7120 Field2End = RD2->field_end(),
7121 Field1 = RD1->field_begin(),
7122 Field1End = RD1->field_end();
7123 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7124 if (!isLayoutCompatible(C, *Field1, *Field2))
7125 return false;
7126 }
7127 if (Field1 != Field1End || Field2 != Field2End)
7128 return false;
7129
7130 return true;
7131}
7132
7133/// \brief Check if two standard-layout unions are layout-compatible.
7134/// (C++11 [class.mem] p18)
7135bool isLayoutCompatibleUnion(ASTContext &C,
7136 RecordDecl *RD1,
7137 RecordDecl *RD2) {
7138 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7139 for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7140 Field2End = RD2->field_end();
7141 Field2 != Field2End; ++Field2) {
7142 UnmatchedFields.insert(*Field2);
7143 }
7144
7145 for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7146 Field1End = RD1->field_end();
7147 Field1 != Field1End; ++Field1) {
7148 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7149 I = UnmatchedFields.begin(),
7150 E = UnmatchedFields.end();
7151
7152 for ( ; I != E; ++I) {
7153 if (isLayoutCompatible(C, *Field1, *I)) {
7154 bool Result = UnmatchedFields.erase(*I);
7155 (void) Result;
7156 assert(Result);
7157 break;
7158 }
7159 }
7160 if (I == E)
7161 return false;
7162 }
7163
7164 return UnmatchedFields.empty();
7165}
7166
7167bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7168 if (RD1->isUnion() != RD2->isUnion())
7169 return false;
7170
7171 if (RD1->isUnion())
7172 return isLayoutCompatibleUnion(C, RD1, RD2);
7173 else
7174 return isLayoutCompatibleStruct(C, RD1, RD2);
7175}
7176
7177/// \brief Check if two types are layout-compatible in C++11 sense.
7178bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7179 if (T1.isNull() || T2.isNull())
7180 return false;
7181
7182 // C++11 [basic.types] p11:
7183 // If two types T1 and T2 are the same type, then T1 and T2 are
7184 // layout-compatible types.
7185 if (C.hasSameType(T1, T2))
7186 return true;
7187
7188 T1 = T1.getCanonicalType().getUnqualifiedType();
7189 T2 = T2.getCanonicalType().getUnqualifiedType();
7190
7191 const Type::TypeClass TC1 = T1->getTypeClass();
7192 const Type::TypeClass TC2 = T2->getTypeClass();
7193
7194 if (TC1 != TC2)
7195 return false;
7196
7197 if (TC1 == Type::Enum) {
7198 return isLayoutCompatible(C,
7199 cast<EnumType>(T1)->getDecl(),
7200 cast<EnumType>(T2)->getDecl());
7201 } else if (TC1 == Type::Record) {
7202 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7203 return false;
7204
7205 return isLayoutCompatible(C,
7206 cast<RecordType>(T1)->getDecl(),
7207 cast<RecordType>(T2)->getDecl());
7208 }
7209
7210 return false;
7211}
7212}
7213
7214//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7215
7216namespace {
7217/// \brief Given a type tag expression find the type tag itself.
7218///
7219/// \param TypeExpr Type tag expression, as it appears in user's code.
7220///
7221/// \param VD Declaration of an identifier that appears in a type tag.
7222///
7223/// \param MagicValue Type tag magic value.
7224bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7225 const ValueDecl **VD, uint64_t *MagicValue) {
7226 while(true) {
7227 if (!TypeExpr)
7228 return false;
7229
7230 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7231
7232 switch (TypeExpr->getStmtClass()) {
7233 case Stmt::UnaryOperatorClass: {
7234 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7235 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7236 TypeExpr = UO->getSubExpr();
7237 continue;
7238 }
7239 return false;
7240 }
7241
7242 case Stmt::DeclRefExprClass: {
7243 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7244 *VD = DRE->getDecl();
7245 return true;
7246 }
7247
7248 case Stmt::IntegerLiteralClass: {
7249 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7250 llvm::APInt MagicValueAPInt = IL->getValue();
7251 if (MagicValueAPInt.getActiveBits() <= 64) {
7252 *MagicValue = MagicValueAPInt.getZExtValue();
7253 return true;
7254 } else
7255 return false;
7256 }
7257
7258 case Stmt::BinaryConditionalOperatorClass:
7259 case Stmt::ConditionalOperatorClass: {
7260 const AbstractConditionalOperator *ACO =
7261 cast<AbstractConditionalOperator>(TypeExpr);
7262 bool Result;
7263 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7264 if (Result)
7265 TypeExpr = ACO->getTrueExpr();
7266 else
7267 TypeExpr = ACO->getFalseExpr();
7268 continue;
7269 }
7270 return false;
7271 }
7272
7273 case Stmt::BinaryOperatorClass: {
7274 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7275 if (BO->getOpcode() == BO_Comma) {
7276 TypeExpr = BO->getRHS();
7277 continue;
7278 }
7279 return false;
7280 }
7281
7282 default:
7283 return false;
7284 }
7285 }
7286}
7287
7288/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7289///
7290/// \param TypeExpr Expression that specifies a type tag.
7291///
7292/// \param MagicValues Registered magic values.
7293///
7294/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7295/// kind.
7296///
7297/// \param TypeInfo Information about the corresponding C type.
7298///
7299/// \returns true if the corresponding C type was found.
7300bool GetMatchingCType(
7301 const IdentifierInfo *ArgumentKind,
7302 const Expr *TypeExpr, const ASTContext &Ctx,
7303 const llvm::DenseMap<Sema::TypeTagMagicValue,
7304 Sema::TypeTagData> *MagicValues,
7305 bool &FoundWrongKind,
7306 Sema::TypeTagData &TypeInfo) {
7307 FoundWrongKind = false;
7308
7309 // Variable declaration that has type_tag_for_datatype attribute.
7310 const ValueDecl *VD = NULL;
7311
7312 uint64_t MagicValue;
7313
7314 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7315 return false;
7316
7317 if (VD) {
7318 for (specific_attr_iterator<TypeTagForDatatypeAttr>
7319 I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7320 E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7321 I != E; ++I) {
7322 if (I->getArgumentKind() != ArgumentKind) {
7323 FoundWrongKind = true;
7324 return false;
7325 }
7326 TypeInfo.Type = I->getMatchingCType();
7327 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7328 TypeInfo.MustBeNull = I->getMustBeNull();
7329 return true;
7330 }
7331 return false;
7332 }
7333
7334 if (!MagicValues)
7335 return false;
7336
7337 llvm::DenseMap<Sema::TypeTagMagicValue,
7338 Sema::TypeTagData>::const_iterator I =
7339 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7340 if (I == MagicValues->end())
7341 return false;
7342
7343 TypeInfo = I->second;
7344 return true;
7345}
7346} // unnamed namespace
7347
7348void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7349 uint64_t MagicValue, QualType Type,
7350 bool LayoutCompatible,
7351 bool MustBeNull) {
7352 if (!TypeTagForDatatypeMagicValues)
7353 TypeTagForDatatypeMagicValues.reset(
7354 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7355
7356 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7357 (*TypeTagForDatatypeMagicValues)[Magic] =
7358 TypeTagData(Type, LayoutCompatible, MustBeNull);
7359}
7360
7361namespace {
7362bool IsSameCharType(QualType T1, QualType T2) {
7363 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7364 if (!BT1)
7365 return false;
7366
7367 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7368 if (!BT2)
7369 return false;
7370
7371 BuiltinType::Kind T1Kind = BT1->getKind();
7372 BuiltinType::Kind T2Kind = BT2->getKind();
7373
7374 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
7375 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
7376 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7377 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7378}
7379} // unnamed namespace
7380
7381void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7382 const Expr * const *ExprArgs) {
7383 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7384 bool IsPointerAttr = Attr->getIsPointer();
7385
7386 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7387 bool FoundWrongKind;
7388 TypeTagData TypeInfo;
7389 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7390 TypeTagForDatatypeMagicValues.get(),
7391 FoundWrongKind, TypeInfo)) {
7392 if (FoundWrongKind)
7393 Diag(TypeTagExpr->getExprLoc(),
7394 diag::warn_type_tag_for_datatype_wrong_kind)
7395 << TypeTagExpr->getSourceRange();
7396 return;
7397 }
7398
7399 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7400 if (IsPointerAttr) {
7401 // Skip implicit cast of pointer to `void *' (as a function argument).
7402 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00007403 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00007404 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007405 ArgumentExpr = ICE->getSubExpr();
7406 }
7407 QualType ArgumentType = ArgumentExpr->getType();
7408
7409 // Passing a `void*' pointer shouldn't trigger a warning.
7410 if (IsPointerAttr && ArgumentType->isVoidPointerType())
7411 return;
7412
7413 if (TypeInfo.MustBeNull) {
7414 // Type tag with matching void type requires a null pointer.
7415 if (!ArgumentExpr->isNullPointerConstant(Context,
7416 Expr::NPC_ValueDependentIsNotNull)) {
7417 Diag(ArgumentExpr->getExprLoc(),
7418 diag::warn_type_safety_null_pointer_required)
7419 << ArgumentKind->getName()
7420 << ArgumentExpr->getSourceRange()
7421 << TypeTagExpr->getSourceRange();
7422 }
7423 return;
7424 }
7425
7426 QualType RequiredType = TypeInfo.Type;
7427 if (IsPointerAttr)
7428 RequiredType = Context.getPointerType(RequiredType);
7429
7430 bool mismatch = false;
7431 if (!TypeInfo.LayoutCompatible) {
7432 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7433
7434 // C++11 [basic.fundamental] p1:
7435 // Plain char, signed char, and unsigned char are three distinct types.
7436 //
7437 // But we treat plain `char' as equivalent to `signed char' or `unsigned
7438 // char' depending on the current char signedness mode.
7439 if (mismatch)
7440 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7441 RequiredType->getPointeeType())) ||
7442 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7443 mismatch = false;
7444 } else
7445 if (IsPointerAttr)
7446 mismatch = !isLayoutCompatible(Context,
7447 ArgumentType->getPointeeType(),
7448 RequiredType->getPointeeType());
7449 else
7450 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7451
7452 if (mismatch)
7453 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00007454 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00007455 << TypeInfo.LayoutCompatible << RequiredType
7456 << ArgumentExpr->getSourceRange()
7457 << TypeTagExpr->getSourceRange();
7458}