blob: 4a5ad1bc961153892089ada297054da66bd1368d [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"
Alexey Bataev1a3320e2015-08-25 14:24:04 +000024#include "clang/AST/ExprOpenMP.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/StmtCXX.h"
26#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000027#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000028#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000029#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000030#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000031#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ScopeInfo.h"
35#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000036#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000037#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000039#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000041#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000042using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000043using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
46 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000047 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
48 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000049}
50
John McCallbebede42011-02-26 05:39:39 +000051/// Checks that a call expression's argument count is the desired number.
52/// This is useful when doing custom type-checking. Returns true on error.
53static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
54 unsigned argCount = call->getNumArgs();
55 if (argCount == desiredArgCount) return false;
56
57 if (argCount < desiredArgCount)
58 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 /*function call*/ << desiredArgCount << argCount
60 << call->getSourceRange();
61
62 // Highlight all the excess arguments.
63 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
64 call->getArg(argCount - 1)->getLocEnd());
65
66 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 /*function call*/ << desiredArgCount << argCount
68 << call->getArg(1)->getSourceRange();
69}
70
Julien Lerouge4a5b4442012-04-28 17:39:16 +000071/// Check that the first argument to __builtin_annotation is an integer
72/// and the second argument is a non-wide string literal.
73static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
74 if (checkArgCount(S, TheCall, 2))
75 return true;
76
77 // First argument should be an integer.
78 Expr *ValArg = TheCall->getArg(0);
79 QualType Ty = ValArg->getType();
80 if (!Ty->isIntegerType()) {
81 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000083 return true;
84 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000085
86 // Second argument should be a constant string.
87 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
88 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
89 if (!Literal || !Literal->isAscii()) {
90 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
92 return true;
93 }
94
95 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000096 return false;
97}
98
Richard Smith6cbd65d2013-07-11 02:27:57 +000099/// Check that the argument to __builtin_addressof is a glvalue, and set the
100/// result type to the corresponding pointer type.
101static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
102 if (checkArgCount(S, TheCall, 1))
103 return true;
104
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000105 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000106 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
107 if (ResultType.isNull())
108 return true;
109
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000110 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000111 TheCall->setType(ResultType);
112 return false;
113}
114
John McCall03107a42015-10-29 20:48:01 +0000115static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
116 if (checkArgCount(S, TheCall, 3))
117 return true;
118
119 // First two arguments should be integers.
120 for (unsigned I = 0; I < 2; ++I) {
121 Expr *Arg = TheCall->getArg(I);
122 QualType Ty = Arg->getType();
123 if (!Ty->isIntegerType()) {
124 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
125 << Ty << Arg->getSourceRange();
126 return true;
127 }
128 }
129
130 // Third argument should be a pointer to a non-const integer.
131 // IRGen correctly handles volatile, restrict, and address spaces, and
132 // the other qualifiers aren't possible.
133 {
134 Expr *Arg = TheCall->getArg(2);
135 QualType Ty = Arg->getType();
136 const auto *PtrTy = Ty->getAs<PointerType>();
137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
138 !PtrTy->getPointeeType().isConstQualified())) {
139 S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
140 << Ty << Arg->getSourceRange();
141 return true;
142 }
143 }
144
145 return false;
146}
147
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000148static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
149 CallExpr *TheCall, unsigned SizeIdx,
150 unsigned DstSizeIdx) {
151 if (TheCall->getNumArgs() <= SizeIdx ||
152 TheCall->getNumArgs() <= DstSizeIdx)
153 return;
154
155 const Expr *SizeArg = TheCall->getArg(SizeIdx);
156 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
157
158 llvm::APSInt Size, DstSize;
159
160 // find out if both sizes are known at compile time
161 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
162 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
163 return;
164
165 if (Size.ule(DstSize))
166 return;
167
168 // confirmed overflow so generate the diagnostic.
169 IdentifierInfo *FnName = FDecl->getIdentifier();
170 SourceLocation SL = TheCall->getLocStart();
171 SourceRange SR = TheCall->getSourceRange();
172
173 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
174}
175
Peter Collingbournef7706832014-12-12 23:41:25 +0000176static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
177 if (checkArgCount(S, BuiltinCall, 2))
178 return true;
179
180 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
181 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
182 Expr *Call = BuiltinCall->getArg(0);
183 Expr *Chain = BuiltinCall->getArg(1);
184
185 if (Call->getStmtClass() != Stmt::CallExprClass) {
186 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
187 << Call->getSourceRange();
188 return true;
189 }
190
191 auto CE = cast<CallExpr>(Call);
192 if (CE->getCallee()->getType()->isBlockPointerType()) {
193 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
194 << Call->getSourceRange();
195 return true;
196 }
197
198 const Decl *TargetDecl = CE->getCalleeDecl();
199 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
200 if (FD->getBuiltinID()) {
201 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
202 << Call->getSourceRange();
203 return true;
204 }
205
206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
207 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
208 << Call->getSourceRange();
209 return true;
210 }
211
212 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
213 if (ChainResult.isInvalid())
214 return true;
215 if (!ChainResult.get()->getType()->isPointerType()) {
216 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
217 << Chain->getSourceRange();
218 return true;
219 }
220
David Majnemerced8bdf2015-02-25 17:36:15 +0000221 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000222 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
223 QualType BuiltinTy = S.Context.getFunctionType(
224 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
225 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
226
227 Builtin =
228 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
229
230 BuiltinCall->setType(CE->getType());
231 BuiltinCall->setValueKind(CE->getValueKind());
232 BuiltinCall->setObjectKind(CE->getObjectKind());
233 BuiltinCall->setCallee(Builtin);
234 BuiltinCall->setArg(1, ChainResult.get());
235
236 return false;
237}
238
Reid Kleckner1d59f992015-01-22 01:36:17 +0000239static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
240 Scope::ScopeFlags NeededScopeFlags,
241 unsigned DiagID) {
242 // Scopes aren't available during instantiation. Fortunately, builtin
243 // functions cannot be template args so they cannot be formed through template
244 // instantiation. Therefore checking once during the parse is sufficient.
245 if (!SemaRef.ActiveTemplateInstantiations.empty())
246 return false;
247
248 Scope *S = SemaRef.getCurScope();
249 while (S && !S->isSEHExceptScope())
250 S = S->getParent();
251 if (!S || !(S->getFlags() & NeededScopeFlags)) {
252 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
253 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
254 << DRE->getDecl()->getIdentifier();
255 return true;
256 }
257
258 return false;
259}
260
John McCalldadc5752010-08-24 06:29:42 +0000261ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000262Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
263 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000264 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000265
Chris Lattner3be167f2010-10-01 23:23:24 +0000266 // Find out if any arguments are required to be integer constant expressions.
267 unsigned ICEArguments = 0;
268 ASTContext::GetBuiltinTypeError Error;
269 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
270 if (Error != ASTContext::GE_None)
271 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
272
273 // If any arguments are required to be ICE's, check and diagnose.
274 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
275 // Skip arguments not required to be ICE's.
276 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
277
278 llvm::APSInt Result;
279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
280 return true;
281 ICEArguments &= ~(1 << ArgNo);
282 }
283
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000285 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000286 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000287 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000288 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000289 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000290 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000291 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000292 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000293 if (SemaBuiltinVAStart(TheCall))
294 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000295 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000296 case Builtin::BI__va_start: {
297 switch (Context.getTargetInfo().getTriple().getArch()) {
298 case llvm::Triple::arm:
299 case llvm::Triple::thumb:
300 if (SemaBuiltinVAStartARM(TheCall))
301 return ExprError();
302 break;
303 default:
304 if (SemaBuiltinVAStart(TheCall))
305 return ExprError();
306 break;
307 }
308 break;
309 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000310 case Builtin::BI__builtin_isgreater:
311 case Builtin::BI__builtin_isgreaterequal:
312 case Builtin::BI__builtin_isless:
313 case Builtin::BI__builtin_islessequal:
314 case Builtin::BI__builtin_islessgreater:
315 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 if (SemaBuiltinUnorderedCompare(TheCall))
317 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000318 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000319 case Builtin::BI__builtin_fpclassify:
320 if (SemaBuiltinFPClassification(TheCall, 6))
321 return ExprError();
322 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000323 case Builtin::BI__builtin_isfinite:
324 case Builtin::BI__builtin_isinf:
325 case Builtin::BI__builtin_isinf_sign:
326 case Builtin::BI__builtin_isnan:
327 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000328 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000329 return ExprError();
330 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000331 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000332 return SemaBuiltinShuffleVector(TheCall);
333 // TheCall will be freed by the smart pointer here, but that's fine, since
334 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000335 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000336 if (SemaBuiltinPrefetch(TheCall))
337 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000338 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000339 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000340 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000341 if (SemaBuiltinAssume(TheCall))
342 return ExprError();
343 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000344 case Builtin::BI__builtin_assume_aligned:
345 if (SemaBuiltinAssumeAligned(TheCall))
346 return ExprError();
347 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000348 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000349 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000350 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000351 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000352 case Builtin::BI__builtin_longjmp:
353 if (SemaBuiltinLongjmp(TheCall))
354 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000355 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000356 case Builtin::BI__builtin_setjmp:
357 if (SemaBuiltinSetjmp(TheCall))
358 return ExprError();
359 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000360 case Builtin::BI_setjmp:
361 case Builtin::BI_setjmpex:
362 if (checkArgCount(*this, TheCall, 1))
363 return true;
364 break;
John McCallbebede42011-02-26 05:39:39 +0000365
366 case Builtin::BI__builtin_classify_type:
367 if (checkArgCount(*this, TheCall, 1)) return true;
368 TheCall->setType(Context.IntTy);
369 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000370 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000371 if (checkArgCount(*this, TheCall, 1)) return true;
372 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000373 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000374 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000375 case Builtin::BI__sync_fetch_and_add_1:
376 case Builtin::BI__sync_fetch_and_add_2:
377 case Builtin::BI__sync_fetch_and_add_4:
378 case Builtin::BI__sync_fetch_and_add_8:
379 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000380 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000381 case Builtin::BI__sync_fetch_and_sub_1:
382 case Builtin::BI__sync_fetch_and_sub_2:
383 case Builtin::BI__sync_fetch_and_sub_4:
384 case Builtin::BI__sync_fetch_and_sub_8:
385 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000386 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000387 case Builtin::BI__sync_fetch_and_or_1:
388 case Builtin::BI__sync_fetch_and_or_2:
389 case Builtin::BI__sync_fetch_and_or_4:
390 case Builtin::BI__sync_fetch_and_or_8:
391 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000392 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000393 case Builtin::BI__sync_fetch_and_and_1:
394 case Builtin::BI__sync_fetch_and_and_2:
395 case Builtin::BI__sync_fetch_and_and_4:
396 case Builtin::BI__sync_fetch_and_and_8:
397 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000398 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000399 case Builtin::BI__sync_fetch_and_xor_1:
400 case Builtin::BI__sync_fetch_and_xor_2:
401 case Builtin::BI__sync_fetch_and_xor_4:
402 case Builtin::BI__sync_fetch_and_xor_8:
403 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000404 case Builtin::BI__sync_fetch_and_nand:
405 case Builtin::BI__sync_fetch_and_nand_1:
406 case Builtin::BI__sync_fetch_and_nand_2:
407 case Builtin::BI__sync_fetch_and_nand_4:
408 case Builtin::BI__sync_fetch_and_nand_8:
409 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000410 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000411 case Builtin::BI__sync_add_and_fetch_1:
412 case Builtin::BI__sync_add_and_fetch_2:
413 case Builtin::BI__sync_add_and_fetch_4:
414 case Builtin::BI__sync_add_and_fetch_8:
415 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000416 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000417 case Builtin::BI__sync_sub_and_fetch_1:
418 case Builtin::BI__sync_sub_and_fetch_2:
419 case Builtin::BI__sync_sub_and_fetch_4:
420 case Builtin::BI__sync_sub_and_fetch_8:
421 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000422 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000423 case Builtin::BI__sync_and_and_fetch_1:
424 case Builtin::BI__sync_and_and_fetch_2:
425 case Builtin::BI__sync_and_and_fetch_4:
426 case Builtin::BI__sync_and_and_fetch_8:
427 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000428 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000429 case Builtin::BI__sync_or_and_fetch_1:
430 case Builtin::BI__sync_or_and_fetch_2:
431 case Builtin::BI__sync_or_and_fetch_4:
432 case Builtin::BI__sync_or_and_fetch_8:
433 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000434 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000435 case Builtin::BI__sync_xor_and_fetch_1:
436 case Builtin::BI__sync_xor_and_fetch_2:
437 case Builtin::BI__sync_xor_and_fetch_4:
438 case Builtin::BI__sync_xor_and_fetch_8:
439 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000440 case Builtin::BI__sync_nand_and_fetch:
441 case Builtin::BI__sync_nand_and_fetch_1:
442 case Builtin::BI__sync_nand_and_fetch_2:
443 case Builtin::BI__sync_nand_and_fetch_4:
444 case Builtin::BI__sync_nand_and_fetch_8:
445 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000446 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000447 case Builtin::BI__sync_val_compare_and_swap_1:
448 case Builtin::BI__sync_val_compare_and_swap_2:
449 case Builtin::BI__sync_val_compare_and_swap_4:
450 case Builtin::BI__sync_val_compare_and_swap_8:
451 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000452 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000453 case Builtin::BI__sync_bool_compare_and_swap_1:
454 case Builtin::BI__sync_bool_compare_and_swap_2:
455 case Builtin::BI__sync_bool_compare_and_swap_4:
456 case Builtin::BI__sync_bool_compare_and_swap_8:
457 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000458 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000459 case Builtin::BI__sync_lock_test_and_set_1:
460 case Builtin::BI__sync_lock_test_and_set_2:
461 case Builtin::BI__sync_lock_test_and_set_4:
462 case Builtin::BI__sync_lock_test_and_set_8:
463 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000464 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000465 case Builtin::BI__sync_lock_release_1:
466 case Builtin::BI__sync_lock_release_2:
467 case Builtin::BI__sync_lock_release_4:
468 case Builtin::BI__sync_lock_release_8:
469 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000470 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000471 case Builtin::BI__sync_swap_1:
472 case Builtin::BI__sync_swap_2:
473 case Builtin::BI__sync_swap_4:
474 case Builtin::BI__sync_swap_8:
475 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000476 return SemaBuiltinAtomicOverloaded(TheCallResult);
Michael Zolotukhin84df1232015-09-08 23:52:33 +0000477 case Builtin::BI__builtin_nontemporal_load:
478 case Builtin::BI__builtin_nontemporal_store:
479 return SemaBuiltinNontemporalOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000480#define BUILTIN(ID, TYPE, ATTRS)
481#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
482 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000483 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000484#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000485 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000486 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000487 return ExprError();
488 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000489 case Builtin::BI__builtin_addressof:
490 if (SemaBuiltinAddressof(*this, TheCall))
491 return ExprError();
492 break;
John McCall03107a42015-10-29 20:48:01 +0000493 case Builtin::BI__builtin_add_overflow:
494 case Builtin::BI__builtin_sub_overflow:
495 case Builtin::BI__builtin_mul_overflow:
496 if (SemaBuiltinOverflow(*this, TheCall))
497 return ExprError();
498 break;
Richard Smith760520b2014-06-03 23:27:44 +0000499 case Builtin::BI__builtin_operator_new:
500 case Builtin::BI__builtin_operator_delete:
501 if (!getLangOpts().CPlusPlus) {
502 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
503 << (BuiltinID == Builtin::BI__builtin_operator_new
504 ? "__builtin_operator_new"
505 : "__builtin_operator_delete")
506 << "C++";
507 return ExprError();
508 }
509 // CodeGen assumes it can find the global new and delete to call,
510 // so ensure that they are declared.
511 DeclareGlobalNewDelete();
512 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000513
514 // check secure string manipulation functions where overflows
515 // are detectable at compile time
516 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000517 case Builtin::BI__builtin___memmove_chk:
518 case Builtin::BI__builtin___memset_chk:
519 case Builtin::BI__builtin___strlcat_chk:
520 case Builtin::BI__builtin___strlcpy_chk:
521 case Builtin::BI__builtin___strncat_chk:
522 case Builtin::BI__builtin___strncpy_chk:
523 case Builtin::BI__builtin___stpncpy_chk:
524 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
525 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000526 case Builtin::BI__builtin___memccpy_chk:
527 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
528 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000529 case Builtin::BI__builtin___snprintf_chk:
530 case Builtin::BI__builtin___vsnprintf_chk:
531 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
532 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000533
534 case Builtin::BI__builtin_call_with_static_chain:
535 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
536 return ExprError();
537 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000538
539 case Builtin::BI__exception_code:
540 case Builtin::BI_exception_code: {
541 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
542 diag::err_seh___except_block))
543 return ExprError();
544 break;
545 }
546 case Builtin::BI__exception_info:
547 case Builtin::BI_exception_info: {
548 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
549 diag::err_seh___except_filter))
550 return ExprError();
551 break;
552 }
553
David Majnemerba3e5ec2015-03-13 18:26:17 +0000554 case Builtin::BI__GetExceptionInfo:
555 if (checkArgCount(*this, TheCall, 1))
556 return ExprError();
557
558 if (CheckCXXThrowOperand(
559 TheCall->getLocStart(),
560 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
561 TheCall))
562 return ExprError();
563
564 TheCall->setType(Context.VoidPtrTy);
565 break;
566
Nate Begeman4904e322010-06-08 02:47:44 +0000567 }
Richard Smith760520b2014-06-03 23:27:44 +0000568
Nate Begeman4904e322010-06-08 02:47:44 +0000569 // Since the target specific builtins for each arch overlap, only check those
570 // of the arch we are compiling for.
Artem Belevich9674a642015-09-22 17:23:05 +0000571 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000572 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000573 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000574 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000575 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000576 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000577 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
578 return ExprError();
579 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000580 case llvm::Triple::aarch64:
581 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000582 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000583 return ExprError();
584 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000585 case llvm::Triple::mips:
586 case llvm::Triple::mipsel:
587 case llvm::Triple::mips64:
588 case llvm::Triple::mips64el:
589 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
590 return ExprError();
591 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000592 case llvm::Triple::systemz:
593 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
594 return ExprError();
595 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000596 case llvm::Triple::x86:
597 case llvm::Triple::x86_64:
598 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
599 return ExprError();
600 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000601 case llvm::Triple::ppc:
602 case llvm::Triple::ppc64:
603 case llvm::Triple::ppc64le:
604 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
605 return ExprError();
606 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000607 default:
608 break;
609 }
610 }
611
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000612 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000613}
614
Nate Begeman91e1fea2010-06-14 05:21:25 +0000615// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000616static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000617 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000618 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000619 switch (Type.getEltType()) {
620 case NeonTypeFlags::Int8:
621 case NeonTypeFlags::Poly8:
622 return shift ? 7 : (8 << IsQuad) - 1;
623 case NeonTypeFlags::Int16:
624 case NeonTypeFlags::Poly16:
625 return shift ? 15 : (4 << IsQuad) - 1;
626 case NeonTypeFlags::Int32:
627 return shift ? 31 : (2 << IsQuad) - 1;
628 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000629 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000630 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000631 case NeonTypeFlags::Poly128:
632 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000633 case NeonTypeFlags::Float16:
634 assert(!shift && "cannot shift float types!");
635 return (4 << IsQuad) - 1;
636 case NeonTypeFlags::Float32:
637 assert(!shift && "cannot shift float types!");
638 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000639 case NeonTypeFlags::Float64:
640 assert(!shift && "cannot shift float types!");
641 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000642 }
David Blaikie8a40f702012-01-17 06:56:22 +0000643 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000644}
645
Bob Wilsone4d77232011-11-08 05:04:11 +0000646/// getNeonEltType - Return the QualType corresponding to the elements of
647/// the vector type specified by the NeonTypeFlags. This is used to check
648/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000649static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000650 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000651 switch (Flags.getEltType()) {
652 case NeonTypeFlags::Int8:
653 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
654 case NeonTypeFlags::Int16:
655 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
656 case NeonTypeFlags::Int32:
657 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
658 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000659 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000660 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
661 else
662 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
663 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000664 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000665 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000666 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000667 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000668 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000669 if (IsInt64Long)
670 return Context.UnsignedLongTy;
671 else
672 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000673 case NeonTypeFlags::Poly128:
674 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000675 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000676 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000677 case NeonTypeFlags::Float32:
678 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000679 case NeonTypeFlags::Float64:
680 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000681 }
David Blaikie8a40f702012-01-17 06:56:22 +0000682 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000683}
684
Tim Northover12670412014-02-19 10:37:05 +0000685bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000686 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000687 uint64_t mask = 0;
688 unsigned TV = 0;
689 int PtrArgNum = -1;
690 bool HasConstPtr = false;
691 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000692#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000693#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000694#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000695 }
696
697 // For NEON intrinsics which are overloaded on vector element type, validate
698 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000699 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000700 if (mask) {
701 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
702 return true;
703
704 TV = Result.getLimitedValue(64);
705 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
706 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000707 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000708 }
709
710 if (PtrArgNum >= 0) {
711 // Check that pointer arguments have the specified type.
712 Expr *Arg = TheCall->getArg(PtrArgNum);
713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
714 Arg = ICE->getSubExpr();
715 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
716 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000717
Tim Northovera2ee4332014-03-29 15:09:45 +0000718 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000719 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000720 bool IsInt64Long =
721 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
722 QualType EltTy =
723 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000724 if (HasConstPtr)
725 EltTy = EltTy.withConst();
726 QualType LHSTy = Context.getPointerType(EltTy);
727 AssignConvertType ConvTy;
728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
729 if (RHS.isInvalid())
730 return true;
731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
732 RHS.get(), AA_Assigning))
733 return true;
734 }
735
736 // For NEON intrinsics which take an immediate value as part of the
737 // instruction, range check them here.
738 unsigned i = 0, l = 0, u = 0;
739 switch (BuiltinID) {
740 default:
741 return false;
Tim Northover12670412014-02-19 10:37:05 +0000742#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000743#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000744#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000745 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000746
Richard Sandiford28940af2014-04-16 08:47:51 +0000747 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000748}
749
Tim Northovera2ee4332014-03-29 15:09:45 +0000750bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
751 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000752 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000753 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000754 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000755 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000756 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000757 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
758 BuiltinID == AArch64::BI__builtin_arm_strex ||
759 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000760 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000761 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000762 BuiltinID == ARM::BI__builtin_arm_ldaex ||
763 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
764 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000765
766 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
767
768 // Ensure that we have the proper number of arguments.
769 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
770 return true;
771
772 // Inspect the pointer argument of the atomic builtin. This should always be
773 // a pointer type, whose element is an integral scalar or pointer type.
774 // Because it is a pointer type, we don't have to worry about any implicit
775 // casts here.
776 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
777 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
778 if (PointerArgRes.isInvalid())
779 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000780 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000781
782 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
783 if (!pointerType) {
784 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
785 << PointerArg->getType() << PointerArg->getSourceRange();
786 return true;
787 }
788
789 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
790 // task is to insert the appropriate casts into the AST. First work out just
791 // what the appropriate type is.
792 QualType ValType = pointerType->getPointeeType();
793 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
794 if (IsLdrex)
795 AddrType.addConst();
796
797 // Issue a warning if the cast is dodgy.
798 CastKind CastNeeded = CK_NoOp;
799 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
800 CastNeeded = CK_BitCast;
801 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
802 << PointerArg->getType()
803 << Context.getPointerType(AddrType)
804 << AA_Passing << PointerArg->getSourceRange();
805 }
806
807 // Finally, do the cast and replace the argument with the corrected version.
808 AddrType = Context.getPointerType(AddrType);
809 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
810 if (PointerArgRes.isInvalid())
811 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000812 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000813
814 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
815
816 // In general, we allow ints, floats and pointers to be loaded and stored.
817 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
818 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
819 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
820 << PointerArg->getType() << PointerArg->getSourceRange();
821 return true;
822 }
823
824 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000825 if (Context.getTypeSize(ValType) > MaxWidth) {
826 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000827 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
828 << PointerArg->getType() << PointerArg->getSourceRange();
829 return true;
830 }
831
832 switch (ValType.getObjCLifetime()) {
833 case Qualifiers::OCL_None:
834 case Qualifiers::OCL_ExplicitNone:
835 // okay
836 break;
837
838 case Qualifiers::OCL_Weak:
839 case Qualifiers::OCL_Strong:
840 case Qualifiers::OCL_Autoreleasing:
841 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
842 << ValType << PointerArg->getSourceRange();
843 return true;
844 }
845
846
847 if (IsLdrex) {
848 TheCall->setType(ValType);
849 return false;
850 }
851
852 // Initialize the argument to be stored.
853 ExprResult ValArg = TheCall->getArg(0);
854 InitializedEntity Entity = InitializedEntity::InitializeParameter(
855 Context, ValType, /*consume*/ false);
856 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
857 if (ValArg.isInvalid())
858 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000859 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000860
861 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
862 // but the custom checker bypasses all default analysis.
863 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000864 return false;
865}
866
Nate Begeman4904e322010-06-08 02:47:44 +0000867bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000868 llvm::APSInt Result;
869
Tim Northover6aacd492013-07-16 09:47:53 +0000870 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000871 BuiltinID == ARM::BI__builtin_arm_ldaex ||
872 BuiltinID == ARM::BI__builtin_arm_strex ||
873 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000874 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000875 }
876
Yi Kong26d104a2014-08-13 19:18:14 +0000877 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
878 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
879 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
880 }
881
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000882 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
883 BuiltinID == ARM::BI__builtin_arm_wsr64)
884 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
885
886 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
887 BuiltinID == ARM::BI__builtin_arm_rsrp ||
888 BuiltinID == ARM::BI__builtin_arm_wsr ||
889 BuiltinID == ARM::BI__builtin_arm_wsrp)
890 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
891
Tim Northover12670412014-02-19 10:37:05 +0000892 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
893 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000894
Yi Kong4efadfb2014-07-03 16:01:25 +0000895 // For intrinsics which take an immediate value as part of the instruction,
896 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000897 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000898 switch (BuiltinID) {
899 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000900 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
901 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000902 case ARM::BI__builtin_arm_vcvtr_f:
903 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000904 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000905 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000906 case ARM::BI__builtin_arm_isb:
907 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000908 }
Nate Begemand773fe62010-06-13 04:47:52 +0000909
Nate Begemanf568b072010-08-03 21:32:34 +0000910 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000911 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000912}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000913
Tim Northover573cbee2014-05-24 12:52:07 +0000914bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000915 CallExpr *TheCall) {
916 llvm::APSInt Result;
917
Tim Northover573cbee2014-05-24 12:52:07 +0000918 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000919 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
920 BuiltinID == AArch64::BI__builtin_arm_strex ||
921 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000922 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
923 }
924
Yi Konga5548432014-08-13 19:18:20 +0000925 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
926 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
927 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
928 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
929 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
930 }
931
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000932 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
933 BuiltinID == AArch64::BI__builtin_arm_wsr64)
934 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
935
936 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
937 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
938 BuiltinID == AArch64::BI__builtin_arm_wsr ||
939 BuiltinID == AArch64::BI__builtin_arm_wsrp)
940 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
941
Tim Northovera2ee4332014-03-29 15:09:45 +0000942 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
943 return true;
944
Yi Kong19a29ac2014-07-17 10:52:06 +0000945 // For intrinsics which take an immediate value as part of the instruction,
946 // range check them here.
947 unsigned i = 0, l = 0, u = 0;
948 switch (BuiltinID) {
949 default: return false;
950 case AArch64::BI__builtin_arm_dmb:
951 case AArch64::BI__builtin_arm_dsb:
952 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
953 }
954
Yi Kong19a29ac2014-07-17 10:52:06 +0000955 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000956}
957
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000958bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
959 unsigned i = 0, l = 0, u = 0;
960 switch (BuiltinID) {
961 default: return false;
962 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
963 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000964 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
965 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
966 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
967 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
968 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000969 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000970
Richard Sandiford28940af2014-04-16 08:47:51 +0000971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000972}
973
Kit Bartone50adcb2015-03-30 19:40:59 +0000974bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
975 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000976 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
977 BuiltinID == PPC::BI__builtin_divdeu ||
978 BuiltinID == PPC::BI__builtin_bpermd;
979 bool IsTarget64Bit = Context.getTargetInfo()
980 .getTypeWidth(Context
981 .getTargetInfo()
982 .getIntPtrType()) == 64;
983 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
984 BuiltinID == PPC::BI__builtin_divweu ||
985 BuiltinID == PPC::BI__builtin_divde ||
986 BuiltinID == PPC::BI__builtin_divdeu;
987
988 if (Is64BitBltin && !IsTarget64Bit)
989 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
990 << TheCall->getSourceRange();
991
992 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
993 (BuiltinID == PPC::BI__builtin_bpermd &&
994 !Context.getTargetInfo().hasFeature("bpermd")))
995 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
996 << TheCall->getSourceRange();
997
Kit Bartone50adcb2015-03-30 19:40:59 +0000998 switch (BuiltinID) {
999 default: return false;
1000 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1001 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1004 case PPC::BI__builtin_tbegin:
1005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1007 case PPC::BI__builtin_tabortwc:
1008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1009 case PPC::BI__builtin_tabortwci:
1010 case PPC::BI__builtin_tabortdci:
1011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1013 }
1014 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1015}
1016
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001017bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1018 CallExpr *TheCall) {
1019 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1020 Expr *Arg = TheCall->getArg(0);
1021 llvm::APSInt AbortCode(32);
1022 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1023 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1024 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1025 << Arg->getSourceRange();
1026 }
1027
Ulrich Weigand5722c0f2015-05-05 19:36:42 +00001028 // For intrinsics which take an immediate value as part of the instruction,
1029 // range check them here.
1030 unsigned i = 0, l = 0, u = 0;
1031 switch (BuiltinID) {
1032 default: return false;
1033 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1034 case SystemZ::BI__builtin_s390_verimb:
1035 case SystemZ::BI__builtin_s390_verimh:
1036 case SystemZ::BI__builtin_s390_verimf:
1037 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1038 case SystemZ::BI__builtin_s390_vfaeb:
1039 case SystemZ::BI__builtin_s390_vfaeh:
1040 case SystemZ::BI__builtin_s390_vfaef:
1041 case SystemZ::BI__builtin_s390_vfaebs:
1042 case SystemZ::BI__builtin_s390_vfaehs:
1043 case SystemZ::BI__builtin_s390_vfaefs:
1044 case SystemZ::BI__builtin_s390_vfaezb:
1045 case SystemZ::BI__builtin_s390_vfaezh:
1046 case SystemZ::BI__builtin_s390_vfaezf:
1047 case SystemZ::BI__builtin_s390_vfaezbs:
1048 case SystemZ::BI__builtin_s390_vfaezhs:
1049 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1050 case SystemZ::BI__builtin_s390_vfidb:
1051 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1052 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1053 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1054 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1055 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1056 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1057 case SystemZ::BI__builtin_s390_vstrcb:
1058 case SystemZ::BI__builtin_s390_vstrch:
1059 case SystemZ::BI__builtin_s390_vstrcf:
1060 case SystemZ::BI__builtin_s390_vstrczb:
1061 case SystemZ::BI__builtin_s390_vstrczh:
1062 case SystemZ::BI__builtin_s390_vstrczf:
1063 case SystemZ::BI__builtin_s390_vstrcbs:
1064 case SystemZ::BI__builtin_s390_vstrchs:
1065 case SystemZ::BI__builtin_s390_vstrcfs:
1066 case SystemZ::BI__builtin_s390_vstrczbs:
1067 case SystemZ::BI__builtin_s390_vstrczhs:
1068 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1069 }
1070 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001071}
1072
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001073bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001074 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001075 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001076 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001077 case X86::BI__builtin_cpu_supports:
1078 return SemaBuiltinCpuSupports(TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001079 case X86::BI__builtin_ms_va_start:
1080 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001081 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001082 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001083 case X86::BI__builtin_ia32_vpermil2pd:
1084 case X86::BI__builtin_ia32_vpermil2pd256:
1085 case X86::BI__builtin_ia32_vpermil2ps:
1086 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001087 case X86::BI__builtin_ia32_cmpb128_mask:
1088 case X86::BI__builtin_ia32_cmpw128_mask:
1089 case X86::BI__builtin_ia32_cmpd128_mask:
1090 case X86::BI__builtin_ia32_cmpq128_mask:
1091 case X86::BI__builtin_ia32_cmpb256_mask:
1092 case X86::BI__builtin_ia32_cmpw256_mask:
1093 case X86::BI__builtin_ia32_cmpd256_mask:
1094 case X86::BI__builtin_ia32_cmpq256_mask:
1095 case X86::BI__builtin_ia32_cmpb512_mask:
1096 case X86::BI__builtin_ia32_cmpw512_mask:
1097 case X86::BI__builtin_ia32_cmpd512_mask:
1098 case X86::BI__builtin_ia32_cmpq512_mask:
1099 case X86::BI__builtin_ia32_ucmpb128_mask:
1100 case X86::BI__builtin_ia32_ucmpw128_mask:
1101 case X86::BI__builtin_ia32_ucmpd128_mask:
1102 case X86::BI__builtin_ia32_ucmpq128_mask:
1103 case X86::BI__builtin_ia32_ucmpb256_mask:
1104 case X86::BI__builtin_ia32_ucmpw256_mask:
1105 case X86::BI__builtin_ia32_ucmpd256_mask:
1106 case X86::BI__builtin_ia32_ucmpq256_mask:
1107 case X86::BI__builtin_ia32_ucmpb512_mask:
1108 case X86::BI__builtin_ia32_ucmpw512_mask:
1109 case X86::BI__builtin_ia32_ucmpd512_mask:
1110 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001111 case X86::BI__builtin_ia32_roundps:
1112 case X86::BI__builtin_ia32_roundpd:
1113 case X86::BI__builtin_ia32_roundps256:
1114 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1115 case X86::BI__builtin_ia32_roundss:
1116 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1117 case X86::BI__builtin_ia32_cmpps:
1118 case X86::BI__builtin_ia32_cmpss:
1119 case X86::BI__builtin_ia32_cmppd:
1120 case X86::BI__builtin_ia32_cmpsd:
1121 case X86::BI__builtin_ia32_cmpps256:
1122 case X86::BI__builtin_ia32_cmppd256:
1123 case X86::BI__builtin_ia32_cmpps512_mask:
1124 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001125 case X86::BI__builtin_ia32_vpcomub:
1126 case X86::BI__builtin_ia32_vpcomuw:
1127 case X86::BI__builtin_ia32_vpcomud:
1128 case X86::BI__builtin_ia32_vpcomuq:
1129 case X86::BI__builtin_ia32_vpcomb:
1130 case X86::BI__builtin_ia32_vpcomw:
1131 case X86::BI__builtin_ia32_vpcomd:
1132 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001133 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001134 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001135}
1136
Richard Smith55ce3522012-06-25 20:30:08 +00001137/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1138/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1139/// Returns true when the format fits the function and the FormatStringInfo has
1140/// been populated.
1141bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1142 FormatStringInfo *FSI) {
1143 FSI->HasVAListArg = Format->getFirstArg() == 0;
1144 FSI->FormatIdx = Format->getFormatIdx() - 1;
1145 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001146
Richard Smith55ce3522012-06-25 20:30:08 +00001147 // The way the format attribute works in GCC, the implicit this argument
1148 // of member functions is counted. However, it doesn't appear in our own
1149 // lists, so decrement format_idx in that case.
1150 if (IsCXXMember) {
1151 if(FSI->FormatIdx == 0)
1152 return false;
1153 --FSI->FormatIdx;
1154 if (FSI->FirstDataArg != 0)
1155 --FSI->FirstDataArg;
1156 }
1157 return true;
1158}
Mike Stump11289f42009-09-09 15:08:12 +00001159
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001160/// Checks if a the given expression evaluates to null.
1161///
1162/// \brief Returns true if the value evaluates to null.
1163static bool CheckNonNullExpr(Sema &S,
1164 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001165 // If the expression has non-null type, it doesn't evaluate to null.
1166 if (auto nullability
1167 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1168 if (*nullability == NullabilityKind::NonNull)
1169 return false;
1170 }
1171
Ted Kremeneka146db32014-01-17 06:24:47 +00001172 // As a special case, transparent unions initialized with zero are
1173 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001174 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001175 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1176 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001177 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001178 if (const InitListExpr *ILE =
1179 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001180 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001181 }
1182
1183 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001184 return (!Expr->isValueDependent() &&
1185 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1186 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001187}
1188
1189static void CheckNonNullArgument(Sema &S,
1190 const Expr *ArgExpr,
1191 SourceLocation CallSiteLoc) {
1192 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001193 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1194 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001195}
1196
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001197bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1198 FormatStringInfo FSI;
1199 if ((GetFormatStringType(Format) == FST_NSString) &&
1200 getFormatStringInfo(Format, false, &FSI)) {
1201 Idx = FSI.FormatIdx;
1202 return true;
1203 }
1204 return false;
1205}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001206/// \brief Diagnose use of %s directive in an NSString which is being passed
1207/// as formatting string to formatting method.
1208static void
1209DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1210 const NamedDecl *FDecl,
1211 Expr **Args,
1212 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001213 unsigned Idx = 0;
1214 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001215 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1216 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001217 Idx = 2;
1218 Format = true;
1219 }
1220 else
1221 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1222 if (S.GetFormatNSStringIdx(I, Idx)) {
1223 Format = true;
1224 break;
1225 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001226 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001227 if (!Format || NumArgs <= Idx)
1228 return;
1229 const Expr *FormatExpr = Args[Idx];
1230 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1231 FormatExpr = CSCE->getSubExpr();
1232 const StringLiteral *FormatString;
1233 if (const ObjCStringLiteral *OSL =
1234 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1235 FormatString = OSL->getString();
1236 else
1237 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1238 if (!FormatString)
1239 return;
1240 if (S.FormatStringHasSArg(FormatString)) {
1241 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1242 << "%s" << 1 << 1;
1243 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1244 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001245 }
1246}
1247
Douglas Gregorb4866e82015-06-19 18:13:19 +00001248/// Determine whether the given type has a non-null nullability annotation.
1249static bool isNonNullType(ASTContext &ctx, QualType type) {
1250 if (auto nullability = type->getNullability(ctx))
1251 return *nullability == NullabilityKind::NonNull;
1252
1253 return false;
1254}
1255
Ted Kremenek2bc73332014-01-17 06:24:43 +00001256static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001257 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001258 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001259 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001260 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001261 assert((FDecl || Proto) && "Need a function declaration or prototype");
1262
Ted Kremenek9aedc152014-01-17 06:24:56 +00001263 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001264 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001265 if (FDecl) {
1266 // Handle the nonnull attribute on the function/method declaration itself.
1267 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1268 if (!NonNull->args_size()) {
1269 // Easy case: all pointer arguments are nonnull.
1270 for (const auto *Arg : Args)
1271 if (S.isValidPointerAttrType(Arg->getType()))
1272 CheckNonNullArgument(S, Arg, CallSiteLoc);
1273 return;
1274 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001275
Douglas Gregorb4866e82015-06-19 18:13:19 +00001276 for (unsigned Val : NonNull->args()) {
1277 if (Val >= Args.size())
1278 continue;
1279 if (NonNullArgs.empty())
1280 NonNullArgs.resize(Args.size());
1281 NonNullArgs.set(Val);
1282 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001283 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001284 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001285
Douglas Gregorb4866e82015-06-19 18:13:19 +00001286 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1287 // Handle the nonnull attribute on the parameters of the
1288 // function/method.
1289 ArrayRef<ParmVarDecl*> parms;
1290 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1291 parms = FD->parameters();
1292 else
1293 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1294
1295 unsigned ParamIndex = 0;
1296 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1297 I != E; ++I, ++ParamIndex) {
1298 const ParmVarDecl *PVD = *I;
1299 if (PVD->hasAttr<NonNullAttr>() ||
1300 isNonNullType(S.Context, PVD->getType())) {
1301 if (NonNullArgs.empty())
1302 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001303
Douglas Gregorb4866e82015-06-19 18:13:19 +00001304 NonNullArgs.set(ParamIndex);
1305 }
1306 }
1307 } else {
1308 // If we have a non-function, non-method declaration but no
1309 // function prototype, try to dig out the function prototype.
1310 if (!Proto) {
1311 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1312 QualType type = VD->getType().getNonReferenceType();
1313 if (auto pointerType = type->getAs<PointerType>())
1314 type = pointerType->getPointeeType();
1315 else if (auto blockType = type->getAs<BlockPointerType>())
1316 type = blockType->getPointeeType();
1317 // FIXME: data member pointers?
1318
1319 // Dig out the function prototype, if there is one.
1320 Proto = type->getAs<FunctionProtoType>();
1321 }
1322 }
1323
1324 // Fill in non-null argument information from the nullability
1325 // information on the parameter types (if we have them).
1326 if (Proto) {
1327 unsigned Index = 0;
1328 for (auto paramType : Proto->getParamTypes()) {
1329 if (isNonNullType(S.Context, paramType)) {
1330 if (NonNullArgs.empty())
1331 NonNullArgs.resize(Args.size());
1332
1333 NonNullArgs.set(Index);
1334 }
1335
1336 ++Index;
1337 }
1338 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001339 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001340
Douglas Gregorb4866e82015-06-19 18:13:19 +00001341 // Check for non-null arguments.
1342 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1343 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001344 if (NonNullArgs[ArgIndex])
1345 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001346 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001347}
1348
Richard Smith55ce3522012-06-25 20:30:08 +00001349/// Handles the checks for format strings, non-POD arguments to vararg
1350/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001351void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1352 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001353 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001354 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001355 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001356 if (CurContext->isDependentContext())
1357 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001358
Ted Kremenekb8176da2010-09-09 04:33:05 +00001359 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001360 llvm::SmallBitVector CheckedVarArgs;
1361 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001362 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001363 // Only create vector if there are format attributes.
1364 CheckedVarArgs.resize(Args.size());
1365
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001366 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001367 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001368 }
Richard Smithd7293d72013-08-05 18:49:43 +00001369 }
Richard Smith55ce3522012-06-25 20:30:08 +00001370
1371 // Refuse POD arguments that weren't caught by the format string
1372 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001373 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001374 unsigned NumParams = Proto ? Proto->getNumParams()
1375 : FDecl && isa<FunctionDecl>(FDecl)
1376 ? cast<FunctionDecl>(FDecl)->getNumParams()
1377 : FDecl && isa<ObjCMethodDecl>(FDecl)
1378 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1379 : 0;
1380
Alp Toker9cacbab2014-01-20 20:26:09 +00001381 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001382 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001383 if (const Expr *Arg = Args[ArgIdx]) {
1384 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1385 checkVariadicArgument(Arg, CallType);
1386 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001387 }
Richard Smithd7293d72013-08-05 18:49:43 +00001388 }
Mike Stump11289f42009-09-09 15:08:12 +00001389
Douglas Gregorb4866e82015-06-19 18:13:19 +00001390 if (FDecl || Proto) {
1391 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001392
Richard Trieu41bc0992013-06-22 00:20:41 +00001393 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001394 if (FDecl) {
1395 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1396 CheckArgumentWithTypeTag(I, Args.data());
1397 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001398 }
Richard Smith55ce3522012-06-25 20:30:08 +00001399}
1400
1401/// CheckConstructorCall - Check a constructor call for correctness and safety
1402/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001403void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1404 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001405 const FunctionProtoType *Proto,
1406 SourceLocation Loc) {
1407 VariadicCallType CallType =
1408 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001409 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1410 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001411}
1412
1413/// CheckFunctionCall - Check a direct function call for various correctness
1414/// and safety properties not strictly enforced by the C type system.
1415bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1416 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001417 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1418 isa<CXXMethodDecl>(FDecl);
1419 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1420 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001421 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1422 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001423 Expr** Args = TheCall->getArgs();
1424 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001425 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001426 // If this is a call to a member operator, hide the first argument
1427 // from checkCall.
1428 // FIXME: Our choice of AST representation here is less than ideal.
1429 ++Args;
1430 --NumArgs;
1431 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001432 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001433 IsMemberFunction, TheCall->getRParenLoc(),
1434 TheCall->getCallee()->getSourceRange(), CallType);
1435
1436 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1437 // None of the checks below are needed for functions that don't have
1438 // simple names (e.g., C++ conversion functions).
1439 if (!FnInfo)
1440 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001441
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001442 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001443 if (getLangOpts().ObjC1)
1444 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001445
Anna Zaks22122702012-01-17 00:37:07 +00001446 unsigned CMId = FDecl->getMemoryFunctionKind();
1447 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001448 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001449
Anna Zaks201d4892012-01-13 21:52:01 +00001450 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001451 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001452 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001453 else if (CMId == Builtin::BIstrncat)
1454 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001455 else
Anna Zaks22122702012-01-17 00:37:07 +00001456 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001457
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001458 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001459}
1460
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001461bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001462 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001463 VariadicCallType CallType =
1464 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001465
Douglas Gregorb4866e82015-06-19 18:13:19 +00001466 checkCall(Method, nullptr, Args,
1467 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1468 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001469
1470 return false;
1471}
1472
Richard Trieu664c4c62013-06-20 21:03:13 +00001473bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1474 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001475 QualType Ty;
1476 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001477 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001478 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001479 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001480 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001481 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregorb4866e82015-06-19 18:13:19 +00001483 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1484 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001485 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001486
Richard Trieu664c4c62013-06-20 21:03:13 +00001487 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001488 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001489 CallType = VariadicDoesNotApply;
1490 } else if (Ty->isBlockPointerType()) {
1491 CallType = VariadicBlock;
1492 } else { // Ty->isFunctionPointerType()
1493 CallType = VariadicFunction;
1494 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001495
Douglas Gregorb4866e82015-06-19 18:13:19 +00001496 checkCall(NDecl, Proto,
1497 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1498 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001499 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001500
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001501 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001502}
1503
Richard Trieu41bc0992013-06-22 00:20:41 +00001504/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1505/// such as function pointers returned from functions.
1506bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001507 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001508 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001509 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001510 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001511 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001512 TheCall->getCallee()->getSourceRange(), CallType);
1513
1514 return false;
1515}
1516
Tim Northovere94a34c2014-03-11 10:49:14 +00001517static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1518 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1519 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1520 return false;
1521
1522 switch (Op) {
1523 case AtomicExpr::AO__c11_atomic_init:
1524 llvm_unreachable("There is no ordering argument for an init");
1525
1526 case AtomicExpr::AO__c11_atomic_load:
1527 case AtomicExpr::AO__atomic_load_n:
1528 case AtomicExpr::AO__atomic_load:
1529 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1530 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1531
1532 case AtomicExpr::AO__c11_atomic_store:
1533 case AtomicExpr::AO__atomic_store:
1534 case AtomicExpr::AO__atomic_store_n:
1535 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1536 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1537 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1538
1539 default:
1540 return true;
1541 }
1542}
1543
Richard Smithfeea8832012-04-12 05:08:17 +00001544ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1545 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001546 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1547 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001548
Richard Smithfeea8832012-04-12 05:08:17 +00001549 // All these operations take one of the following forms:
1550 enum {
1551 // C __c11_atomic_init(A *, C)
1552 Init,
1553 // C __c11_atomic_load(A *, int)
1554 Load,
1555 // void __atomic_load(A *, CP, int)
1556 Copy,
1557 // C __c11_atomic_add(A *, M, int)
1558 Arithmetic,
1559 // C __atomic_exchange_n(A *, CP, int)
1560 Xchg,
1561 // void __atomic_exchange(A *, C *, CP, int)
1562 GNUXchg,
1563 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1564 C11CmpXchg,
1565 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1566 GNUCmpXchg
1567 } Form = Init;
1568 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1569 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1570 // where:
1571 // C is an appropriate type,
1572 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1573 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1574 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1575 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001576
Gabor Horvath98bd0982015-03-16 09:59:54 +00001577 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1578 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1579 AtomicExpr::AO__atomic_load,
1580 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001581 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1582 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1583 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1584 Op == AtomicExpr::AO__atomic_store_n ||
1585 Op == AtomicExpr::AO__atomic_exchange_n ||
1586 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1587 bool IsAddSub = false;
1588
1589 switch (Op) {
1590 case AtomicExpr::AO__c11_atomic_init:
1591 Form = Init;
1592 break;
1593
1594 case AtomicExpr::AO__c11_atomic_load:
1595 case AtomicExpr::AO__atomic_load_n:
1596 Form = Load;
1597 break;
1598
1599 case AtomicExpr::AO__c11_atomic_store:
1600 case AtomicExpr::AO__atomic_load:
1601 case AtomicExpr::AO__atomic_store:
1602 case AtomicExpr::AO__atomic_store_n:
1603 Form = Copy;
1604 break;
1605
1606 case AtomicExpr::AO__c11_atomic_fetch_add:
1607 case AtomicExpr::AO__c11_atomic_fetch_sub:
1608 case AtomicExpr::AO__atomic_fetch_add:
1609 case AtomicExpr::AO__atomic_fetch_sub:
1610 case AtomicExpr::AO__atomic_add_fetch:
1611 case AtomicExpr::AO__atomic_sub_fetch:
1612 IsAddSub = true;
1613 // Fall through.
1614 case AtomicExpr::AO__c11_atomic_fetch_and:
1615 case AtomicExpr::AO__c11_atomic_fetch_or:
1616 case AtomicExpr::AO__c11_atomic_fetch_xor:
1617 case AtomicExpr::AO__atomic_fetch_and:
1618 case AtomicExpr::AO__atomic_fetch_or:
1619 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001620 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001621 case AtomicExpr::AO__atomic_and_fetch:
1622 case AtomicExpr::AO__atomic_or_fetch:
1623 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001624 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001625 Form = Arithmetic;
1626 break;
1627
1628 case AtomicExpr::AO__c11_atomic_exchange:
1629 case AtomicExpr::AO__atomic_exchange_n:
1630 Form = Xchg;
1631 break;
1632
1633 case AtomicExpr::AO__atomic_exchange:
1634 Form = GNUXchg;
1635 break;
1636
1637 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1638 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1639 Form = C11CmpXchg;
1640 break;
1641
1642 case AtomicExpr::AO__atomic_compare_exchange:
1643 case AtomicExpr::AO__atomic_compare_exchange_n:
1644 Form = GNUCmpXchg;
1645 break;
1646 }
1647
1648 // Check we have the right number of arguments.
1649 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001650 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001651 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001652 << TheCall->getCallee()->getSourceRange();
1653 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001654 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1655 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001656 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001657 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001658 << TheCall->getCallee()->getSourceRange();
1659 return ExprError();
1660 }
1661
Richard Smithfeea8832012-04-12 05:08:17 +00001662 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001663 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001664 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1665 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1666 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001667 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001668 << Ptr->getType() << Ptr->getSourceRange();
1669 return ExprError();
1670 }
1671
Richard Smithfeea8832012-04-12 05:08:17 +00001672 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1673 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1674 QualType ValType = AtomTy; // 'C'
1675 if (IsC11) {
1676 if (!AtomTy->isAtomicType()) {
1677 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1678 << Ptr->getType() << Ptr->getSourceRange();
1679 return ExprError();
1680 }
Richard Smithe00921a2012-09-15 06:09:58 +00001681 if (AtomTy.isConstQualified()) {
1682 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1683 << Ptr->getType() << Ptr->getSourceRange();
1684 return ExprError();
1685 }
Richard Smithfeea8832012-04-12 05:08:17 +00001686 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001687 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1688 if (ValType.isConstQualified()) {
1689 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1690 << Ptr->getType() << Ptr->getSourceRange();
1691 return ExprError();
1692 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001693 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001694
Richard Smithfeea8832012-04-12 05:08:17 +00001695 // For an arithmetic operation, the implied arithmetic must be well-formed.
1696 if (Form == Arithmetic) {
1697 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1698 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1699 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1700 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1701 return ExprError();
1702 }
1703 if (!IsAddSub && !ValType->isIntegerType()) {
1704 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1705 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1706 return ExprError();
1707 }
David Majnemere85cff82015-01-28 05:48:06 +00001708 if (IsC11 && ValType->isPointerType() &&
1709 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1710 diag::err_incomplete_type)) {
1711 return ExprError();
1712 }
Richard Smithfeea8832012-04-12 05:08:17 +00001713 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1714 // For __atomic_*_n operations, the value type must be a scalar integral or
1715 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001716 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001717 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1718 return ExprError();
1719 }
1720
Eli Friedmanaa769812013-09-11 03:49:34 +00001721 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1722 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001723 // For GNU atomics, require a trivially-copyable type. This is not part of
1724 // the GNU atomics specification, but we enforce it for sanity.
1725 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001726 << Ptr->getType() << Ptr->getSourceRange();
1727 return ExprError();
1728 }
1729
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001730 switch (ValType.getObjCLifetime()) {
1731 case Qualifiers::OCL_None:
1732 case Qualifiers::OCL_ExplicitNone:
1733 // okay
1734 break;
1735
1736 case Qualifiers::OCL_Weak:
1737 case Qualifiers::OCL_Strong:
1738 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001739 // FIXME: Can this happen? By this point, ValType should be known
1740 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001741 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1742 << ValType << Ptr->getSourceRange();
1743 return ExprError();
1744 }
1745
David Majnemerc6eb6502015-06-03 00:26:35 +00001746 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1747 // volatile-ness of the pointee-type inject itself into the result or the
1748 // other operands.
1749 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001750 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001751 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001752 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001753 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001754 ResultType = Context.BoolTy;
1755
Richard Smithfeea8832012-04-12 05:08:17 +00001756 // The type of a parameter passed 'by value'. In the GNU atomics, such
1757 // arguments are actually passed as pointers.
1758 QualType ByValType = ValType; // 'CP'
1759 if (!IsC11 && !IsN)
1760 ByValType = Ptr->getType();
1761
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001762 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1763 // but not the second argument. We need to manually remove possible const
1764 // qualifiers.
1765
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001766 // The first argument --- the pointer --- has a fixed type; we
1767 // deduce the types of the rest of the arguments accordingly. Walk
1768 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001769 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001770 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001771 if (i < NumVals[Form] + 1) {
1772 switch (i) {
1773 case 1:
1774 // The second argument is the non-atomic operand. For arithmetic, this
1775 // is always passed by value, and for a compare_exchange it is always
1776 // passed by address. For the rest, GNU uses by-address and C11 uses
1777 // by-value.
1778 assert(Form != Load);
1779 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1780 Ty = ValType;
1781 else if (Form == Copy || Form == Xchg)
1782 Ty = ByValType;
1783 else if (Form == Arithmetic)
1784 Ty = Context.getPointerDiffType();
1785 else
1786 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1787 break;
1788 case 2:
1789 // The third argument to compare_exchange / GNU exchange is a
1790 // (pointer to a) desired value.
1791 Ty = ByValType;
1792 break;
1793 case 3:
1794 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1795 Ty = Context.BoolTy;
1796 break;
1797 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001798 } else {
1799 // The order(s) are always converted to int.
1800 Ty = Context.IntTy;
1801 }
Richard Smithfeea8832012-04-12 05:08:17 +00001802
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001803 InitializedEntity Entity =
1804 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001805 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001806 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1807 if (Arg.isInvalid())
1808 return true;
1809 TheCall->setArg(i, Arg.get());
1810 }
1811
Richard Smithfeea8832012-04-12 05:08:17 +00001812 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001813 SmallVector<Expr*, 5> SubExprs;
1814 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001815 switch (Form) {
1816 case Init:
1817 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001818 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001819 break;
1820 case Load:
1821 SubExprs.push_back(TheCall->getArg(1)); // Order
1822 break;
1823 case Copy:
1824 case Arithmetic:
1825 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001826 SubExprs.push_back(TheCall->getArg(2)); // Order
1827 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001828 break;
1829 case GNUXchg:
1830 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1831 SubExprs.push_back(TheCall->getArg(3)); // Order
1832 SubExprs.push_back(TheCall->getArg(1)); // Val1
1833 SubExprs.push_back(TheCall->getArg(2)); // Val2
1834 break;
1835 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001836 SubExprs.push_back(TheCall->getArg(3)); // Order
1837 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001838 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001839 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001840 break;
1841 case GNUCmpXchg:
1842 SubExprs.push_back(TheCall->getArg(4)); // Order
1843 SubExprs.push_back(TheCall->getArg(1)); // Val1
1844 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1845 SubExprs.push_back(TheCall->getArg(2)); // Val2
1846 SubExprs.push_back(TheCall->getArg(3)); // Weak
1847 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001848 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001849
1850 if (SubExprs.size() >= 2 && Form != Init) {
1851 llvm::APSInt Result(32);
1852 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1853 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001854 Diag(SubExprs[1]->getLocStart(),
1855 diag::warn_atomic_op_has_invalid_memory_order)
1856 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001857 }
1858
Fariborz Jahanian615de762013-05-28 17:37:39 +00001859 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1860 SubExprs, ResultType, Op,
1861 TheCall->getRParenLoc());
1862
1863 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1864 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1865 Context.AtomicUsesUnsupportedLibcall(AE))
1866 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1867 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001868
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001869 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001870}
1871
1872
John McCall29ad95b2011-08-27 01:09:30 +00001873/// checkBuiltinArgument - Given a call to a builtin function, perform
1874/// normal type-checking on the given argument, updating the call in
1875/// place. This is useful when a builtin function requires custom
1876/// type-checking for some of its arguments but not necessarily all of
1877/// them.
1878///
1879/// Returns true on error.
1880static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1881 FunctionDecl *Fn = E->getDirectCallee();
1882 assert(Fn && "builtin call without direct callee!");
1883
1884 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1885 InitializedEntity Entity =
1886 InitializedEntity::InitializeParameter(S.Context, Param);
1887
1888 ExprResult Arg = E->getArg(0);
1889 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1890 if (Arg.isInvalid())
1891 return true;
1892
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001893 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001894 return false;
1895}
1896
Chris Lattnerdc046542009-05-08 06:58:22 +00001897/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1898/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1899/// type of its first argument. The main ActOnCallExpr routines have already
1900/// promoted the types of arguments because all of these calls are prototyped as
1901/// void(...).
1902///
1903/// This function goes through and does final semantic checking for these
1904/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001905ExprResult
1906Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001907 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001908 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1909 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1910
1911 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001912 if (TheCall->getNumArgs() < 1) {
1913 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1914 << 0 << 1 << TheCall->getNumArgs()
1915 << TheCall->getCallee()->getSourceRange();
1916 return ExprError();
1917 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Chris Lattnerdc046542009-05-08 06:58:22 +00001919 // Inspect the first argument of the atomic builtin. This should always be
1920 // a pointer type, whose element is an integral scalar or pointer type.
1921 // Because it is a pointer type, we don't have to worry about any implicit
1922 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001923 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001924 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001925 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1926 if (FirstArgResult.isInvalid())
1927 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001928 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001929 TheCall->setArg(0, FirstArg);
1930
John McCall31168b02011-06-15 23:02:42 +00001931 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1932 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001933 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1934 << FirstArg->getType() << FirstArg->getSourceRange();
1935 return ExprError();
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
John McCall31168b02011-06-15 23:02:42 +00001938 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001939 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001940 !ValType->isBlockPointerType()) {
1941 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1942 << FirstArg->getType() << FirstArg->getSourceRange();
1943 return ExprError();
1944 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001945
John McCall31168b02011-06-15 23:02:42 +00001946 switch (ValType.getObjCLifetime()) {
1947 case Qualifiers::OCL_None:
1948 case Qualifiers::OCL_ExplicitNone:
1949 // okay
1950 break;
1951
1952 case Qualifiers::OCL_Weak:
1953 case Qualifiers::OCL_Strong:
1954 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001955 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001956 << ValType << FirstArg->getSourceRange();
1957 return ExprError();
1958 }
1959
John McCallb50451a2011-10-05 07:41:44 +00001960 // Strip any qualifiers off ValType.
1961 ValType = ValType.getUnqualifiedType();
1962
Chandler Carruth3973af72010-07-18 20:54:12 +00001963 // The majority of builtins return a value, but a few have special return
1964 // types, so allow them to override appropriately below.
1965 QualType ResultType = ValType;
1966
Chris Lattnerdc046542009-05-08 06:58:22 +00001967 // We need to figure out which concrete builtin this maps onto. For example,
1968 // __sync_fetch_and_add with a 2 byte object turns into
1969 // __sync_fetch_and_add_2.
1970#define BUILTIN_ROW(x) \
1971 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1972 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001973
Chris Lattnerdc046542009-05-08 06:58:22 +00001974 static const unsigned BuiltinIndices[][5] = {
1975 BUILTIN_ROW(__sync_fetch_and_add),
1976 BUILTIN_ROW(__sync_fetch_and_sub),
1977 BUILTIN_ROW(__sync_fetch_and_or),
1978 BUILTIN_ROW(__sync_fetch_and_and),
1979 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001980 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattnerdc046542009-05-08 06:58:22 +00001982 BUILTIN_ROW(__sync_add_and_fetch),
1983 BUILTIN_ROW(__sync_sub_and_fetch),
1984 BUILTIN_ROW(__sync_and_and_fetch),
1985 BUILTIN_ROW(__sync_or_and_fetch),
1986 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001987 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001988
Chris Lattnerdc046542009-05-08 06:58:22 +00001989 BUILTIN_ROW(__sync_val_compare_and_swap),
1990 BUILTIN_ROW(__sync_bool_compare_and_swap),
1991 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001992 BUILTIN_ROW(__sync_lock_release),
1993 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001994 };
Mike Stump11289f42009-09-09 15:08:12 +00001995#undef BUILTIN_ROW
1996
Chris Lattnerdc046542009-05-08 06:58:22 +00001997 // Determine the index of the size.
1998 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001999 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002000 case 1: SizeIndex = 0; break;
2001 case 2: SizeIndex = 1; break;
2002 case 4: SizeIndex = 2; break;
2003 case 8: SizeIndex = 3; break;
2004 case 16: SizeIndex = 4; break;
2005 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002006 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2007 << FirstArg->getType() << FirstArg->getSourceRange();
2008 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattnerdc046542009-05-08 06:58:22 +00002011 // Each of these builtins has one pointer argument, followed by some number of
2012 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2013 // that we ignore. Find out which row of BuiltinIndices to read from as well
2014 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002015 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002016 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002017 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002018 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002019 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002020 case Builtin::BI__sync_fetch_and_add:
2021 case Builtin::BI__sync_fetch_and_add_1:
2022 case Builtin::BI__sync_fetch_and_add_2:
2023 case Builtin::BI__sync_fetch_and_add_4:
2024 case Builtin::BI__sync_fetch_and_add_8:
2025 case Builtin::BI__sync_fetch_and_add_16:
2026 BuiltinIndex = 0;
2027 break;
2028
2029 case Builtin::BI__sync_fetch_and_sub:
2030 case Builtin::BI__sync_fetch_and_sub_1:
2031 case Builtin::BI__sync_fetch_and_sub_2:
2032 case Builtin::BI__sync_fetch_and_sub_4:
2033 case Builtin::BI__sync_fetch_and_sub_8:
2034 case Builtin::BI__sync_fetch_and_sub_16:
2035 BuiltinIndex = 1;
2036 break;
2037
2038 case Builtin::BI__sync_fetch_and_or:
2039 case Builtin::BI__sync_fetch_and_or_1:
2040 case Builtin::BI__sync_fetch_and_or_2:
2041 case Builtin::BI__sync_fetch_and_or_4:
2042 case Builtin::BI__sync_fetch_and_or_8:
2043 case Builtin::BI__sync_fetch_and_or_16:
2044 BuiltinIndex = 2;
2045 break;
2046
2047 case Builtin::BI__sync_fetch_and_and:
2048 case Builtin::BI__sync_fetch_and_and_1:
2049 case Builtin::BI__sync_fetch_and_and_2:
2050 case Builtin::BI__sync_fetch_and_and_4:
2051 case Builtin::BI__sync_fetch_and_and_8:
2052 case Builtin::BI__sync_fetch_and_and_16:
2053 BuiltinIndex = 3;
2054 break;
Mike Stump11289f42009-09-09 15:08:12 +00002055
Douglas Gregor73722482011-11-28 16:30:08 +00002056 case Builtin::BI__sync_fetch_and_xor:
2057 case Builtin::BI__sync_fetch_and_xor_1:
2058 case Builtin::BI__sync_fetch_and_xor_2:
2059 case Builtin::BI__sync_fetch_and_xor_4:
2060 case Builtin::BI__sync_fetch_and_xor_8:
2061 case Builtin::BI__sync_fetch_and_xor_16:
2062 BuiltinIndex = 4;
2063 break;
2064
Hal Finkeld2208b52014-10-02 20:53:50 +00002065 case Builtin::BI__sync_fetch_and_nand:
2066 case Builtin::BI__sync_fetch_and_nand_1:
2067 case Builtin::BI__sync_fetch_and_nand_2:
2068 case Builtin::BI__sync_fetch_and_nand_4:
2069 case Builtin::BI__sync_fetch_and_nand_8:
2070 case Builtin::BI__sync_fetch_and_nand_16:
2071 BuiltinIndex = 5;
2072 WarnAboutSemanticsChange = true;
2073 break;
2074
Douglas Gregor73722482011-11-28 16:30:08 +00002075 case Builtin::BI__sync_add_and_fetch:
2076 case Builtin::BI__sync_add_and_fetch_1:
2077 case Builtin::BI__sync_add_and_fetch_2:
2078 case Builtin::BI__sync_add_and_fetch_4:
2079 case Builtin::BI__sync_add_and_fetch_8:
2080 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002081 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002082 break;
2083
2084 case Builtin::BI__sync_sub_and_fetch:
2085 case Builtin::BI__sync_sub_and_fetch_1:
2086 case Builtin::BI__sync_sub_and_fetch_2:
2087 case Builtin::BI__sync_sub_and_fetch_4:
2088 case Builtin::BI__sync_sub_and_fetch_8:
2089 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002090 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002091 break;
2092
2093 case Builtin::BI__sync_and_and_fetch:
2094 case Builtin::BI__sync_and_and_fetch_1:
2095 case Builtin::BI__sync_and_and_fetch_2:
2096 case Builtin::BI__sync_and_and_fetch_4:
2097 case Builtin::BI__sync_and_and_fetch_8:
2098 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002099 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002100 break;
2101
2102 case Builtin::BI__sync_or_and_fetch:
2103 case Builtin::BI__sync_or_and_fetch_1:
2104 case Builtin::BI__sync_or_and_fetch_2:
2105 case Builtin::BI__sync_or_and_fetch_4:
2106 case Builtin::BI__sync_or_and_fetch_8:
2107 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002108 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002109 break;
2110
2111 case Builtin::BI__sync_xor_and_fetch:
2112 case Builtin::BI__sync_xor_and_fetch_1:
2113 case Builtin::BI__sync_xor_and_fetch_2:
2114 case Builtin::BI__sync_xor_and_fetch_4:
2115 case Builtin::BI__sync_xor_and_fetch_8:
2116 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002117 BuiltinIndex = 10;
2118 break;
2119
2120 case Builtin::BI__sync_nand_and_fetch:
2121 case Builtin::BI__sync_nand_and_fetch_1:
2122 case Builtin::BI__sync_nand_and_fetch_2:
2123 case Builtin::BI__sync_nand_and_fetch_4:
2124 case Builtin::BI__sync_nand_and_fetch_8:
2125 case Builtin::BI__sync_nand_and_fetch_16:
2126 BuiltinIndex = 11;
2127 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002128 break;
Mike Stump11289f42009-09-09 15:08:12 +00002129
Chris Lattnerdc046542009-05-08 06:58:22 +00002130 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002131 case Builtin::BI__sync_val_compare_and_swap_1:
2132 case Builtin::BI__sync_val_compare_and_swap_2:
2133 case Builtin::BI__sync_val_compare_and_swap_4:
2134 case Builtin::BI__sync_val_compare_and_swap_8:
2135 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002136 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002137 NumFixed = 2;
2138 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002139
Chris Lattnerdc046542009-05-08 06:58:22 +00002140 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002141 case Builtin::BI__sync_bool_compare_and_swap_1:
2142 case Builtin::BI__sync_bool_compare_and_swap_2:
2143 case Builtin::BI__sync_bool_compare_and_swap_4:
2144 case Builtin::BI__sync_bool_compare_and_swap_8:
2145 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002146 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002147 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002148 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002149 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002150
2151 case Builtin::BI__sync_lock_test_and_set:
2152 case Builtin::BI__sync_lock_test_and_set_1:
2153 case Builtin::BI__sync_lock_test_and_set_2:
2154 case Builtin::BI__sync_lock_test_and_set_4:
2155 case Builtin::BI__sync_lock_test_and_set_8:
2156 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002157 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002158 break;
2159
Chris Lattnerdc046542009-05-08 06:58:22 +00002160 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002161 case Builtin::BI__sync_lock_release_1:
2162 case Builtin::BI__sync_lock_release_2:
2163 case Builtin::BI__sync_lock_release_4:
2164 case Builtin::BI__sync_lock_release_8:
2165 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002166 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002167 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002168 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002169 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002170
2171 case Builtin::BI__sync_swap:
2172 case Builtin::BI__sync_swap_1:
2173 case Builtin::BI__sync_swap_2:
2174 case Builtin::BI__sync_swap_4:
2175 case Builtin::BI__sync_swap_8:
2176 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002177 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002178 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Chris Lattnerdc046542009-05-08 06:58:22 +00002181 // Now that we know how many fixed arguments we expect, first check that we
2182 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002183 if (TheCall->getNumArgs() < 1+NumFixed) {
2184 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2185 << 0 << 1+NumFixed << TheCall->getNumArgs()
2186 << TheCall->getCallee()->getSourceRange();
2187 return ExprError();
2188 }
Mike Stump11289f42009-09-09 15:08:12 +00002189
Hal Finkeld2208b52014-10-02 20:53:50 +00002190 if (WarnAboutSemanticsChange) {
2191 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2192 << TheCall->getCallee()->getSourceRange();
2193 }
2194
Chris Lattner5b9241b2009-05-08 15:36:58 +00002195 // Get the decl for the concrete builtin from this, we can tell what the
2196 // concrete integer type we should convert to is.
2197 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002198 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002199 FunctionDecl *NewBuiltinDecl;
2200 if (NewBuiltinID == BuiltinID)
2201 NewBuiltinDecl = FDecl;
2202 else {
2203 // Perform builtin lookup to avoid redeclaring it.
2204 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2205 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2206 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2207 assert(Res.getFoundDecl());
2208 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002210 return ExprError();
2211 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002212
John McCallcf142162010-08-07 06:22:56 +00002213 // The first argument --- the pointer --- has a fixed type; we
2214 // deduce the types of the rest of the arguments accordingly. Walk
2215 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002216 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002217 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002218
Chris Lattnerdc046542009-05-08 06:58:22 +00002219 // GCC does an implicit conversion to the pointer or integer ValType. This
2220 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002221 // Initialize the argument.
2222 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2223 ValType, /*consume*/ false);
2224 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002225 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002226 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002227
Chris Lattnerdc046542009-05-08 06:58:22 +00002228 // Okay, we have something that *can* be converted to the right type. Check
2229 // to see if there is a potentially weird extension going on here. This can
2230 // happen when you do an atomic operation on something like an char* and
2231 // pass in 42. The 42 gets converted to char. This is even more strange
2232 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002233 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002234 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002235 }
Mike Stump11289f42009-09-09 15:08:12 +00002236
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002237 ASTContext& Context = this->getASTContext();
2238
2239 // Create a new DeclRefExpr to refer to the new decl.
2240 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2241 Context,
2242 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002243 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002244 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002245 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002246 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002247 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002248 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002249
Chris Lattnerdc046542009-05-08 06:58:22 +00002250 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002251 // FIXME: This loses syntactic information.
2252 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2253 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2254 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002255 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002256
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002257 // Change the result type of the call to match the original value type. This
2258 // is arbitrary, but the codegen for these builtins ins design to handle it
2259 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002260 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002261
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002262 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002263}
2264
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002265/// SemaBuiltinNontemporalOverloaded - We have a call to
2266/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2267/// overloaded function based on the pointer type of its last argument.
2268///
2269/// This function goes through and does final semantic checking for these
2270/// builtins.
2271ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2272 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2273 DeclRefExpr *DRE =
2274 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2275 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2276 unsigned BuiltinID = FDecl->getBuiltinID();
2277 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2278 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2279 "Unexpected nontemporal load/store builtin!");
2280 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2281 unsigned numArgs = isStore ? 2 : 1;
2282
2283 // Ensure that we have the proper number of arguments.
2284 if (checkArgCount(*this, TheCall, numArgs))
2285 return ExprError();
2286
2287 // Inspect the last argument of the nontemporal builtin. This should always
2288 // be a pointer type, from which we imply the type of the memory access.
2289 // Because it is a pointer type, we don't have to worry about any implicit
2290 // casts here.
2291 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2292 ExprResult PointerArgResult =
2293 DefaultFunctionArrayLvalueConversion(PointerArg);
2294
2295 if (PointerArgResult.isInvalid())
2296 return ExprError();
2297 PointerArg = PointerArgResult.get();
2298 TheCall->setArg(numArgs - 1, PointerArg);
2299
2300 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2301 if (!pointerType) {
2302 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2303 << PointerArg->getType() << PointerArg->getSourceRange();
2304 return ExprError();
2305 }
2306
2307 QualType ValType = pointerType->getPointeeType();
2308
2309 // Strip any qualifiers off ValType.
2310 ValType = ValType.getUnqualifiedType();
2311 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2312 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2313 !ValType->isVectorType()) {
2314 Diag(DRE->getLocStart(),
2315 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2316 << PointerArg->getType() << PointerArg->getSourceRange();
2317 return ExprError();
2318 }
2319
2320 if (!isStore) {
2321 TheCall->setType(ValType);
2322 return TheCallResult;
2323 }
2324
2325 ExprResult ValArg = TheCall->getArg(0);
2326 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2327 Context, ValType, /*consume*/ false);
2328 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2329 if (ValArg.isInvalid())
2330 return ExprError();
2331
2332 TheCall->setArg(0, ValArg.get());
2333 TheCall->setType(Context.VoidTy);
2334 return TheCallResult;
2335}
2336
Chris Lattner6436fb62009-02-18 06:01:06 +00002337/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002338/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002339/// Note: It might also make sense to do the UTF-16 conversion here (would
2340/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002341bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002342 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002343 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2344
Douglas Gregorfb65e592011-07-27 05:40:30 +00002345 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002346 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2347 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002348 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002349 }
Mike Stump11289f42009-09-09 15:08:12 +00002350
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002351 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002352 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002353 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002354 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002355 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002356 UTF16 *ToPtr = &ToBuf[0];
2357
2358 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2359 &ToPtr, ToPtr + NumBytes,
2360 strictConversion);
2361 // Check for conversion failure.
2362 if (Result != conversionOK)
2363 Diag(Arg->getLocStart(),
2364 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2365 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002366 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002367}
2368
Charles Davisc7d5c942015-09-17 20:55:33 +00002369/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2370/// for validity. Emit an error and return true on failure; return false
2371/// on success.
2372bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002373 Expr *Fn = TheCall->getCallee();
2374 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002375 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002376 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002377 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2378 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002379 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002380 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002381 return true;
2382 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002383
2384 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002385 return Diag(TheCall->getLocEnd(),
2386 diag::err_typecheck_call_too_few_args_at_least)
2387 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002388 }
2389
John McCall29ad95b2011-08-27 01:09:30 +00002390 // Type-check the first argument normally.
2391 if (checkBuiltinArgument(*this, TheCall, 0))
2392 return true;
2393
Chris Lattnere202e6a2007-12-20 00:05:45 +00002394 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002395 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002396 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002397 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002398 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002399 else if (FunctionDecl *FD = getCurFunctionDecl())
2400 isVariadic = FD->isVariadic();
2401 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002402 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002403
Chris Lattnere202e6a2007-12-20 00:05:45 +00002404 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002405 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2406 return true;
2407 }
Mike Stump11289f42009-09-09 15:08:12 +00002408
Chris Lattner43be2e62007-12-19 23:59:04 +00002409 // Verify that the second argument to the builtin is the last argument of the
2410 // current function or method.
2411 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002412 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002413
Nico Weber9eea7642013-05-24 23:31:57 +00002414 // These are valid if SecondArgIsLastNamedArgument is false after the next
2415 // block.
2416 QualType Type;
2417 SourceLocation ParamLoc;
2418
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002419 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2420 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002421 // FIXME: This isn't correct for methods (results in bogus warning).
2422 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002423 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002424 if (CurBlock)
2425 LastArg = *(CurBlock->TheDecl->param_end()-1);
2426 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002427 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002428 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002429 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002430 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002431
2432 Type = PV->getType();
2433 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002434 }
2435 }
Mike Stump11289f42009-09-09 15:08:12 +00002436
Chris Lattner43be2e62007-12-19 23:59:04 +00002437 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002438 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002439 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002440 else if (Type->isReferenceType()) {
2441 Diag(Arg->getLocStart(),
2442 diag::warn_va_start_of_reference_type_is_undefined);
2443 Diag(ParamLoc, diag::note_parameter_type) << Type;
2444 }
2445
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002446 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002447 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002448}
Chris Lattner43be2e62007-12-19 23:59:04 +00002449
Charles Davisc7d5c942015-09-17 20:55:33 +00002450/// Check the arguments to '__builtin_va_start' for validity, and that
2451/// it was called from a function of the native ABI.
2452/// Emit an error and return true on failure; return false on success.
2453bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2454 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2455 // On x64 Windows, don't allow this in System V ABI functions.
2456 // (Yes, that means there's no corresponding way to support variadic
2457 // System V ABI functions on Windows.)
2458 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2459 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2460 clang::CallingConv CC = CC_C;
2461 if (const FunctionDecl *FD = getCurFunctionDecl())
2462 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2463 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2464 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2465 return Diag(TheCall->getCallee()->getLocStart(),
2466 diag::err_va_start_used_in_wrong_abi_function)
2467 << (OS != llvm::Triple::Win32);
2468 }
2469 return SemaBuiltinVAStartImpl(TheCall);
2470}
2471
2472/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2473/// it was called from a Win64 ABI function.
2474/// Emit an error and return true on failure; return false on success.
2475bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2476 // This only makes sense for x86-64.
2477 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2478 Expr *Callee = TheCall->getCallee();
2479 if (TT.getArch() != llvm::Triple::x86_64)
2480 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2481 // Don't allow this in System V ABI functions.
2482 clang::CallingConv CC = CC_C;
2483 if (const FunctionDecl *FD = getCurFunctionDecl())
2484 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2485 if (CC == CC_X86_64SysV ||
2486 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2487 return Diag(Callee->getLocStart(),
2488 diag::err_ms_va_start_used_in_sysv_function);
2489 return SemaBuiltinVAStartImpl(TheCall);
2490}
2491
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002492bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2493 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2494 // const char *named_addr);
2495
2496 Expr *Func = Call->getCallee();
2497
2498 if (Call->getNumArgs() < 3)
2499 return Diag(Call->getLocEnd(),
2500 diag::err_typecheck_call_too_few_args_at_least)
2501 << 0 /*function call*/ << 3 << Call->getNumArgs();
2502
2503 // Determine whether the current function is variadic or not.
2504 bool IsVariadic;
2505 if (BlockScopeInfo *CurBlock = getCurBlock())
2506 IsVariadic = CurBlock->TheDecl->isVariadic();
2507 else if (FunctionDecl *FD = getCurFunctionDecl())
2508 IsVariadic = FD->isVariadic();
2509 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2510 IsVariadic = MD->isVariadic();
2511 else
2512 llvm_unreachable("unexpected statement type");
2513
2514 if (!IsVariadic) {
2515 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2516 return true;
2517 }
2518
2519 // Type-check the first argument normally.
2520 if (checkBuiltinArgument(*this, Call, 0))
2521 return true;
2522
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002523 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002524 unsigned ArgNo;
2525 QualType Type;
2526 } ArgumentTypes[] = {
2527 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2528 { 2, Context.getSizeType() },
2529 };
2530
2531 for (const auto &AT : ArgumentTypes) {
2532 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2533 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2534 continue;
2535 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2536 << Arg->getType() << AT.Type << 1 /* different class */
2537 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2538 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2539 }
2540
2541 return false;
2542}
2543
Chris Lattner2da14fb2007-12-20 00:26:33 +00002544/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2545/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002546bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2547 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002548 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002549 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002550 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002551 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002552 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002553 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002554 << SourceRange(TheCall->getArg(2)->getLocStart(),
2555 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002556
John Wiegley01296292011-04-08 18:41:53 +00002557 ExprResult OrigArg0 = TheCall->getArg(0);
2558 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002559
Chris Lattner2da14fb2007-12-20 00:26:33 +00002560 // Do standard promotions between the two arguments, returning their common
2561 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002562 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002563 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2564 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002565
2566 // Make sure any conversions are pushed back into the call; this is
2567 // type safe since unordered compare builtins are declared as "_Bool
2568 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002569 TheCall->setArg(0, OrigArg0.get());
2570 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002571
John Wiegley01296292011-04-08 18:41:53 +00002572 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002573 return false;
2574
Chris Lattner2da14fb2007-12-20 00:26:33 +00002575 // If the common type isn't a real floating type, then the arguments were
2576 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002577 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002578 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002579 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002580 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2581 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002582
Chris Lattner2da14fb2007-12-20 00:26:33 +00002583 return false;
2584}
2585
Benjamin Kramer634fc102010-02-15 22:42:31 +00002586/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2587/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002588/// to check everything. We expect the last argument to be a floating point
2589/// value.
2590bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2591 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002592 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002593 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002594 if (TheCall->getNumArgs() > NumArgs)
2595 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002596 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002597 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002598 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002599 (*(TheCall->arg_end()-1))->getLocEnd());
2600
Benjamin Kramer64aae502010-02-16 10:07:31 +00002601 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002602
Eli Friedman7e4faac2009-08-31 20:06:00 +00002603 if (OrigArg->isTypeDependent())
2604 return false;
2605
Chris Lattner68784ef2010-05-06 05:50:07 +00002606 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002607 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002608 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002609 diag::err_typecheck_call_invalid_unary_fp)
2610 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002611
Chris Lattner68784ef2010-05-06 05:50:07 +00002612 // If this is an implicit conversion from float -> double, remove it.
2613 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2614 Expr *CastArg = Cast->getSubExpr();
2615 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2616 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2617 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002618 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002619 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002620 }
2621 }
2622
Eli Friedman7e4faac2009-08-31 20:06:00 +00002623 return false;
2624}
2625
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002626/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2627// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002628ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002629 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002630 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002631 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002632 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2633 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002634
Nate Begemana0110022010-06-08 00:16:34 +00002635 // Determine which of the following types of shufflevector we're checking:
2636 // 1) unary, vector mask: (lhs, mask)
2637 // 2) binary, vector mask: (lhs, rhs, mask)
2638 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2639 QualType resType = TheCall->getArg(0)->getType();
2640 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002641
Douglas Gregorc25f7662009-05-19 22:10:17 +00002642 if (!TheCall->getArg(0)->isTypeDependent() &&
2643 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002644 QualType LHSType = TheCall->getArg(0)->getType();
2645 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002646
Craig Topperbaca3892013-07-29 06:47:04 +00002647 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2648 return ExprError(Diag(TheCall->getLocStart(),
2649 diag::err_shufflevector_non_vector)
2650 << SourceRange(TheCall->getArg(0)->getLocStart(),
2651 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002652
Nate Begemana0110022010-06-08 00:16:34 +00002653 numElements = LHSType->getAs<VectorType>()->getNumElements();
2654 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002655
Nate Begemana0110022010-06-08 00:16:34 +00002656 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2657 // with mask. If so, verify that RHS is an integer vector type with the
2658 // same number of elts as lhs.
2659 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002660 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002661 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002662 return ExprError(Diag(TheCall->getLocStart(),
2663 diag::err_shufflevector_incompatible_vector)
2664 << SourceRange(TheCall->getArg(1)->getLocStart(),
2665 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002666 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002667 return ExprError(Diag(TheCall->getLocStart(),
2668 diag::err_shufflevector_incompatible_vector)
2669 << SourceRange(TheCall->getArg(0)->getLocStart(),
2670 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002671 } else if (numElements != numResElements) {
2672 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002673 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002674 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002675 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002676 }
2677
2678 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002679 if (TheCall->getArg(i)->isTypeDependent() ||
2680 TheCall->getArg(i)->isValueDependent())
2681 continue;
2682
Nate Begemana0110022010-06-08 00:16:34 +00002683 llvm::APSInt Result(32);
2684 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2685 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002686 diag::err_shufflevector_nonconstant_argument)
2687 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002688
Craig Topper50ad5b72013-08-03 17:40:38 +00002689 // Allow -1 which will be translated to undef in the IR.
2690 if (Result.isSigned() && Result.isAllOnesValue())
2691 continue;
2692
Chris Lattner7ab824e2008-08-10 02:05:13 +00002693 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002694 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002695 diag::err_shufflevector_argument_too_large)
2696 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002697 }
2698
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002699 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002700
Chris Lattner7ab824e2008-08-10 02:05:13 +00002701 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002702 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002703 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002704 }
2705
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002706 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2707 TheCall->getCallee()->getLocStart(),
2708 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002709}
Chris Lattner43be2e62007-12-19 23:59:04 +00002710
Hal Finkelc4d7c822013-09-18 03:29:45 +00002711/// SemaConvertVectorExpr - Handle __builtin_convertvector
2712ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2713 SourceLocation BuiltinLoc,
2714 SourceLocation RParenLoc) {
2715 ExprValueKind VK = VK_RValue;
2716 ExprObjectKind OK = OK_Ordinary;
2717 QualType DstTy = TInfo->getType();
2718 QualType SrcTy = E->getType();
2719
2720 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2721 return ExprError(Diag(BuiltinLoc,
2722 diag::err_convertvector_non_vector)
2723 << E->getSourceRange());
2724 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2725 return ExprError(Diag(BuiltinLoc,
2726 diag::err_convertvector_non_vector_type));
2727
2728 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2729 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2730 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2731 if (SrcElts != DstElts)
2732 return ExprError(Diag(BuiltinLoc,
2733 diag::err_convertvector_incompatible_vector)
2734 << E->getSourceRange());
2735 }
2736
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002737 return new (Context)
2738 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002739}
2740
Daniel Dunbarb7257262008-07-21 22:59:13 +00002741/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2742// This is declared to take (const void*, ...) and can take two
2743// optional constant int args.
2744bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002745 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002746
Chris Lattner3b054132008-11-19 05:08:23 +00002747 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002748 return Diag(TheCall->getLocEnd(),
2749 diag::err_typecheck_call_too_many_args_at_most)
2750 << 0 /*function call*/ << 3 << NumArgs
2751 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002752
2753 // Argument 0 is checked for us and the remaining arguments must be
2754 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002755 for (unsigned i = 1; i != NumArgs; ++i)
2756 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002757 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002758
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002759 return false;
2760}
2761
Hal Finkelf0417332014-07-17 14:25:55 +00002762/// SemaBuiltinAssume - Handle __assume (MS Extension).
2763// __assume does not evaluate its arguments, and should warn if its argument
2764// has side effects.
2765bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2766 Expr *Arg = TheCall->getArg(0);
2767 if (Arg->isInstantiationDependent()) return false;
2768
2769 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002770 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002771 << Arg->getSourceRange()
2772 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2773
2774 return false;
2775}
2776
2777/// Handle __builtin_assume_aligned. This is declared
2778/// as (const void*, size_t, ...) and can take one optional constant int arg.
2779bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2780 unsigned NumArgs = TheCall->getNumArgs();
2781
2782 if (NumArgs > 3)
2783 return Diag(TheCall->getLocEnd(),
2784 diag::err_typecheck_call_too_many_args_at_most)
2785 << 0 /*function call*/ << 3 << NumArgs
2786 << TheCall->getSourceRange();
2787
2788 // The alignment must be a constant integer.
2789 Expr *Arg = TheCall->getArg(1);
2790
2791 // We can't check the value of a dependent argument.
2792 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2793 llvm::APSInt Result;
2794 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2795 return true;
2796
2797 if (!Result.isPowerOf2())
2798 return Diag(TheCall->getLocStart(),
2799 diag::err_alignment_not_power_of_two)
2800 << Arg->getSourceRange();
2801 }
2802
2803 if (NumArgs > 2) {
2804 ExprResult Arg(TheCall->getArg(2));
2805 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2806 Context.getSizeType(), false);
2807 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2808 if (Arg.isInvalid()) return true;
2809 TheCall->setArg(2, Arg.get());
2810 }
Hal Finkelf0417332014-07-17 14:25:55 +00002811
2812 return false;
2813}
2814
Eric Christopher8d0c6212010-04-17 02:26:23 +00002815/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2816/// TheCall is a constant expression.
2817bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2818 llvm::APSInt &Result) {
2819 Expr *Arg = TheCall->getArg(ArgNum);
2820 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2821 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2822
2823 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2824
2825 if (!Arg->isIntegerConstantExpr(Result, Context))
2826 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002827 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002828
Chris Lattnerd545ad12009-09-23 06:06:36 +00002829 return false;
2830}
2831
Richard Sandiford28940af2014-04-16 08:47:51 +00002832/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2833/// TheCall is a constant expression in the range [Low, High].
2834bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2835 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002836 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002837
2838 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002839 Expr *Arg = TheCall->getArg(ArgNum);
2840 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002841 return false;
2842
Eric Christopher8d0c6212010-04-17 02:26:23 +00002843 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002844 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002845 return true;
2846
Richard Sandiford28940af2014-04-16 08:47:51 +00002847 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002848 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002849 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002850
2851 return false;
2852}
2853
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002854/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2855/// TheCall is an ARM/AArch64 special register string literal.
2856bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2857 int ArgNum, unsigned ExpectedFieldNum,
2858 bool AllowName) {
2859 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2860 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2861 BuiltinID == ARM::BI__builtin_arm_rsr ||
2862 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2863 BuiltinID == ARM::BI__builtin_arm_wsr ||
2864 BuiltinID == ARM::BI__builtin_arm_wsrp;
2865 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2866 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2867 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2868 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2869 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2870 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2871 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2872
2873 // We can't check the value of a dependent argument.
2874 Expr *Arg = TheCall->getArg(ArgNum);
2875 if (Arg->isTypeDependent() || Arg->isValueDependent())
2876 return false;
2877
2878 // Check if the argument is a string literal.
2879 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2880 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2881 << Arg->getSourceRange();
2882
2883 // Check the type of special register given.
2884 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2885 SmallVector<StringRef, 6> Fields;
2886 Reg.split(Fields, ":");
2887
2888 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2889 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2890 << Arg->getSourceRange();
2891
2892 // If the string is the name of a register then we cannot check that it is
2893 // valid here but if the string is of one the forms described in ACLE then we
2894 // can check that the supplied fields are integers and within the valid
2895 // ranges.
2896 if (Fields.size() > 1) {
2897 bool FiveFields = Fields.size() == 5;
2898
2899 bool ValidString = true;
2900 if (IsARMBuiltin) {
2901 ValidString &= Fields[0].startswith_lower("cp") ||
2902 Fields[0].startswith_lower("p");
2903 if (ValidString)
2904 Fields[0] =
2905 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2906
2907 ValidString &= Fields[2].startswith_lower("c");
2908 if (ValidString)
2909 Fields[2] = Fields[2].drop_front(1);
2910
2911 if (FiveFields) {
2912 ValidString &= Fields[3].startswith_lower("c");
2913 if (ValidString)
2914 Fields[3] = Fields[3].drop_front(1);
2915 }
2916 }
2917
2918 SmallVector<int, 5> Ranges;
2919 if (FiveFields)
2920 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2921 else
2922 Ranges.append({15, 7, 15});
2923
2924 for (unsigned i=0; i<Fields.size(); ++i) {
2925 int IntField;
2926 ValidString &= !Fields[i].getAsInteger(10, IntField);
2927 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2928 }
2929
2930 if (!ValidString)
2931 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2932 << Arg->getSourceRange();
2933
2934 } else if (IsAArch64Builtin && Fields.size() == 1) {
2935 // If the register name is one of those that appear in the condition below
2936 // and the special register builtin being used is one of the write builtins,
2937 // then we require that the argument provided for writing to the register
2938 // is an integer constant expression. This is because it will be lowered to
2939 // an MSR (immediate) instruction, so we need to know the immediate at
2940 // compile time.
2941 if (TheCall->getNumArgs() != 2)
2942 return false;
2943
2944 std::string RegLower = Reg.lower();
2945 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2946 RegLower != "pan" && RegLower != "uao")
2947 return false;
2948
2949 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2950 }
2951
2952 return false;
2953}
2954
Eric Christopherd9832702015-06-29 21:00:05 +00002955/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
2956/// This checks that the target supports __builtin_cpu_supports and
2957/// that the string argument is constant and valid.
2958bool Sema::SemaBuiltinCpuSupports(CallExpr *TheCall) {
2959 Expr *Arg = TheCall->getArg(0);
2960
2961 // Check if the argument is a string literal.
2962 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2963 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2964 << Arg->getSourceRange();
2965
2966 // Check the contents of the string.
2967 StringRef Feature =
2968 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2969 if (!Context.getTargetInfo().validateCpuSupports(Feature))
2970 return Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
2971 << Arg->getSourceRange();
2972 return false;
2973}
2974
Eli Friedmanc97d0142009-05-03 06:04:26 +00002975/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002976/// This checks that the target supports __builtin_longjmp and
2977/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002978bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002979 if (!Context.getTargetInfo().hasSjLjLowering())
2980 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2981 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2982
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002983 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002984 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002985
Eric Christopher8d0c6212010-04-17 02:26:23 +00002986 // TODO: This is less than ideal. Overload this to take a value.
2987 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2988 return true;
2989
2990 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002991 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2992 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2993
2994 return false;
2995}
2996
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002997
2998/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2999/// This checks that the target supports __builtin_setjmp.
3000bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3001 if (!Context.getTargetInfo().hasSjLjLowering())
3002 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3003 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3004 return false;
3005}
3006
Richard Smithd7293d72013-08-05 18:49:43 +00003007namespace {
3008enum StringLiteralCheckType {
3009 SLCT_NotALiteral,
3010 SLCT_UncheckedLiteral,
3011 SLCT_CheckedLiteral
3012};
3013}
3014
Richard Smith55ce3522012-06-25 20:30:08 +00003015// Determine if an expression is a string literal or constant string.
3016// If this function returns false on the arguments to a function expecting a
3017// format string, we will usually need to emit a warning.
3018// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003019static StringLiteralCheckType
3020checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3021 bool HasVAListArg, unsigned format_idx,
3022 unsigned firstDataArg, Sema::FormatStringType Type,
3023 Sema::VariadicCallType CallType, bool InFunctionCall,
3024 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003025 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003026 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003027 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003028
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003029 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003030
Richard Smithd7293d72013-08-05 18:49:43 +00003031 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003032 // Technically -Wformat-nonliteral does not warn about this case.
3033 // The behavior of printf and friends in this case is implementation
3034 // dependent. Ideally if the format string cannot be null then
3035 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003036 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003037
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003038 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003039 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003040 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003041 // The expression is a literal if both sub-expressions were, and it was
3042 // completely checked only if both sub-expressions were checked.
3043 const AbstractConditionalOperator *C =
3044 cast<AbstractConditionalOperator>(E);
3045 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003046 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003047 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003048 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003049 if (Left == SLCT_NotALiteral)
3050 return SLCT_NotALiteral;
3051 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003052 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003053 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003054 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003055 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003056 }
3057
3058 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003059 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3060 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003061 }
3062
John McCallc07a0c72011-02-17 10:25:35 +00003063 case Stmt::OpaqueValueExprClass:
3064 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3065 E = src;
3066 goto tryAgain;
3067 }
Richard Smith55ce3522012-06-25 20:30:08 +00003068 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003069
Ted Kremeneka8890832011-02-24 23:03:04 +00003070 case Stmt::PredefinedExprClass:
3071 // While __func__, etc., are technically not string literals, they
3072 // cannot contain format specifiers and thus are not a security
3073 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003074 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003075
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003076 case Stmt::DeclRefExprClass: {
3077 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003079 // As an exception, do not flag errors for variables binding to
3080 // const string literals.
3081 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3082 bool isConstant = false;
3083 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003084
Richard Smithd7293d72013-08-05 18:49:43 +00003085 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3086 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003087 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003088 isConstant = T.isConstant(S.Context) &&
3089 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003090 } else if (T->isObjCObjectPointerType()) {
3091 // In ObjC, there is usually no "const ObjectPointer" type,
3092 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003093 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003096 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003097 if (const Expr *Init = VD->getAnyInitializer()) {
3098 // Look through initializers like const char c[] = { "foo" }
3099 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3100 if (InitList->isStringLiteralInit())
3101 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3102 }
Richard Smithd7293d72013-08-05 18:49:43 +00003103 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003104 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003105 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003106 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003107 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003108 }
Mike Stump11289f42009-09-09 15:08:12 +00003109
Anders Carlssonb012ca92009-06-28 19:55:58 +00003110 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3111 // special check to see if the format string is a function parameter
3112 // of the function calling the printf function. If the function
3113 // has an attribute indicating it is a printf-like function, then we
3114 // should suppress warnings concerning non-literals being used in a call
3115 // to a vprintf function. For example:
3116 //
3117 // void
3118 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3119 // va_list ap;
3120 // va_start(ap, fmt);
3121 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3122 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003123 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003124 if (HasVAListArg) {
3125 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3126 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3127 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003128 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003129 // adjust for implicit parameter
3130 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3131 if (MD->isInstance())
3132 ++PVIndex;
3133 // We also check if the formats are compatible.
3134 // We can't pass a 'scanf' string to a 'printf' function.
3135 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003136 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003137 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003138 }
3139 }
3140 }
3141 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003142 }
Mike Stump11289f42009-09-09 15:08:12 +00003143
Richard Smith55ce3522012-06-25 20:30:08 +00003144 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003145 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003146
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003147 case Stmt::CallExprClass:
3148 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003149 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003150 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3151 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3152 unsigned ArgIndex = FA->getFormatIdx();
3153 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3154 if (MD->isInstance())
3155 --ArgIndex;
3156 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Richard Smithd7293d72013-08-05 18:49:43 +00003158 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003159 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003160 Type, CallType, InFunctionCall,
3161 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003162 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3163 unsigned BuiltinID = FD->getBuiltinID();
3164 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3165 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3166 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003167 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003168 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003169 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003170 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003171 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003172 }
3173 }
Mike Stump11289f42009-09-09 15:08:12 +00003174
Richard Smith55ce3522012-06-25 20:30:08 +00003175 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003176 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003177 case Stmt::ObjCStringLiteralClass:
3178 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003179 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003181 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003182 StrE = ObjCFExpr->getString();
3183 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003184 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003186 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003187 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3188 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003189 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Richard Smith55ce3522012-06-25 20:30:08 +00003192 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003195 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003196 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003197 }
3198}
3199
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003200Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003201 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003202 .Case("scanf", FST_Scanf)
3203 .Cases("printf", "printf0", FST_Printf)
3204 .Cases("NSString", "CFString", FST_NSString)
3205 .Case("strftime", FST_Strftime)
3206 .Case("strfmon", FST_Strfmon)
3207 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003208 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003209 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003210 .Default(FST_Unknown);
3211}
3212
Jordan Rose3e0ec582012-07-19 18:10:23 +00003213/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003214/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003215/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003216bool Sema::CheckFormatArguments(const FormatAttr *Format,
3217 ArrayRef<const Expr *> Args,
3218 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003219 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003220 SourceLocation Loc, SourceRange Range,
3221 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003222 FormatStringInfo FSI;
3223 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003224 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003225 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003226 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003227 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003228}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003229
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003230bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003231 bool HasVAListArg, unsigned format_idx,
3232 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003233 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003234 SourceLocation Loc, SourceRange Range,
3235 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003236 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003237 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003238 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003239 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003242 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003243
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003244 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003245 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003246 // Dynamically generated format strings are difficult to
3247 // automatically vet at compile time. Requiring that format strings
3248 // are string literals: (1) permits the checking of format strings by
3249 // the compiler and thereby (2) can practically remove the source of
3250 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003251
Mike Stump11289f42009-09-09 15:08:12 +00003252 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003253 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003254 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003255 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003256 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003257 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3258 format_idx, firstDataArg, Type, CallType,
3259 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003260 if (CT != SLCT_NotALiteral)
3261 // Literal format string found, check done!
3262 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003263
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003264 // Strftime is particular as it always uses a single 'time' argument,
3265 // so it is safe to pass a non-literal string.
3266 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003267 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003268
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003269 // Do not emit diag when the string param is a macro expansion and the
3270 // format is either NSString or CFString. This is a hack to prevent
3271 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3272 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003273 if (Type == FST_NSString &&
3274 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003275 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003276
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003277 // If there are no arguments specified, warn with -Wformat-security, otherwise
3278 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003279 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003280 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003281 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003282 << OrigFormatExpr->getSourceRange();
3283 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003284 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003285 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003286 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003287 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003288}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003289
Ted Kremenekab278de2010-01-28 23:39:18 +00003290namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003291class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3292protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003293 Sema &S;
3294 const StringLiteral *FExpr;
3295 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003296 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003297 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003298 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003299 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003300 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003301 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003302 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003303 bool usesPositionalArgs;
3304 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003305 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003306 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003307 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003308public:
Ted Kremenek02087932010-07-16 02:11:22 +00003309 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003310 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003311 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003312 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003313 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003314 Sema::VariadicCallType callType,
3315 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003316 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003317 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3318 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003319 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003320 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003321 inFunctionCall(inFunctionCall), CallType(callType),
3322 CheckedVarArgs(CheckedVarArgs) {
3323 CoveredArgs.resize(numDataArgs);
3324 CoveredArgs.reset();
3325 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003326
Ted Kremenek019d2242010-01-29 01:50:07 +00003327 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003328
Ted Kremenek02087932010-07-16 02:11:22 +00003329 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003330 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003331
Jordan Rose92303592012-09-08 04:00:03 +00003332 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003333 const analyze_format_string::FormatSpecifier &FS,
3334 const analyze_format_string::ConversionSpecifier &CS,
3335 const char *startSpecifier, unsigned specifierLen,
3336 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003337
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003338 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003339 const analyze_format_string::FormatSpecifier &FS,
3340 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003341
3342 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003343 const analyze_format_string::ConversionSpecifier &CS,
3344 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003345
Craig Toppere14c0f82014-03-12 04:55:44 +00003346 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003347
Craig Toppere14c0f82014-03-12 04:55:44 +00003348 void HandleInvalidPosition(const char *startSpecifier,
3349 unsigned specifierLen,
3350 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003351
Craig Toppere14c0f82014-03-12 04:55:44 +00003352 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003353
Craig Toppere14c0f82014-03-12 04:55:44 +00003354 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003355
Richard Trieu03cf7b72011-10-28 00:41:25 +00003356 template <typename Range>
3357 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3358 const Expr *ArgumentExpr,
3359 PartialDiagnostic PDiag,
3360 SourceLocation StringLoc,
3361 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003362 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003363
Ted Kremenek02087932010-07-16 02:11:22 +00003364protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003365 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3366 const char *startSpec,
3367 unsigned specifierLen,
3368 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003369
3370 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3371 const char *startSpec,
3372 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003373
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003374 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003375 CharSourceRange getSpecifierRange(const char *startSpecifier,
3376 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003377 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003378
Ted Kremenek5739de72010-01-29 01:06:55 +00003379 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003380
3381 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3382 const analyze_format_string::ConversionSpecifier &CS,
3383 const char *startSpecifier, unsigned specifierLen,
3384 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003385
3386 template <typename Range>
3387 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3388 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003389 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003391}
Ted Kremenekab278de2010-01-28 23:39:18 +00003392
Ted Kremenek02087932010-07-16 02:11:22 +00003393SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003394 return OrigFormatExpr->getSourceRange();
3395}
3396
Ted Kremenek02087932010-07-16 02:11:22 +00003397CharSourceRange CheckFormatHandler::
3398getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003399 SourceLocation Start = getLocationOfByte(startSpecifier);
3400 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3401
3402 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003403 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003404
3405 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003406}
3407
Ted Kremenek02087932010-07-16 02:11:22 +00003408SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003409 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003410}
3411
Ted Kremenek02087932010-07-16 02:11:22 +00003412void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3413 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003414 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3415 getLocationOfByte(startSpecifier),
3416 /*IsStringLocation*/true,
3417 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003418}
3419
Jordan Rose92303592012-09-08 04:00:03 +00003420void CheckFormatHandler::HandleInvalidLengthModifier(
3421 const analyze_format_string::FormatSpecifier &FS,
3422 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003423 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003424 using namespace analyze_format_string;
3425
3426 const LengthModifier &LM = FS.getLengthModifier();
3427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3428
3429 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003431 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003432 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003433 getLocationOfByte(LM.getStart()),
3434 /*IsStringLocation*/true,
3435 getSpecifierRange(startSpecifier, specifierLen));
3436
3437 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3438 << FixedLM->toString()
3439 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3440
3441 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003442 FixItHint Hint;
3443 if (DiagID == diag::warn_format_nonsensical_length)
3444 Hint = FixItHint::CreateRemoval(LMRange);
3445
3446 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003447 getLocationOfByte(LM.getStart()),
3448 /*IsStringLocation*/true,
3449 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003450 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003451 }
3452}
3453
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003454void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003455 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003456 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003457 using namespace analyze_format_string;
3458
3459 const LengthModifier &LM = FS.getLengthModifier();
3460 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3461
3462 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003463 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003464 if (FixedLM) {
3465 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3466 << LM.toString() << 0,
3467 getLocationOfByte(LM.getStart()),
3468 /*IsStringLocation*/true,
3469 getSpecifierRange(startSpecifier, specifierLen));
3470
3471 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3472 << FixedLM->toString()
3473 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3474
3475 } else {
3476 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3477 << LM.toString() << 0,
3478 getLocationOfByte(LM.getStart()),
3479 /*IsStringLocation*/true,
3480 getSpecifierRange(startSpecifier, specifierLen));
3481 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003482}
3483
3484void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3485 const analyze_format_string::ConversionSpecifier &CS,
3486 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003487 using namespace analyze_format_string;
3488
3489 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003490 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003491 if (FixedCS) {
3492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3493 << CS.toString() << /*conversion specifier*/1,
3494 getLocationOfByte(CS.getStart()),
3495 /*IsStringLocation*/true,
3496 getSpecifierRange(startSpecifier, specifierLen));
3497
3498 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3499 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3500 << FixedCS->toString()
3501 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3502 } else {
3503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3504 << CS.toString() << /*conversion specifier*/1,
3505 getLocationOfByte(CS.getStart()),
3506 /*IsStringLocation*/true,
3507 getSpecifierRange(startSpecifier, specifierLen));
3508 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003509}
3510
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003511void CheckFormatHandler::HandlePosition(const char *startPos,
3512 unsigned posLen) {
3513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3514 getLocationOfByte(startPos),
3515 /*IsStringLocation*/true,
3516 getSpecifierRange(startPos, posLen));
3517}
3518
Ted Kremenekd1668192010-02-27 01:41:03 +00003519void
Ted Kremenek02087932010-07-16 02:11:22 +00003520CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3521 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3523 << (unsigned) p,
3524 getLocationOfByte(startPos), /*IsStringLocation*/true,
3525 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003526}
3527
Ted Kremenek02087932010-07-16 02:11:22 +00003528void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003529 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3531 getLocationOfByte(startPos),
3532 /*IsStringLocation*/true,
3533 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003534}
3535
Ted Kremenek02087932010-07-16 02:11:22 +00003536void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003537 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003538 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003539 EmitFormatDiagnostic(
3540 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3541 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3542 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003543 }
Ted Kremenek02087932010-07-16 02:11:22 +00003544}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003545
Jordan Rose58bbe422012-07-19 18:10:08 +00003546// Note that this may return NULL if there was an error parsing or building
3547// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003548const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003549 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003550}
3551
3552void CheckFormatHandler::DoneProcessing() {
3553 // Does the number of data arguments exceed the number of
3554 // format conversions in the format string?
3555 if (!HasVAListArg) {
3556 // Find any arguments that weren't covered.
3557 CoveredArgs.flip();
3558 signed notCoveredArg = CoveredArgs.find_first();
3559 if (notCoveredArg >= 0) {
3560 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003561 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3562 SourceLocation Loc = E->getLocStart();
3563 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3564 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3565 Loc, /*IsStringLocation*/false,
3566 getFormatStringRange());
3567 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003568 }
Ted Kremenek02087932010-07-16 02:11:22 +00003569 }
3570 }
3571}
3572
Ted Kremenekce815422010-07-19 21:25:57 +00003573bool
3574CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3575 SourceLocation Loc,
3576 const char *startSpec,
3577 unsigned specifierLen,
3578 const char *csStart,
3579 unsigned csLen) {
3580
3581 bool keepGoing = true;
3582 if (argIndex < NumDataArgs) {
3583 // Consider the argument coverered, even though the specifier doesn't
3584 // make sense.
3585 CoveredArgs.set(argIndex);
3586 }
3587 else {
3588 // If argIndex exceeds the number of data arguments we
3589 // don't issue a warning because that is just a cascade of warnings (and
3590 // they may have intended '%%' anyway). We don't want to continue processing
3591 // the format string after this point, however, as we will like just get
3592 // gibberish when trying to match arguments.
3593 keepGoing = false;
3594 }
3595
Richard Trieu03cf7b72011-10-28 00:41:25 +00003596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3597 << StringRef(csStart, csLen),
3598 Loc, /*IsStringLocation*/true,
3599 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003600
3601 return keepGoing;
3602}
3603
Richard Trieu03cf7b72011-10-28 00:41:25 +00003604void
3605CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3606 const char *startSpec,
3607 unsigned specifierLen) {
3608 EmitFormatDiagnostic(
3609 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3610 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3611}
3612
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003613bool
3614CheckFormatHandler::CheckNumArgs(
3615 const analyze_format_string::FormatSpecifier &FS,
3616 const analyze_format_string::ConversionSpecifier &CS,
3617 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3618
3619 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003620 PartialDiagnostic PDiag = FS.usesPositionalArg()
3621 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3622 << (argIndex+1) << NumDataArgs)
3623 : S.PDiag(diag::warn_printf_insufficient_data_args);
3624 EmitFormatDiagnostic(
3625 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3626 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003627 return false;
3628 }
3629 return true;
3630}
3631
Richard Trieu03cf7b72011-10-28 00:41:25 +00003632template<typename Range>
3633void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3634 SourceLocation Loc,
3635 bool IsStringLocation,
3636 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003637 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003638 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003639 Loc, IsStringLocation, StringRange, FixIt);
3640}
3641
3642/// \brief If the format string is not within the funcion call, emit a note
3643/// so that the function call and string are in diagnostic messages.
3644///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003645/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646/// call and only one diagnostic message will be produced. Otherwise, an
3647/// extra note will be emitted pointing to location of the format string.
3648///
3649/// \param ArgumentExpr the expression that is passed as the format string
3650/// argument in the function call. Used for getting locations when two
3651/// diagnostics are emitted.
3652///
3653/// \param PDiag the callee should already have provided any strings for the
3654/// diagnostic message. This function only adds locations and fixits
3655/// to diagnostics.
3656///
3657/// \param Loc primary location for diagnostic. If two diagnostics are
3658/// required, one will be at Loc and a new SourceLocation will be created for
3659/// the other one.
3660///
3661/// \param IsStringLocation if true, Loc points to the format string should be
3662/// used for the note. Otherwise, Loc points to the argument list and will
3663/// be used with PDiag.
3664///
3665/// \param StringRange some or all of the string to highlight. This is
3666/// templated so it can accept either a CharSourceRange or a SourceRange.
3667///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003668/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003669template<typename Range>
3670void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3671 const Expr *ArgumentExpr,
3672 PartialDiagnostic PDiag,
3673 SourceLocation Loc,
3674 bool IsStringLocation,
3675 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003676 ArrayRef<FixItHint> FixIt) {
3677 if (InFunctionCall) {
3678 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3679 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003680 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003681 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003682 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3683 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003684
3685 const Sema::SemaDiagnosticBuilder &Note =
3686 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3687 diag::note_format_string_defined);
3688
3689 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003690 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003691 }
3692}
3693
Ted Kremenek02087932010-07-16 02:11:22 +00003694//===--- CHECK: Printf format string checking ------------------------------===//
3695
3696namespace {
3697class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003698 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003699public:
3700 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3701 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003702 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003703 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003704 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003705 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003706 Sema::VariadicCallType CallType,
3707 llvm::SmallBitVector &CheckedVarArgs)
3708 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3709 numDataArgs, beg, hasVAListArg, Args,
3710 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3711 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003712 {}
3713
Craig Toppere14c0f82014-03-12 04:55:44 +00003714
Ted Kremenek02087932010-07-16 02:11:22 +00003715 bool HandleInvalidPrintfConversionSpecifier(
3716 const analyze_printf::PrintfSpecifier &FS,
3717 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003718 unsigned specifierLen) override;
3719
Ted Kremenek02087932010-07-16 02:11:22 +00003720 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3721 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003722 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003723 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3724 const char *StartSpecifier,
3725 unsigned SpecifierLen,
3726 const Expr *E);
3727
Ted Kremenek02087932010-07-16 02:11:22 +00003728 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3729 const char *startSpecifier, unsigned specifierLen);
3730 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3731 const analyze_printf::OptionalAmount &Amt,
3732 unsigned type,
3733 const char *startSpecifier, unsigned specifierLen);
3734 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3735 const analyze_printf::OptionalFlag &flag,
3736 const char *startSpecifier, unsigned specifierLen);
3737 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3738 const analyze_printf::OptionalFlag &ignoredFlag,
3739 const analyze_printf::OptionalFlag &flag,
3740 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003741 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003742 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003743
3744 void HandleEmptyObjCModifierFlag(const char *startFlag,
3745 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003746
Ted Kremenek2b417712015-07-02 05:39:16 +00003747 void HandleInvalidObjCModifierFlag(const char *startFlag,
3748 unsigned flagLen) override;
3749
3750 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3751 const char *flagsEnd,
3752 const char *conversionPosition)
3753 override;
3754};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003755}
Ted Kremenek02087932010-07-16 02:11:22 +00003756
3757bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3758 const analyze_printf::PrintfSpecifier &FS,
3759 const char *startSpecifier,
3760 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003761 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003762 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003763
Ted Kremenekce815422010-07-19 21:25:57 +00003764 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3765 getLocationOfByte(CS.getStart()),
3766 startSpecifier, specifierLen,
3767 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003768}
3769
Ted Kremenek02087932010-07-16 02:11:22 +00003770bool CheckPrintfHandler::HandleAmount(
3771 const analyze_format_string::OptionalAmount &Amt,
3772 unsigned k, const char *startSpecifier,
3773 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003774
3775 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003776 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003777 unsigned argIndex = Amt.getArgIndex();
3778 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003779 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3780 << k,
3781 getLocationOfByte(Amt.getStart()),
3782 /*IsStringLocation*/true,
3783 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003784 // Don't do any more checking. We will just emit
3785 // spurious errors.
3786 return false;
3787 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003788
Ted Kremenek5739de72010-01-29 01:06:55 +00003789 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003790 // Although not in conformance with C99, we also allow the argument to be
3791 // an 'unsigned int' as that is a reasonably safe case. GCC also
3792 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003793 CoveredArgs.set(argIndex);
3794 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003795 if (!Arg)
3796 return false;
3797
Ted Kremenek5739de72010-01-29 01:06:55 +00003798 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003799
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003800 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3801 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003802
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003803 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003804 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003805 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003806 << T << Arg->getSourceRange(),
3807 getLocationOfByte(Amt.getStart()),
3808 /*IsStringLocation*/true,
3809 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003810 // Don't do any more checking. We will just emit
3811 // spurious errors.
3812 return false;
3813 }
3814 }
3815 }
3816 return true;
3817}
Ted Kremenek5739de72010-01-29 01:06:55 +00003818
Tom Careb49ec692010-06-17 19:00:27 +00003819void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003820 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003821 const analyze_printf::OptionalAmount &Amt,
3822 unsigned type,
3823 const char *startSpecifier,
3824 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003825 const analyze_printf::PrintfConversionSpecifier &CS =
3826 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003827
Richard Trieu03cf7b72011-10-28 00:41:25 +00003828 FixItHint fixit =
3829 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3830 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3831 Amt.getConstantLength()))
3832 : FixItHint();
3833
3834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3835 << type << CS.toString(),
3836 getLocationOfByte(Amt.getStart()),
3837 /*IsStringLocation*/true,
3838 getSpecifierRange(startSpecifier, specifierLen),
3839 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003840}
3841
Ted Kremenek02087932010-07-16 02:11:22 +00003842void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003843 const analyze_printf::OptionalFlag &flag,
3844 const char *startSpecifier,
3845 unsigned specifierLen) {
3846 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003847 const analyze_printf::PrintfConversionSpecifier &CS =
3848 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003849 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3850 << flag.toString() << CS.toString(),
3851 getLocationOfByte(flag.getPosition()),
3852 /*IsStringLocation*/true,
3853 getSpecifierRange(startSpecifier, specifierLen),
3854 FixItHint::CreateRemoval(
3855 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003856}
3857
3858void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003859 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003860 const analyze_printf::OptionalFlag &ignoredFlag,
3861 const analyze_printf::OptionalFlag &flag,
3862 const char *startSpecifier,
3863 unsigned specifierLen) {
3864 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003865 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3866 << ignoredFlag.toString() << flag.toString(),
3867 getLocationOfByte(ignoredFlag.getPosition()),
3868 /*IsStringLocation*/true,
3869 getSpecifierRange(startSpecifier, specifierLen),
3870 FixItHint::CreateRemoval(
3871 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003872}
3873
Ted Kremenek2b417712015-07-02 05:39:16 +00003874// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3875// bool IsStringLocation, Range StringRange,
3876// ArrayRef<FixItHint> Fixit = None);
3877
3878void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3879 unsigned flagLen) {
3880 // Warn about an empty flag.
3881 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3882 getLocationOfByte(startFlag),
3883 /*IsStringLocation*/true,
3884 getSpecifierRange(startFlag, flagLen));
3885}
3886
3887void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3888 unsigned flagLen) {
3889 // Warn about an invalid flag.
3890 auto Range = getSpecifierRange(startFlag, flagLen);
3891 StringRef flag(startFlag, flagLen);
3892 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3893 getLocationOfByte(startFlag),
3894 /*IsStringLocation*/true,
3895 Range, FixItHint::CreateRemoval(Range));
3896}
3897
3898void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3899 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3900 // Warn about using '[...]' without a '@' conversion.
3901 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3902 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3903 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3904 getLocationOfByte(conversionPosition),
3905 /*IsStringLocation*/true,
3906 Range, FixItHint::CreateRemoval(Range));
3907}
3908
Richard Smith55ce3522012-06-25 20:30:08 +00003909// Determines if the specified is a C++ class or struct containing
3910// a member with the specified name and kind (e.g. a CXXMethodDecl named
3911// "c_str()").
3912template<typename MemberKind>
3913static llvm::SmallPtrSet<MemberKind*, 1>
3914CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3915 const RecordType *RT = Ty->getAs<RecordType>();
3916 llvm::SmallPtrSet<MemberKind*, 1> Results;
3917
3918 if (!RT)
3919 return Results;
3920 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003921 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003922 return Results;
3923
Alp Tokerb6cc5922014-05-03 03:45:55 +00003924 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003925 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003926 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003927
3928 // We just need to include all members of the right kind turned up by the
3929 // filter, at this point.
3930 if (S.LookupQualifiedName(R, RT->getDecl()))
3931 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3932 NamedDecl *decl = (*I)->getUnderlyingDecl();
3933 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3934 Results.insert(FK);
3935 }
3936 return Results;
3937}
3938
Richard Smith2868a732014-02-28 01:36:39 +00003939/// Check if we could call '.c_str()' on an object.
3940///
3941/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3942/// allow the call, or if it would be ambiguous).
3943bool Sema::hasCStrMethod(const Expr *E) {
3944 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3945 MethodSet Results =
3946 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3947 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3948 MI != ME; ++MI)
3949 if ((*MI)->getMinRequiredArguments() == 0)
3950 return true;
3951 return false;
3952}
3953
Richard Smith55ce3522012-06-25 20:30:08 +00003954// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003955// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003956// Returns true when a c_str() conversion method is found.
3957bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003958 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003959 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3960
3961 MethodSet Results =
3962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3963
3964 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3965 MI != ME; ++MI) {
3966 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003967 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003968 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003969 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003970 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003971 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3972 << "c_str()"
3973 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3974 return true;
3975 }
3976 }
3977
3978 return false;
3979}
3980
Ted Kremenekab278de2010-01-28 23:39:18 +00003981bool
Ted Kremenek02087932010-07-16 02:11:22 +00003982CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003983 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003984 const char *startSpecifier,
3985 unsigned specifierLen) {
3986
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003987 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003988 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003989 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003990
Ted Kremenek6cd69422010-07-19 22:01:06 +00003991 if (FS.consumesDataArgument()) {
3992 if (atFirstArg) {
3993 atFirstArg = false;
3994 usesPositionalArgs = FS.usesPositionalArg();
3995 }
3996 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003997 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3998 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003999 return false;
4000 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004001 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004002
Ted Kremenekd1668192010-02-27 01:41:03 +00004003 // First check if the field width, precision, and conversion specifier
4004 // have matching data arguments.
4005 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4006 startSpecifier, specifierLen)) {
4007 return false;
4008 }
4009
4010 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4011 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004012 return false;
4013 }
4014
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004015 if (!CS.consumesDataArgument()) {
4016 // FIXME: Technically specifying a precision or field width here
4017 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004018 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004019 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004020
Ted Kremenek4a49d982010-02-26 19:18:41 +00004021 // Consume the argument.
4022 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004023 if (argIndex < NumDataArgs) {
4024 // The check to see if the argIndex is valid will come later.
4025 // We set the bit here because we may exit early from this
4026 // function if we encounter some other error.
4027 CoveredArgs.set(argIndex);
4028 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004029
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004030 // FreeBSD kernel extensions.
4031 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4032 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4033 // We need at least two arguments.
4034 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4035 return false;
4036
4037 // Claim the second argument.
4038 CoveredArgs.set(argIndex + 1);
4039
4040 // Type check the first argument (int for %b, pointer for %D)
4041 const Expr *Ex = getDataArg(argIndex);
4042 const analyze_printf::ArgType &AT =
4043 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4044 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4045 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4046 EmitFormatDiagnostic(
4047 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4048 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4049 << false << Ex->getSourceRange(),
4050 Ex->getLocStart(), /*IsStringLocation*/false,
4051 getSpecifierRange(startSpecifier, specifierLen));
4052
4053 // Type check the second argument (char * for both %b and %D)
4054 Ex = getDataArg(argIndex + 1);
4055 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4056 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4057 EmitFormatDiagnostic(
4058 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4059 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4060 << false << Ex->getSourceRange(),
4061 Ex->getLocStart(), /*IsStringLocation*/false,
4062 getSpecifierRange(startSpecifier, specifierLen));
4063
4064 return true;
4065 }
4066
Ted Kremenek4a49d982010-02-26 19:18:41 +00004067 // Check for using an Objective-C specific conversion specifier
4068 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004069 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004070 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4071 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004072 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004073
Tom Careb49ec692010-06-17 19:00:27 +00004074 // Check for invalid use of field width
4075 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004076 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004077 startSpecifier, specifierLen);
4078 }
4079
4080 // Check for invalid use of precision
4081 if (!FS.hasValidPrecision()) {
4082 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4083 startSpecifier, specifierLen);
4084 }
4085
4086 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004087 if (!FS.hasValidThousandsGroupingPrefix())
4088 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004089 if (!FS.hasValidLeadingZeros())
4090 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4091 if (!FS.hasValidPlusPrefix())
4092 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004093 if (!FS.hasValidSpacePrefix())
4094 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004095 if (!FS.hasValidAlternativeForm())
4096 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4097 if (!FS.hasValidLeftJustified())
4098 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4099
4100 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004101 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4102 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4103 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004104 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4105 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4106 startSpecifier, specifierLen);
4107
4108 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004109 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4111 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004112 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004113 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004114 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004115 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4116 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004117
Jordan Rose92303592012-09-08 04:00:03 +00004118 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4119 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4120
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004121 // The remaining checks depend on the data arguments.
4122 if (HasVAListArg)
4123 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004124
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004125 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004126 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004127
Jordan Rose58bbe422012-07-19 18:10:08 +00004128 const Expr *Arg = getDataArg(argIndex);
4129 if (!Arg)
4130 return true;
4131
4132 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004133}
4134
Jordan Roseaee34382012-09-05 22:56:26 +00004135static bool requiresParensToAddCast(const Expr *E) {
4136 // FIXME: We should have a general way to reason about operator
4137 // precedence and whether parens are actually needed here.
4138 // Take care of a few common cases where they aren't.
4139 const Expr *Inside = E->IgnoreImpCasts();
4140 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4141 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4142
4143 switch (Inside->getStmtClass()) {
4144 case Stmt::ArraySubscriptExprClass:
4145 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004146 case Stmt::CharacterLiteralClass:
4147 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004148 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004149 case Stmt::FloatingLiteralClass:
4150 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004151 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004152 case Stmt::ObjCArrayLiteralClass:
4153 case Stmt::ObjCBoolLiteralExprClass:
4154 case Stmt::ObjCBoxedExprClass:
4155 case Stmt::ObjCDictionaryLiteralClass:
4156 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004157 case Stmt::ObjCIvarRefExprClass:
4158 case Stmt::ObjCMessageExprClass:
4159 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004160 case Stmt::ObjCStringLiteralClass:
4161 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004162 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004163 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004164 case Stmt::UnaryOperatorClass:
4165 return false;
4166 default:
4167 return true;
4168 }
4169}
4170
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004171static std::pair<QualType, StringRef>
4172shouldNotPrintDirectly(const ASTContext &Context,
4173 QualType IntendedTy,
4174 const Expr *E) {
4175 // Use a 'while' to peel off layers of typedefs.
4176 QualType TyTy = IntendedTy;
4177 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4178 StringRef Name = UserTy->getDecl()->getName();
4179 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4180 .Case("NSInteger", Context.LongTy)
4181 .Case("NSUInteger", Context.UnsignedLongTy)
4182 .Case("SInt32", Context.IntTy)
4183 .Case("UInt32", Context.UnsignedIntTy)
4184 .Default(QualType());
4185
4186 if (!CastTy.isNull())
4187 return std::make_pair(CastTy, Name);
4188
4189 TyTy = UserTy->desugar();
4190 }
4191
4192 // Strip parens if necessary.
4193 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4194 return shouldNotPrintDirectly(Context,
4195 PE->getSubExpr()->getType(),
4196 PE->getSubExpr());
4197
4198 // If this is a conditional expression, then its result type is constructed
4199 // via usual arithmetic conversions and thus there might be no necessary
4200 // typedef sugar there. Recurse to operands to check for NSInteger &
4201 // Co. usage condition.
4202 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4203 QualType TrueTy, FalseTy;
4204 StringRef TrueName, FalseName;
4205
4206 std::tie(TrueTy, TrueName) =
4207 shouldNotPrintDirectly(Context,
4208 CO->getTrueExpr()->getType(),
4209 CO->getTrueExpr());
4210 std::tie(FalseTy, FalseName) =
4211 shouldNotPrintDirectly(Context,
4212 CO->getFalseExpr()->getType(),
4213 CO->getFalseExpr());
4214
4215 if (TrueTy == FalseTy)
4216 return std::make_pair(TrueTy, TrueName);
4217 else if (TrueTy.isNull())
4218 return std::make_pair(FalseTy, FalseName);
4219 else if (FalseTy.isNull())
4220 return std::make_pair(TrueTy, TrueName);
4221 }
4222
4223 return std::make_pair(QualType(), StringRef());
4224}
4225
Richard Smith55ce3522012-06-25 20:30:08 +00004226bool
4227CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4228 const char *StartSpecifier,
4229 unsigned SpecifierLen,
4230 const Expr *E) {
4231 using namespace analyze_format_string;
4232 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004233 // Now type check the data expression that matches the
4234 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004235 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4236 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004237 if (!AT.isValid())
4238 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004239
Jordan Rose598ec092012-12-05 18:44:40 +00004240 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004241 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4242 ExprTy = TET->getUnderlyingExpr()->getType();
4243 }
4244
Seth Cantrellb4802962015-03-04 03:12:10 +00004245 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4246
4247 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004248 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004249 }
Jordan Rose98709982012-06-04 22:48:57 +00004250
Jordan Rose22b74712012-09-05 22:56:19 +00004251 // Look through argument promotions for our error message's reported type.
4252 // This includes the integral and floating promotions, but excludes array
4253 // and function pointer decay; seeing that an argument intended to be a
4254 // string has type 'char [6]' is probably more confusing than 'char *'.
4255 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4256 if (ICE->getCastKind() == CK_IntegralCast ||
4257 ICE->getCastKind() == CK_FloatingCast) {
4258 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004259 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004260
4261 // Check if we didn't match because of an implicit cast from a 'char'
4262 // or 'short' to an 'int'. This is done because printf is a varargs
4263 // function.
4264 if (ICE->getType() == S.Context.IntTy ||
4265 ICE->getType() == S.Context.UnsignedIntTy) {
4266 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004267 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004268 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004269 }
Jordan Rose98709982012-06-04 22:48:57 +00004270 }
Jordan Rose598ec092012-12-05 18:44:40 +00004271 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4272 // Special case for 'a', which has type 'int' in C.
4273 // Note, however, that we do /not/ want to treat multibyte constants like
4274 // 'MooV' as characters! This form is deprecated but still exists.
4275 if (ExprTy == S.Context.IntTy)
4276 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4277 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004278 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004279
Jordan Rosebc53ed12014-05-31 04:12:14 +00004280 // Look through enums to their underlying type.
4281 bool IsEnum = false;
4282 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4283 ExprTy = EnumTy->getDecl()->getIntegerType();
4284 IsEnum = true;
4285 }
4286
Jordan Rose0e5badd2012-12-05 18:44:49 +00004287 // %C in an Objective-C context prints a unichar, not a wchar_t.
4288 // If the argument is an integer of some kind, believe the %C and suggest
4289 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004290 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004291 if (ObjCContext &&
4292 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4293 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4294 !ExprTy->isCharType()) {
4295 // 'unichar' is defined as a typedef of unsigned short, but we should
4296 // prefer using the typedef if it is visible.
4297 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004298
4299 // While we are here, check if the value is an IntegerLiteral that happens
4300 // to be within the valid range.
4301 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4302 const llvm::APInt &V = IL->getValue();
4303 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4304 return true;
4305 }
4306
Jordan Rose0e5badd2012-12-05 18:44:49 +00004307 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4308 Sema::LookupOrdinaryName);
4309 if (S.LookupName(Result, S.getCurScope())) {
4310 NamedDecl *ND = Result.getFoundDecl();
4311 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4312 if (TD->getUnderlyingType() == IntendedTy)
4313 IntendedTy = S.Context.getTypedefType(TD);
4314 }
4315 }
4316 }
4317
4318 // Special-case some of Darwin's platform-independence types by suggesting
4319 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004320 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004321 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004322 QualType CastTy;
4323 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4324 if (!CastTy.isNull()) {
4325 IntendedTy = CastTy;
4326 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004327 }
4328 }
4329
Jordan Rose22b74712012-09-05 22:56:19 +00004330 // We may be able to offer a FixItHint if it is a supported type.
4331 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004332 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004333 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004334
Jordan Rose22b74712012-09-05 22:56:19 +00004335 if (success) {
4336 // Get the fix string from the fixed format specifier
4337 SmallString<16> buf;
4338 llvm::raw_svector_ostream os(buf);
4339 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004340
Jordan Roseaee34382012-09-05 22:56:26 +00004341 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4342
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004343 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004344 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4345 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4346 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4347 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004348 // In this case, the specifier is wrong and should be changed to match
4349 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004350 EmitFormatDiagnostic(S.PDiag(diag)
4351 << AT.getRepresentativeTypeName(S.Context)
4352 << IntendedTy << IsEnum << E->getSourceRange(),
4353 E->getLocStart(),
4354 /*IsStringLocation*/ false, SpecRange,
4355 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004356
4357 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004358 // The canonical type for formatting this value is different from the
4359 // actual type of the expression. (This occurs, for example, with Darwin's
4360 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4361 // should be printed as 'long' for 64-bit compatibility.)
4362 // Rather than emitting a normal format/argument mismatch, we want to
4363 // add a cast to the recommended type (and correct the format string
4364 // if necessary).
4365 SmallString<16> CastBuf;
4366 llvm::raw_svector_ostream CastFix(CastBuf);
4367 CastFix << "(";
4368 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4369 CastFix << ")";
4370
4371 SmallVector<FixItHint,4> Hints;
4372 if (!AT.matchesType(S.Context, IntendedTy))
4373 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4374
4375 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4376 // If there's already a cast present, just replace it.
4377 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4378 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4379
4380 } else if (!requiresParensToAddCast(E)) {
4381 // If the expression has high enough precedence,
4382 // just write the C-style cast.
4383 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4384 CastFix.str()));
4385 } else {
4386 // Otherwise, add parens around the expression as well as the cast.
4387 CastFix << "(";
4388 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4389 CastFix.str()));
4390
Alp Tokerb6cc5922014-05-03 03:45:55 +00004391 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004392 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4393 }
4394
Jordan Rose0e5badd2012-12-05 18:44:49 +00004395 if (ShouldNotPrintDirectly) {
4396 // The expression has a type that should not be printed directly.
4397 // We extract the name from the typedef because we don't want to show
4398 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004399 StringRef Name;
4400 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4401 Name = TypedefTy->getDecl()->getName();
4402 else
4403 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004404 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004405 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004406 << E->getSourceRange(),
4407 E->getLocStart(), /*IsStringLocation=*/false,
4408 SpecRange, Hints);
4409 } else {
4410 // In this case, the expression could be printed using a different
4411 // specifier, but we've decided that the specifier is probably correct
4412 // and we should cast instead. Just use the normal warning message.
4413 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004414 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4415 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004416 << E->getSourceRange(),
4417 E->getLocStart(), /*IsStringLocation*/false,
4418 SpecRange, Hints);
4419 }
Jordan Roseaee34382012-09-05 22:56:26 +00004420 }
Jordan Rose22b74712012-09-05 22:56:19 +00004421 } else {
4422 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4423 SpecifierLen);
4424 // Since the warning for passing non-POD types to variadic functions
4425 // was deferred until now, we emit a warning for non-POD
4426 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004427 switch (S.isValidVarArgType(ExprTy)) {
4428 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004429 case Sema::VAK_ValidInCXX11: {
4430 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4431 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4432 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4433 }
Richard Smithd7293d72013-08-05 18:49:43 +00004434
Seth Cantrellb4802962015-03-04 03:12:10 +00004435 EmitFormatDiagnostic(
4436 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4437 << IsEnum << CSR << E->getSourceRange(),
4438 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4439 break;
4440 }
Richard Smithd7293d72013-08-05 18:49:43 +00004441 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004442 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004443 EmitFormatDiagnostic(
4444 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004445 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004446 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004447 << CallType
4448 << AT.getRepresentativeTypeName(S.Context)
4449 << CSR
4450 << E->getSourceRange(),
4451 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004452 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004453 break;
4454
4455 case Sema::VAK_Invalid:
4456 if (ExprTy->isObjCObjectType())
4457 EmitFormatDiagnostic(
4458 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4459 << S.getLangOpts().CPlusPlus11
4460 << ExprTy
4461 << CallType
4462 << AT.getRepresentativeTypeName(S.Context)
4463 << CSR
4464 << E->getSourceRange(),
4465 E->getLocStart(), /*IsStringLocation*/false, CSR);
4466 else
4467 // FIXME: If this is an initializer list, suggest removing the braces
4468 // or inserting a cast to the target type.
4469 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4470 << isa<InitListExpr>(E) << ExprTy << CallType
4471 << AT.getRepresentativeTypeName(S.Context)
4472 << E->getSourceRange();
4473 break;
4474 }
4475
4476 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4477 "format string specifier index out of range");
4478 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004479 }
4480
Ted Kremenekab278de2010-01-28 23:39:18 +00004481 return true;
4482}
4483
Ted Kremenek02087932010-07-16 02:11:22 +00004484//===--- CHECK: Scanf format string checking ------------------------------===//
4485
4486namespace {
4487class CheckScanfHandler : public CheckFormatHandler {
4488public:
4489 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4490 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004491 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004492 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004493 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004494 Sema::VariadicCallType CallType,
4495 llvm::SmallBitVector &CheckedVarArgs)
4496 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4497 numDataArgs, beg, hasVAListArg,
4498 Args, formatIdx, inFunctionCall, CallType,
4499 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004500 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004501
4502 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4503 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004504 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004505
4506 bool HandleInvalidScanfConversionSpecifier(
4507 const analyze_scanf::ScanfSpecifier &FS,
4508 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004509 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004510
Craig Toppere14c0f82014-03-12 04:55:44 +00004511 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004512};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004513}
Ted Kremenekab278de2010-01-28 23:39:18 +00004514
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004515void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4516 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004517 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4518 getLocationOfByte(end), /*IsStringLocation*/true,
4519 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004520}
4521
Ted Kremenekce815422010-07-19 21:25:57 +00004522bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4523 const analyze_scanf::ScanfSpecifier &FS,
4524 const char *startSpecifier,
4525 unsigned specifierLen) {
4526
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004527 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004528 FS.getConversionSpecifier();
4529
4530 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4531 getLocationOfByte(CS.getStart()),
4532 startSpecifier, specifierLen,
4533 CS.getStart(), CS.getLength());
4534}
4535
Ted Kremenek02087932010-07-16 02:11:22 +00004536bool CheckScanfHandler::HandleScanfSpecifier(
4537 const analyze_scanf::ScanfSpecifier &FS,
4538 const char *startSpecifier,
4539 unsigned specifierLen) {
4540
4541 using namespace analyze_scanf;
4542 using namespace analyze_format_string;
4543
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004544 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004545
Ted Kremenek6cd69422010-07-19 22:01:06 +00004546 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4547 // be used to decide if we are using positional arguments consistently.
4548 if (FS.consumesDataArgument()) {
4549 if (atFirstArg) {
4550 atFirstArg = false;
4551 usesPositionalArgs = FS.usesPositionalArg();
4552 }
4553 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004554 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4555 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004556 return false;
4557 }
Ted Kremenek02087932010-07-16 02:11:22 +00004558 }
4559
4560 // Check if the field with is non-zero.
4561 const OptionalAmount &Amt = FS.getFieldWidth();
4562 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4563 if (Amt.getConstantAmount() == 0) {
4564 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4565 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004566 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4567 getLocationOfByte(Amt.getStart()),
4568 /*IsStringLocation*/true, R,
4569 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004570 }
4571 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004572
Ted Kremenek02087932010-07-16 02:11:22 +00004573 if (!FS.consumesDataArgument()) {
4574 // FIXME: Technically specifying a precision or field width here
4575 // makes no sense. Worth issuing a warning at some point.
4576 return true;
4577 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004578
Ted Kremenek02087932010-07-16 02:11:22 +00004579 // Consume the argument.
4580 unsigned argIndex = FS.getArgIndex();
4581 if (argIndex < NumDataArgs) {
4582 // The check to see if the argIndex is valid will come later.
4583 // We set the bit here because we may exit early from this
4584 // function if we encounter some other error.
4585 CoveredArgs.set(argIndex);
4586 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004587
Ted Kremenek4407ea42010-07-20 20:04:47 +00004588 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004589 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004590 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4591 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004592 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004593 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004594 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004595 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4596 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004597
Jordan Rose92303592012-09-08 04:00:03 +00004598 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4599 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4600
Ted Kremenek02087932010-07-16 02:11:22 +00004601 // The remaining checks depend on the data arguments.
4602 if (HasVAListArg)
4603 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004604
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004605 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004606 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004607
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004608 // Check that the argument type matches the format specifier.
4609 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004610 if (!Ex)
4611 return true;
4612
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004613 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004614
4615 if (!AT.isValid()) {
4616 return true;
4617 }
4618
Seth Cantrellb4802962015-03-04 03:12:10 +00004619 analyze_format_string::ArgType::MatchKind match =
4620 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004621 if (match == analyze_format_string::ArgType::Match) {
4622 return true;
4623 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004624
Seth Cantrell79340072015-03-04 05:58:08 +00004625 ScanfSpecifier fixedFS = FS;
4626 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4627 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004628
Seth Cantrell79340072015-03-04 05:58:08 +00004629 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4630 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4631 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4632 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004633
Seth Cantrell79340072015-03-04 05:58:08 +00004634 if (success) {
4635 // Get the fix string from the fixed format specifier.
4636 SmallString<128> buf;
4637 llvm::raw_svector_ostream os(buf);
4638 fixedFS.toString(os);
4639
4640 EmitFormatDiagnostic(
4641 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4642 << Ex->getType() << false << Ex->getSourceRange(),
4643 Ex->getLocStart(),
4644 /*IsStringLocation*/ false,
4645 getSpecifierRange(startSpecifier, specifierLen),
4646 FixItHint::CreateReplacement(
4647 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4648 } else {
4649 EmitFormatDiagnostic(S.PDiag(diag)
4650 << AT.getRepresentativeTypeName(S.Context)
4651 << Ex->getType() << false << Ex->getSourceRange(),
4652 Ex->getLocStart(),
4653 /*IsStringLocation*/ false,
4654 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004655 }
4656
Ted Kremenek02087932010-07-16 02:11:22 +00004657 return true;
4658}
4659
4660void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004661 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004662 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004663 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004664 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004665 bool inFunctionCall, VariadicCallType CallType,
4666 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004667
Ted Kremenekab278de2010-01-28 23:39:18 +00004668 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004669 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004670 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004671 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004672 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4673 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004674 return;
4675 }
Ted Kremenek02087932010-07-16 02:11:22 +00004676
Ted Kremenekab278de2010-01-28 23:39:18 +00004677 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004678 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004679 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004680 // Account for cases where the string literal is truncated in a declaration.
4681 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4682 assert(T && "String literal not of constant array type!");
4683 size_t TypeSize = T->getSize().getZExtValue();
4684 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004685 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004686
4687 // Emit a warning if the string literal is truncated and does not contain an
4688 // embedded null character.
4689 if (TypeSize <= StrRef.size() &&
4690 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4691 CheckFormatHandler::EmitFormatDiagnostic(
4692 *this, inFunctionCall, Args[format_idx],
4693 PDiag(diag::warn_printf_format_string_not_null_terminated),
4694 FExpr->getLocStart(),
4695 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4696 return;
4697 }
4698
Ted Kremenekab278de2010-01-28 23:39:18 +00004699 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004700 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004701 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004702 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004703 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4704 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004705 return;
4706 }
Ted Kremenek02087932010-07-16 02:11:22 +00004707
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004708 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004709 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004710 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004711 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004712 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004713 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004714
Hans Wennborg23926bd2011-12-15 10:25:47 +00004715 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004716 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004717 Context.getTargetInfo(),
4718 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004719 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004720 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004721 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004722 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004723 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004724
Hans Wennborg23926bd2011-12-15 10:25:47 +00004725 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004726 getLangOpts(),
4727 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004728 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004729 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004730}
4731
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004732bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4733 // Str - The format string. NOTE: this is NOT null-terminated!
4734 StringRef StrRef = FExpr->getString();
4735 const char *Str = StrRef.data();
4736 // Account for cases where the string literal is truncated in a declaration.
4737 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4738 assert(T && "String literal not of constant array type!");
4739 size_t TypeSize = T->getSize().getZExtValue();
4740 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4741 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4742 getLangOpts(),
4743 Context.getTargetInfo());
4744}
4745
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004746//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4747
4748// Returns the related absolute value function that is larger, of 0 if one
4749// does not exist.
4750static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4751 switch (AbsFunction) {
4752 default:
4753 return 0;
4754
4755 case Builtin::BI__builtin_abs:
4756 return Builtin::BI__builtin_labs;
4757 case Builtin::BI__builtin_labs:
4758 return Builtin::BI__builtin_llabs;
4759 case Builtin::BI__builtin_llabs:
4760 return 0;
4761
4762 case Builtin::BI__builtin_fabsf:
4763 return Builtin::BI__builtin_fabs;
4764 case Builtin::BI__builtin_fabs:
4765 return Builtin::BI__builtin_fabsl;
4766 case Builtin::BI__builtin_fabsl:
4767 return 0;
4768
4769 case Builtin::BI__builtin_cabsf:
4770 return Builtin::BI__builtin_cabs;
4771 case Builtin::BI__builtin_cabs:
4772 return Builtin::BI__builtin_cabsl;
4773 case Builtin::BI__builtin_cabsl:
4774 return 0;
4775
4776 case Builtin::BIabs:
4777 return Builtin::BIlabs;
4778 case Builtin::BIlabs:
4779 return Builtin::BIllabs;
4780 case Builtin::BIllabs:
4781 return 0;
4782
4783 case Builtin::BIfabsf:
4784 return Builtin::BIfabs;
4785 case Builtin::BIfabs:
4786 return Builtin::BIfabsl;
4787 case Builtin::BIfabsl:
4788 return 0;
4789
4790 case Builtin::BIcabsf:
4791 return Builtin::BIcabs;
4792 case Builtin::BIcabs:
4793 return Builtin::BIcabsl;
4794 case Builtin::BIcabsl:
4795 return 0;
4796 }
4797}
4798
4799// Returns the argument type of the absolute value function.
4800static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4801 unsigned AbsType) {
4802 if (AbsType == 0)
4803 return QualType();
4804
4805 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4806 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4807 if (Error != ASTContext::GE_None)
4808 return QualType();
4809
4810 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4811 if (!FT)
4812 return QualType();
4813
4814 if (FT->getNumParams() != 1)
4815 return QualType();
4816
4817 return FT->getParamType(0);
4818}
4819
4820// Returns the best absolute value function, or zero, based on type and
4821// current absolute value function.
4822static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4823 unsigned AbsFunctionKind) {
4824 unsigned BestKind = 0;
4825 uint64_t ArgSize = Context.getTypeSize(ArgType);
4826 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4827 Kind = getLargerAbsoluteValueFunction(Kind)) {
4828 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4829 if (Context.getTypeSize(ParamType) >= ArgSize) {
4830 if (BestKind == 0)
4831 BestKind = Kind;
4832 else if (Context.hasSameType(ParamType, ArgType)) {
4833 BestKind = Kind;
4834 break;
4835 }
4836 }
4837 }
4838 return BestKind;
4839}
4840
4841enum AbsoluteValueKind {
4842 AVK_Integer,
4843 AVK_Floating,
4844 AVK_Complex
4845};
4846
4847static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4848 if (T->isIntegralOrEnumerationType())
4849 return AVK_Integer;
4850 if (T->isRealFloatingType())
4851 return AVK_Floating;
4852 if (T->isAnyComplexType())
4853 return AVK_Complex;
4854
4855 llvm_unreachable("Type not integer, floating, or complex");
4856}
4857
4858// Changes the absolute value function to a different type. Preserves whether
4859// the function is a builtin.
4860static unsigned changeAbsFunction(unsigned AbsKind,
4861 AbsoluteValueKind ValueKind) {
4862 switch (ValueKind) {
4863 case AVK_Integer:
4864 switch (AbsKind) {
4865 default:
4866 return 0;
4867 case Builtin::BI__builtin_fabsf:
4868 case Builtin::BI__builtin_fabs:
4869 case Builtin::BI__builtin_fabsl:
4870 case Builtin::BI__builtin_cabsf:
4871 case Builtin::BI__builtin_cabs:
4872 case Builtin::BI__builtin_cabsl:
4873 return Builtin::BI__builtin_abs;
4874 case Builtin::BIfabsf:
4875 case Builtin::BIfabs:
4876 case Builtin::BIfabsl:
4877 case Builtin::BIcabsf:
4878 case Builtin::BIcabs:
4879 case Builtin::BIcabsl:
4880 return Builtin::BIabs;
4881 }
4882 case AVK_Floating:
4883 switch (AbsKind) {
4884 default:
4885 return 0;
4886 case Builtin::BI__builtin_abs:
4887 case Builtin::BI__builtin_labs:
4888 case Builtin::BI__builtin_llabs:
4889 case Builtin::BI__builtin_cabsf:
4890 case Builtin::BI__builtin_cabs:
4891 case Builtin::BI__builtin_cabsl:
4892 return Builtin::BI__builtin_fabsf;
4893 case Builtin::BIabs:
4894 case Builtin::BIlabs:
4895 case Builtin::BIllabs:
4896 case Builtin::BIcabsf:
4897 case Builtin::BIcabs:
4898 case Builtin::BIcabsl:
4899 return Builtin::BIfabsf;
4900 }
4901 case AVK_Complex:
4902 switch (AbsKind) {
4903 default:
4904 return 0;
4905 case Builtin::BI__builtin_abs:
4906 case Builtin::BI__builtin_labs:
4907 case Builtin::BI__builtin_llabs:
4908 case Builtin::BI__builtin_fabsf:
4909 case Builtin::BI__builtin_fabs:
4910 case Builtin::BI__builtin_fabsl:
4911 return Builtin::BI__builtin_cabsf;
4912 case Builtin::BIabs:
4913 case Builtin::BIlabs:
4914 case Builtin::BIllabs:
4915 case Builtin::BIfabsf:
4916 case Builtin::BIfabs:
4917 case Builtin::BIfabsl:
4918 return Builtin::BIcabsf;
4919 }
4920 }
4921 llvm_unreachable("Unable to convert function");
4922}
4923
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004924static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004925 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4926 if (!FnInfo)
4927 return 0;
4928
4929 switch (FDecl->getBuiltinID()) {
4930 default:
4931 return 0;
4932 case Builtin::BI__builtin_abs:
4933 case Builtin::BI__builtin_fabs:
4934 case Builtin::BI__builtin_fabsf:
4935 case Builtin::BI__builtin_fabsl:
4936 case Builtin::BI__builtin_labs:
4937 case Builtin::BI__builtin_llabs:
4938 case Builtin::BI__builtin_cabs:
4939 case Builtin::BI__builtin_cabsf:
4940 case Builtin::BI__builtin_cabsl:
4941 case Builtin::BIabs:
4942 case Builtin::BIlabs:
4943 case Builtin::BIllabs:
4944 case Builtin::BIfabs:
4945 case Builtin::BIfabsf:
4946 case Builtin::BIfabsl:
4947 case Builtin::BIcabs:
4948 case Builtin::BIcabsf:
4949 case Builtin::BIcabsl:
4950 return FDecl->getBuiltinID();
4951 }
4952 llvm_unreachable("Unknown Builtin type");
4953}
4954
4955// If the replacement is valid, emit a note with replacement function.
4956// Additionally, suggest including the proper header if not already included.
4957static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004958 unsigned AbsKind, QualType ArgType) {
4959 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 const char *HeaderName = nullptr;
4961 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004962 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4963 FunctionName = "std::abs";
4964 if (ArgType->isIntegralOrEnumerationType()) {
4965 HeaderName = "cstdlib";
4966 } else if (ArgType->isRealFloatingType()) {
4967 HeaderName = "cmath";
4968 } else {
4969 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004970 }
Richard Trieubeffb832014-04-15 23:47:53 +00004971
4972 // Lookup all std::abs
4973 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004974 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004975 R.suppressDiagnostics();
4976 S.LookupQualifiedName(R, Std);
4977
4978 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004979 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004980 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4981 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4982 } else {
4983 FDecl = dyn_cast<FunctionDecl>(I);
4984 }
4985 if (!FDecl)
4986 continue;
4987
4988 // Found std::abs(), check that they are the right ones.
4989 if (FDecl->getNumParams() != 1)
4990 continue;
4991
4992 // Check that the parameter type can handle the argument.
4993 QualType ParamType = FDecl->getParamDecl(0)->getType();
4994 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4995 S.Context.getTypeSize(ArgType) <=
4996 S.Context.getTypeSize(ParamType)) {
4997 // Found a function, don't need the header hint.
4998 EmitHeaderHint = false;
4999 break;
5000 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005001 }
Richard Trieubeffb832014-04-15 23:47:53 +00005002 }
5003 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005004 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005005 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5006
5007 if (HeaderName) {
5008 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5009 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5010 R.suppressDiagnostics();
5011 S.LookupName(R, S.getCurScope());
5012
5013 if (R.isSingleResult()) {
5014 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5015 if (FD && FD->getBuiltinID() == AbsKind) {
5016 EmitHeaderHint = false;
5017 } else {
5018 return;
5019 }
5020 } else if (!R.empty()) {
5021 return;
5022 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005023 }
5024 }
5025
5026 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005027 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005028
Richard Trieubeffb832014-04-15 23:47:53 +00005029 if (!HeaderName)
5030 return;
5031
5032 if (!EmitHeaderHint)
5033 return;
5034
Alp Toker5d96e0a2014-07-11 20:53:51 +00005035 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5036 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005037}
5038
5039static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5040 if (!FDecl)
5041 return false;
5042
5043 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5044 return false;
5045
5046 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5047
5048 while (ND && ND->isInlineNamespace()) {
5049 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005050 }
Richard Trieubeffb832014-04-15 23:47:53 +00005051
5052 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5053 return false;
5054
5055 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5056 return false;
5057
5058 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005059}
5060
5061// Warn when using the wrong abs() function.
5062void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5063 const FunctionDecl *FDecl,
5064 IdentifierInfo *FnInfo) {
5065 if (Call->getNumArgs() != 1)
5066 return;
5067
5068 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005069 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5070 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005071 return;
5072
5073 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5074 QualType ParamType = Call->getArg(0)->getType();
5075
Alp Toker5d96e0a2014-07-11 20:53:51 +00005076 // Unsigned types cannot be negative. Suggest removing the absolute value
5077 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005078 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005079 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005080 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005081 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5082 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005083 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005084 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5085 return;
5086 }
5087
Richard Trieubeffb832014-04-15 23:47:53 +00005088 // std::abs has overloads which prevent most of the absolute value problems
5089 // from occurring.
5090 if (IsStdAbs)
5091 return;
5092
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005093 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5094 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5095
5096 // The argument and parameter are the same kind. Check if they are the right
5097 // size.
5098 if (ArgValueKind == ParamValueKind) {
5099 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5100 return;
5101
5102 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5103 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5104 << FDecl << ArgType << ParamType;
5105
5106 if (NewAbsKind == 0)
5107 return;
5108
5109 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005110 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005111 return;
5112 }
5113
5114 // ArgValueKind != ParamValueKind
5115 // The wrong type of absolute value function was used. Attempt to find the
5116 // proper one.
5117 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5118 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5119 if (NewAbsKind == 0)
5120 return;
5121
5122 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5123 << FDecl << ParamValueKind << ArgValueKind;
5124
5125 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005126 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005127 return;
5128}
5129
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005130//===--- CHECK: Standard memory functions ---------------------------------===//
5131
Nico Weber0e6daef2013-12-26 23:38:39 +00005132/// \brief Takes the expression passed to the size_t parameter of functions
5133/// such as memcmp, strncat, etc and warns if it's a comparison.
5134///
5135/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5136static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5137 IdentifierInfo *FnName,
5138 SourceLocation FnLoc,
5139 SourceLocation RParenLoc) {
5140 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5141 if (!Size)
5142 return false;
5143
5144 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5145 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5146 return false;
5147
Nico Weber0e6daef2013-12-26 23:38:39 +00005148 SourceRange SizeRange = Size->getSourceRange();
5149 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5150 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005151 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005152 << FnName << FixItHint::CreateInsertion(
5153 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005154 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005155 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005156 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005157 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5158 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005159
5160 return true;
5161}
5162
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005163/// \brief Determine whether the given type is or contains a dynamic class type
5164/// (e.g., whether it has a vtable).
5165static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5166 bool &IsContained) {
5167 // Look through array types while ignoring qualifiers.
5168 const Type *Ty = T->getBaseElementTypeUnsafe();
5169 IsContained = false;
5170
5171 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5172 RD = RD ? RD->getDefinition() : nullptr;
5173 if (!RD)
5174 return nullptr;
5175
5176 if (RD->isDynamicClass())
5177 return RD;
5178
5179 // Check all the fields. If any bases were dynamic, the class is dynamic.
5180 // It's impossible for a class to transitively contain itself by value, so
5181 // infinite recursion is impossible.
5182 for (auto *FD : RD->fields()) {
5183 bool SubContained;
5184 if (const CXXRecordDecl *ContainedRD =
5185 getContainedDynamicClass(FD->getType(), SubContained)) {
5186 IsContained = true;
5187 return ContainedRD;
5188 }
5189 }
5190
5191 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005192}
5193
Chandler Carruth889ed862011-06-21 23:04:20 +00005194/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005195/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005196static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005197 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005198 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5199 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5200 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005201
Craig Topperc3ec1492014-05-26 06:22:03 +00005202 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005203}
5204
Chandler Carruth889ed862011-06-21 23:04:20 +00005205/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005206static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005207 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5208 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5209 if (SizeOf->getKind() == clang::UETT_SizeOf)
5210 return SizeOf->getTypeOfArgument();
5211
5212 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005213}
5214
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005215/// \brief Check for dangerous or invalid arguments to memset().
5216///
Chandler Carruthac687262011-06-03 06:23:57 +00005217/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005218/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5219/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005220///
5221/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005222void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005223 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005224 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005225 assert(BId != 0);
5226
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005227 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005228 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005229 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005230 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005231 return;
5232
Anna Zaks22122702012-01-17 00:37:07 +00005233 unsigned LastArg = (BId == Builtin::BImemset ||
5234 BId == Builtin::BIstrndup ? 1 : 2);
5235 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005236 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005237
Nico Weber0e6daef2013-12-26 23:38:39 +00005238 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5239 Call->getLocStart(), Call->getRParenLoc()))
5240 return;
5241
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005242 // We have special checking when the length is a sizeof expression.
5243 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5244 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5245 llvm::FoldingSetNodeID SizeOfArgID;
5246
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005247 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5248 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005249 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005250
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005251 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005252 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005253 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005254 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005255
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005256 // Never warn about void type pointers. This can be used to suppress
5257 // false positives.
5258 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005259 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005260
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005261 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5262 // actually comparing the expressions for equality. Because computing the
5263 // expression IDs can be expensive, we only do this if the diagnostic is
5264 // enabled.
5265 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005266 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5267 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005268 // We only compute IDs for expressions if the warning is enabled, and
5269 // cache the sizeof arg's ID.
5270 if (SizeOfArgID == llvm::FoldingSetNodeID())
5271 SizeOfArg->Profile(SizeOfArgID, Context, true);
5272 llvm::FoldingSetNodeID DestID;
5273 Dest->Profile(DestID, Context, true);
5274 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005275 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5276 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005277 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005278 StringRef ReadableName = FnName->getName();
5279
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005280 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005281 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005282 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005283 if (!PointeeTy->isIncompleteType() &&
5284 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005285 ActionIdx = 2; // If the pointee's size is sizeof(char),
5286 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005287
5288 // If the function is defined as a builtin macro, do not show macro
5289 // expansion.
5290 SourceLocation SL = SizeOfArg->getExprLoc();
5291 SourceRange DSR = Dest->getSourceRange();
5292 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005293 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005294
5295 if (SM.isMacroArgExpansion(SL)) {
5296 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5297 SL = SM.getSpellingLoc(SL);
5298 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5299 SM.getSpellingLoc(DSR.getEnd()));
5300 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5301 SM.getSpellingLoc(SSR.getEnd()));
5302 }
5303
Anna Zaksd08d9152012-05-30 23:14:52 +00005304 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005305 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005306 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005307 << PointeeTy
5308 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005309 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005310 << SSR);
5311 DiagRuntimeBehavior(SL, SizeOfArg,
5312 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5313 << ActionIdx
5314 << SSR);
5315
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005316 break;
5317 }
5318 }
5319
5320 // Also check for cases where the sizeof argument is the exact same
5321 // type as the memory argument, and where it points to a user-defined
5322 // record type.
5323 if (SizeOfArgTy != QualType()) {
5324 if (PointeeTy->isRecordType() &&
5325 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5326 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5327 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5328 << FnName << SizeOfArgTy << ArgIdx
5329 << PointeeTy << Dest->getSourceRange()
5330 << LenExpr->getSourceRange());
5331 break;
5332 }
Nico Weberc5e73862011-06-14 16:14:58 +00005333 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005334 } else if (DestTy->isArrayType()) {
5335 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005336 }
Nico Weberc5e73862011-06-14 16:14:58 +00005337
Nico Weberc44b35e2015-03-21 17:37:46 +00005338 if (PointeeTy == QualType())
5339 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005340
Nico Weberc44b35e2015-03-21 17:37:46 +00005341 // Always complain about dynamic classes.
5342 bool IsContained;
5343 if (const CXXRecordDecl *ContainedRD =
5344 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005345
Nico Weberc44b35e2015-03-21 17:37:46 +00005346 unsigned OperationType = 0;
5347 // "overwritten" if we're warning about the destination for any call
5348 // but memcmp; otherwise a verb appropriate to the call.
5349 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5350 if (BId == Builtin::BImemcpy)
5351 OperationType = 1;
5352 else if(BId == Builtin::BImemmove)
5353 OperationType = 2;
5354 else if (BId == Builtin::BImemcmp)
5355 OperationType = 3;
5356 }
5357
John McCall31168b02011-06-15 23:02:42 +00005358 DiagRuntimeBehavior(
5359 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005360 PDiag(diag::warn_dyn_class_memaccess)
5361 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5362 << FnName << IsContained << ContainedRD << OperationType
5363 << Call->getCallee()->getSourceRange());
5364 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5365 BId != Builtin::BImemset)
5366 DiagRuntimeBehavior(
5367 Dest->getExprLoc(), Dest,
5368 PDiag(diag::warn_arc_object_memaccess)
5369 << ArgIdx << FnName << PointeeTy
5370 << Call->getCallee()->getSourceRange());
5371 else
5372 continue;
5373
5374 DiagRuntimeBehavior(
5375 Dest->getExprLoc(), Dest,
5376 PDiag(diag::note_bad_memaccess_silence)
5377 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5378 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005379 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005380
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005381}
5382
Ted Kremenek6865f772011-08-18 20:55:45 +00005383// A little helper routine: ignore addition and subtraction of integer literals.
5384// This intentionally does not ignore all integer constant expressions because
5385// we don't want to remove sizeof().
5386static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5387 Ex = Ex->IgnoreParenCasts();
5388
5389 for (;;) {
5390 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5391 if (!BO || !BO->isAdditiveOp())
5392 break;
5393
5394 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5395 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5396
5397 if (isa<IntegerLiteral>(RHS))
5398 Ex = LHS;
5399 else if (isa<IntegerLiteral>(LHS))
5400 Ex = RHS;
5401 else
5402 break;
5403 }
5404
5405 return Ex;
5406}
5407
Anna Zaks13b08572012-08-08 21:42:23 +00005408static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5409 ASTContext &Context) {
5410 // Only handle constant-sized or VLAs, but not flexible members.
5411 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5412 // Only issue the FIXIT for arrays of size > 1.
5413 if (CAT->getSize().getSExtValue() <= 1)
5414 return false;
5415 } else if (!Ty->isVariableArrayType()) {
5416 return false;
5417 }
5418 return true;
5419}
5420
Ted Kremenek6865f772011-08-18 20:55:45 +00005421// Warn if the user has made the 'size' argument to strlcpy or strlcat
5422// be the size of the source, instead of the destination.
5423void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5424 IdentifierInfo *FnName) {
5425
5426 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005427 unsigned NumArgs = Call->getNumArgs();
5428 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005429 return;
5430
5431 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5432 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005433 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005434
5435 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5436 Call->getLocStart(), Call->getRParenLoc()))
5437 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005438
5439 // Look for 'strlcpy(dst, x, sizeof(x))'
5440 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5441 CompareWithSrc = Ex;
5442 else {
5443 // Look for 'strlcpy(dst, x, strlen(x))'
5444 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005445 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5446 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005447 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5448 }
5449 }
5450
5451 if (!CompareWithSrc)
5452 return;
5453
5454 // Determine if the argument to sizeof/strlen is equal to the source
5455 // argument. In principle there's all kinds of things you could do
5456 // here, for instance creating an == expression and evaluating it with
5457 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5458 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5459 if (!SrcArgDRE)
5460 return;
5461
5462 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5463 if (!CompareWithSrcDRE ||
5464 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5465 return;
5466
5467 const Expr *OriginalSizeArg = Call->getArg(2);
5468 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5469 << OriginalSizeArg->getSourceRange() << FnName;
5470
5471 // Output a FIXIT hint if the destination is an array (rather than a
5472 // pointer to an array). This could be enhanced to handle some
5473 // pointers if we know the actual size, like if DstArg is 'array+2'
5474 // we could say 'sizeof(array)-2'.
5475 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005476 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005477 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005478
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005479 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005480 llvm::raw_svector_ostream OS(sizeString);
5481 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005482 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005483 OS << ")";
5484
5485 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5486 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5487 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005488}
5489
Anna Zaks314cd092012-02-01 19:08:57 +00005490/// Check if two expressions refer to the same declaration.
5491static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5492 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5493 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5494 return D1->getDecl() == D2->getDecl();
5495 return false;
5496}
5497
5498static const Expr *getStrlenExprArg(const Expr *E) {
5499 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5500 const FunctionDecl *FD = CE->getDirectCallee();
5501 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005502 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005503 return CE->getArg(0)->IgnoreParenCasts();
5504 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005505 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005506}
5507
5508// Warn on anti-patterns as the 'size' argument to strncat.
5509// The correct size argument should look like following:
5510// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5511void Sema::CheckStrncatArguments(const CallExpr *CE,
5512 IdentifierInfo *FnName) {
5513 // Don't crash if the user has the wrong number of arguments.
5514 if (CE->getNumArgs() < 3)
5515 return;
5516 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5517 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5518 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5519
Nico Weber0e6daef2013-12-26 23:38:39 +00005520 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5521 CE->getRParenLoc()))
5522 return;
5523
Anna Zaks314cd092012-02-01 19:08:57 +00005524 // Identify common expressions, which are wrongly used as the size argument
5525 // to strncat and may lead to buffer overflows.
5526 unsigned PatternType = 0;
5527 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5528 // - sizeof(dst)
5529 if (referToTheSameDecl(SizeOfArg, DstArg))
5530 PatternType = 1;
5531 // - sizeof(src)
5532 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5533 PatternType = 2;
5534 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5535 if (BE->getOpcode() == BO_Sub) {
5536 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5537 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5538 // - sizeof(dst) - strlen(dst)
5539 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5540 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5541 PatternType = 1;
5542 // - sizeof(src) - (anything)
5543 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5544 PatternType = 2;
5545 }
5546 }
5547
5548 if (PatternType == 0)
5549 return;
5550
Anna Zaks5069aa32012-02-03 01:27:37 +00005551 // Generate the diagnostic.
5552 SourceLocation SL = LenArg->getLocStart();
5553 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005554 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005555
5556 // If the function is defined as a builtin macro, do not show macro expansion.
5557 if (SM.isMacroArgExpansion(SL)) {
5558 SL = SM.getSpellingLoc(SL);
5559 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5560 SM.getSpellingLoc(SR.getEnd()));
5561 }
5562
Anna Zaks13b08572012-08-08 21:42:23 +00005563 // Check if the destination is an array (rather than a pointer to an array).
5564 QualType DstTy = DstArg->getType();
5565 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5566 Context);
5567 if (!isKnownSizeArray) {
5568 if (PatternType == 1)
5569 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5570 else
5571 Diag(SL, diag::warn_strncat_src_size) << SR;
5572 return;
5573 }
5574
Anna Zaks314cd092012-02-01 19:08:57 +00005575 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005576 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005577 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005578 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005579
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005580 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005581 llvm::raw_svector_ostream OS(sizeString);
5582 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005583 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005584 OS << ") - ";
5585 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005586 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005587 OS << ") - 1";
5588
Anna Zaks5069aa32012-02-03 01:27:37 +00005589 Diag(SL, diag::note_strncat_wrong_size)
5590 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005591}
5592
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005593//===--- CHECK: Return Address of Stack Variable --------------------------===//
5594
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005595static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5596 Decl *ParentDecl);
5597static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5598 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005599
5600/// CheckReturnStackAddr - Check if a return statement returns the address
5601/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005602static void
5603CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5604 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005605
Craig Topperc3ec1492014-05-26 06:22:03 +00005606 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005607 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005608
5609 // Perform checking for returned stack addresses, local blocks,
5610 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005611 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005612 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005613 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005614 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005615 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005616 }
5617
Craig Topperc3ec1492014-05-26 06:22:03 +00005618 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005619 return; // Nothing suspicious was found.
5620
5621 SourceLocation diagLoc;
5622 SourceRange diagRange;
5623 if (refVars.empty()) {
5624 diagLoc = stackE->getLocStart();
5625 diagRange = stackE->getSourceRange();
5626 } else {
5627 // We followed through a reference variable. 'stackE' contains the
5628 // problematic expression but we will warn at the return statement pointing
5629 // at the reference variable. We will later display the "trail" of
5630 // reference variables using notes.
5631 diagLoc = refVars[0]->getLocStart();
5632 diagRange = refVars[0]->getSourceRange();
5633 }
5634
5635 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005636 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005637 : diag::warn_ret_stack_addr)
5638 << DR->getDecl()->getDeclName() << diagRange;
5639 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005640 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005641 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005642 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005643 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005644 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5645 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005646 << diagRange;
5647 }
5648
5649 // Display the "trail" of reference variables that we followed until we
5650 // found the problematic expression using notes.
5651 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5652 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5653 // If this var binds to another reference var, show the range of the next
5654 // var, otherwise the var binds to the problematic expression, in which case
5655 // show the range of the expression.
5656 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5657 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005658 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5659 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005660 }
5661}
5662
5663/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5664/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005665/// to a location on the stack, a local block, an address of a label, or a
5666/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005667/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005668/// encounter a subexpression that (1) clearly does not lead to one of the
5669/// above problematic expressions (2) is something we cannot determine leads to
5670/// a problematic expression based on such local checking.
5671///
5672/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5673/// the expression that they point to. Such variables are added to the
5674/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005675///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005676/// EvalAddr processes expressions that are pointers that are used as
5677/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005678/// At the base case of the recursion is a check for the above problematic
5679/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005680///
5681/// This implementation handles:
5682///
5683/// * pointer-to-pointer casts
5684/// * implicit conversions from array references to pointers
5685/// * taking the address of fields
5686/// * arbitrary interplay between "&" and "*" operators
5687/// * pointer arithmetic from an address of a stack variable
5688/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005689static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5690 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005691 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005692 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005693
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005694 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005695 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005696 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005697 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005698 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005699
Peter Collingbourne91147592011-04-15 00:35:48 +00005700 E = E->IgnoreParens();
5701
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005702 // Our "symbolic interpreter" is just a dispatch off the currently
5703 // viewed AST node. We then recursively traverse the AST by calling
5704 // EvalAddr and EvalVal appropriately.
5705 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005706 case Stmt::DeclRefExprClass: {
5707 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5708
Richard Smith40f08eb2014-01-30 22:05:38 +00005709 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005710 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005711 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005712
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005713 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5714 // If this is a reference variable, follow through to the expression that
5715 // it points to.
5716 if (V->hasLocalStorage() &&
5717 V->getType()->isReferenceType() && V->hasInit()) {
5718 // Add the reference variable to the "trail".
5719 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005720 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005721 }
5722
Craig Topperc3ec1492014-05-26 06:22:03 +00005723 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005724 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005725
Chris Lattner934edb22007-12-28 05:31:15 +00005726 case Stmt::UnaryOperatorClass: {
5727 // The only unary operator that make sense to handle here
5728 // is AddrOf. All others don't make sense as pointers.
5729 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005730
John McCalle3027922010-08-25 11:45:40 +00005731 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005732 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005733 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005734 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005735 }
Mike Stump11289f42009-09-09 15:08:12 +00005736
Chris Lattner934edb22007-12-28 05:31:15 +00005737 case Stmt::BinaryOperatorClass: {
5738 // Handle pointer arithmetic. All other binary operators are not valid
5739 // in this context.
5740 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005741 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005742
John McCalle3027922010-08-25 11:45:40 +00005743 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005744 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005745
Chris Lattner934edb22007-12-28 05:31:15 +00005746 Expr *Base = B->getLHS();
5747
5748 // Determine which argument is the real pointer base. It could be
5749 // the RHS argument instead of the LHS.
5750 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005751
Chris Lattner934edb22007-12-28 05:31:15 +00005752 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005753 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005754 }
Steve Naroff2752a172008-09-10 19:17:48 +00005755
Chris Lattner934edb22007-12-28 05:31:15 +00005756 // For conditional operators we need to see if either the LHS or RHS are
5757 // valid DeclRefExpr*s. If one of them is valid, we return it.
5758 case Stmt::ConditionalOperatorClass: {
5759 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005760
Chris Lattner934edb22007-12-28 05:31:15 +00005761 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005762 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5763 if (Expr *LHSExpr = C->getLHS()) {
5764 // In C++, we can have a throw-expression, which has 'void' type.
5765 if (!LHSExpr->getType()->isVoidType())
5766 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005767 return LHS;
5768 }
Chris Lattner934edb22007-12-28 05:31:15 +00005769
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005770 // In C++, we can have a throw-expression, which has 'void' type.
5771 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005772 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005773
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005774 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005775 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005776
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005777 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005778 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005779 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005780 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005781
5782 case Stmt::AddrLabelExprClass:
5783 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005784
John McCall28fc7092011-11-10 05:35:25 +00005785 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005786 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5787 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005788
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005789 // For casts, we need to handle conversions from arrays to
5790 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005791 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005792 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005793 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005794 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005795 case Stmt::CXXStaticCastExprClass:
5796 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005797 case Stmt::CXXConstCastExprClass:
5798 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005799 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5800 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005801 case CK_LValueToRValue:
5802 case CK_NoOp:
5803 case CK_BaseToDerived:
5804 case CK_DerivedToBase:
5805 case CK_UncheckedDerivedToBase:
5806 case CK_Dynamic:
5807 case CK_CPointerToObjCPointerCast:
5808 case CK_BlockPointerToObjCPointerCast:
5809 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005810 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005811
5812 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005813 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005814
Richard Trieudadefde2014-07-02 04:39:38 +00005815 case CK_BitCast:
5816 if (SubExpr->getType()->isAnyPointerType() ||
5817 SubExpr->getType()->isBlockPointerType() ||
5818 SubExpr->getType()->isObjCQualifiedIdType())
5819 return EvalAddr(SubExpr, refVars, ParentDecl);
5820 else
5821 return nullptr;
5822
Eli Friedman8195ad72012-02-23 23:04:32 +00005823 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005824 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005825 }
Chris Lattner934edb22007-12-28 05:31:15 +00005826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
Douglas Gregorfe314812011-06-21 17:03:29 +00005828 case Stmt::MaterializeTemporaryExprClass:
5829 if (Expr *Result = EvalAddr(
5830 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005831 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005832 return Result;
5833
5834 return E;
5835
Chris Lattner934edb22007-12-28 05:31:15 +00005836 // Everything else: we simply don't reason about them.
5837 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005838 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005839 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005840}
Mike Stump11289f42009-09-09 15:08:12 +00005841
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005842
5843/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5844/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005845static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5846 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005847do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005848 // We should only be called for evaluating non-pointer expressions, or
5849 // expressions with a pointer type that are not used as references but instead
5850 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005851
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005852 // Our "symbolic interpreter" is just a dispatch off the currently
5853 // viewed AST node. We then recursively traverse the AST by calling
5854 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005855
5856 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005857 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005858 case Stmt::ImplicitCastExprClass: {
5859 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005860 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005861 E = IE->getSubExpr();
5862 continue;
5863 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005864 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005865 }
5866
John McCall28fc7092011-11-10 05:35:25 +00005867 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005868 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005869
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005870 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005871 // When we hit a DeclRefExpr we are looking at code that refers to a
5872 // variable's name. If it's not a reference variable we check if it has
5873 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005874 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005875
Richard Smith40f08eb2014-01-30 22:05:38 +00005876 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005877 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005878 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005879
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005880 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5881 // Check if it refers to itself, e.g. "int& i = i;".
5882 if (V == ParentDecl)
5883 return DR;
5884
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005885 if (V->hasLocalStorage()) {
5886 if (!V->getType()->isReferenceType())
5887 return DR;
5888
5889 // Reference variable, follow through to the expression that
5890 // it points to.
5891 if (V->hasInit()) {
5892 // Add the reference variable to the "trail".
5893 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005894 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005895 }
5896 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005897 }
Mike Stump11289f42009-09-09 15:08:12 +00005898
Craig Topperc3ec1492014-05-26 06:22:03 +00005899 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005900 }
Mike Stump11289f42009-09-09 15:08:12 +00005901
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005902 case Stmt::UnaryOperatorClass: {
5903 // The only unary operator that make sense to handle here
5904 // is Deref. All others don't resolve to a "name." This includes
5905 // handling all sorts of rvalues passed to a unary operator.
5906 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005907
John McCalle3027922010-08-25 11:45:40 +00005908 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005909 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005910
Craig Topperc3ec1492014-05-26 06:22:03 +00005911 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005912 }
Mike Stump11289f42009-09-09 15:08:12 +00005913
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005914 case Stmt::ArraySubscriptExprClass: {
5915 // Array subscripts are potential references to data on the stack. We
5916 // retrieve the DeclRefExpr* for the array variable if it indeed
5917 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005918 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005919 }
Mike Stump11289f42009-09-09 15:08:12 +00005920
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005921 case Stmt::OMPArraySectionExprClass: {
5922 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5923 ParentDecl);
5924 }
5925
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005926 case Stmt::ConditionalOperatorClass: {
5927 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005928 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005929 ConditionalOperator *C = cast<ConditionalOperator>(E);
5930
Anders Carlsson801c5c72007-11-30 19:04:31 +00005931 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005932 if (Expr *LHSExpr = C->getLHS()) {
5933 // In C++, we can have a throw-expression, which has 'void' type.
5934 if (!LHSExpr->getType()->isVoidType())
5935 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5936 return LHS;
5937 }
5938
5939 // In C++, we can have a throw-expression, which has 'void' type.
5940 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005941 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005942
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005943 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005944 }
Mike Stump11289f42009-09-09 15:08:12 +00005945
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005946 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005947 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005948 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005949
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005950 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005951 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005952 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005953
5954 // Check whether the member type is itself a reference, in which case
5955 // we're not going to refer to the member, but to what the member refers to.
5956 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005957 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005958
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005959 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005960 }
Mike Stump11289f42009-09-09 15:08:12 +00005961
Douglas Gregorfe314812011-06-21 17:03:29 +00005962 case Stmt::MaterializeTemporaryExprClass:
5963 if (Expr *Result = EvalVal(
5964 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005965 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005966 return Result;
5967
5968 return E;
5969
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005970 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005971 // Check that we don't return or take the address of a reference to a
5972 // temporary. This is only useful in C++.
5973 if (!E->isTypeDependent() && E->isRValue())
5974 return E;
5975
5976 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005977 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005978 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005979} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005980}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005981
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005982void
5983Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5984 SourceLocation ReturnLoc,
5985 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005986 const AttrVec *Attrs,
5987 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005988 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5989
5990 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005991 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5992 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005993 CheckNonNullExpr(*this, RetValExp))
5994 Diag(ReturnLoc, diag::warn_null_ret)
5995 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005996
5997 // C++11 [basic.stc.dynamic.allocation]p4:
5998 // If an allocation function declared with a non-throwing
5999 // exception-specification fails to allocate storage, it shall return
6000 // a null pointer. Any other allocation function that fails to allocate
6001 // storage shall indicate failure only by throwing an exception [...]
6002 if (FD) {
6003 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6004 if (Op == OO_New || Op == OO_Array_New) {
6005 const FunctionProtoType *Proto
6006 = FD->getType()->castAs<FunctionProtoType>();
6007 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6008 CheckNonNullExpr(*this, RetValExp))
6009 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6010 << FD << getLangOpts().CPlusPlus11;
6011 }
6012 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006013}
6014
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006015//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6016
6017/// Check for comparisons of floating point operands using != and ==.
6018/// Issue a warning if these are no self-comparisons, as they are not likely
6019/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006020void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006021 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6022 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006023
6024 // Special case: check for x == x (which is OK).
6025 // Do not emit warnings for such cases.
6026 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6027 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6028 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006029 return;
Mike Stump11289f42009-09-09 15:08:12 +00006030
6031
Ted Kremenekeda40e22007-11-29 00:59:04 +00006032 // Special case: check for comparisons against literals that can be exactly
6033 // represented by APFloat. In such cases, do not emit a warning. This
6034 // is a heuristic: often comparison against such literals are used to
6035 // detect if a value in a variable has not changed. This clearly can
6036 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006037 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6038 if (FLL->isExact())
6039 return;
6040 } else
6041 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6042 if (FLR->isExact())
6043 return;
Mike Stump11289f42009-09-09 15:08:12 +00006044
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006045 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006046 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006047 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006048 return;
Mike Stump11289f42009-09-09 15:08:12 +00006049
David Blaikie1f4ff152012-07-16 20:47:22 +00006050 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006051 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006052 return;
Mike Stump11289f42009-09-09 15:08:12 +00006053
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006054 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006055 Diag(Loc, diag::warn_floatingpoint_eq)
6056 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006057}
John McCallca01b222010-01-04 23:21:16 +00006058
John McCall70aa5392010-01-06 05:24:50 +00006059//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6060//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006061
John McCall70aa5392010-01-06 05:24:50 +00006062namespace {
John McCallca01b222010-01-04 23:21:16 +00006063
John McCall70aa5392010-01-06 05:24:50 +00006064/// Structure recording the 'active' range of an integer-valued
6065/// expression.
6066struct IntRange {
6067 /// The number of bits active in the int.
6068 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006069
John McCall70aa5392010-01-06 05:24:50 +00006070 /// True if the int is known not to have negative values.
6071 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006072
John McCall70aa5392010-01-06 05:24:50 +00006073 IntRange(unsigned Width, bool NonNegative)
6074 : Width(Width), NonNegative(NonNegative)
6075 {}
John McCallca01b222010-01-04 23:21:16 +00006076
John McCall817d4af2010-11-10 23:38:19 +00006077 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006078 static IntRange forBoolType() {
6079 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006080 }
6081
John McCall817d4af2010-11-10 23:38:19 +00006082 /// Returns the range of an opaque value of the given integral type.
6083 static IntRange forValueOfType(ASTContext &C, QualType T) {
6084 return forValueOfCanonicalType(C,
6085 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006086 }
6087
John McCall817d4af2010-11-10 23:38:19 +00006088 /// Returns the range of an opaque value of a canonical integral type.
6089 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006090 assert(T->isCanonicalUnqualified());
6091
6092 if (const VectorType *VT = dyn_cast<VectorType>(T))
6093 T = VT->getElementType().getTypePtr();
6094 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6095 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006096 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6097 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006098
David Majnemer6a426652013-06-07 22:07:20 +00006099 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006100 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006101 EnumDecl *Enum = ET->getDecl();
6102 if (!Enum->isCompleteDefinition())
6103 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006104
David Majnemer6a426652013-06-07 22:07:20 +00006105 unsigned NumPositive = Enum->getNumPositiveBits();
6106 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006107
David Majnemer6a426652013-06-07 22:07:20 +00006108 if (NumNegative == 0)
6109 return IntRange(NumPositive, true/*NonNegative*/);
6110 else
6111 return IntRange(std::max(NumPositive + 1, NumNegative),
6112 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006113 }
John McCall70aa5392010-01-06 05:24:50 +00006114
6115 const BuiltinType *BT = cast<BuiltinType>(T);
6116 assert(BT->isInteger());
6117
6118 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6119 }
6120
John McCall817d4af2010-11-10 23:38:19 +00006121 /// Returns the "target" range of a canonical integral type, i.e.
6122 /// the range of values expressible in the type.
6123 ///
6124 /// This matches forValueOfCanonicalType except that enums have the
6125 /// full range of their type, not the range of their enumerators.
6126 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6127 assert(T->isCanonicalUnqualified());
6128
6129 if (const VectorType *VT = dyn_cast<VectorType>(T))
6130 T = VT->getElementType().getTypePtr();
6131 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6132 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006133 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6134 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006135 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006136 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006137
6138 const BuiltinType *BT = cast<BuiltinType>(T);
6139 assert(BT->isInteger());
6140
6141 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6142 }
6143
6144 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006145 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006146 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006147 L.NonNegative && R.NonNegative);
6148 }
6149
John McCall817d4af2010-11-10 23:38:19 +00006150 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006151 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006152 return IntRange(std::min(L.Width, R.Width),
6153 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006154 }
6155};
6156
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006157static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6158 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006159 if (value.isSigned() && value.isNegative())
6160 return IntRange(value.getMinSignedBits(), false);
6161
6162 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006163 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006164
6165 // isNonNegative() just checks the sign bit without considering
6166 // signedness.
6167 return IntRange(value.getActiveBits(), true);
6168}
6169
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006170static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6171 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006172 if (result.isInt())
6173 return GetValueRange(C, result.getInt(), MaxWidth);
6174
6175 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006176 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6177 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6178 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6179 R = IntRange::join(R, El);
6180 }
John McCall70aa5392010-01-06 05:24:50 +00006181 return R;
6182 }
6183
6184 if (result.isComplexInt()) {
6185 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6186 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6187 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006188 }
6189
6190 // This can happen with lossless casts to intptr_t of "based" lvalues.
6191 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006192 // FIXME: The only reason we need to pass the type in here is to get
6193 // the sign right on this one case. It would be nice if APValue
6194 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006195 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006196 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006197}
John McCall70aa5392010-01-06 05:24:50 +00006198
Eli Friedmane6d33952013-07-08 20:20:06 +00006199static QualType GetExprType(Expr *E) {
6200 QualType Ty = E->getType();
6201 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6202 Ty = AtomicRHS->getValueType();
6203 return Ty;
6204}
6205
John McCall70aa5392010-01-06 05:24:50 +00006206/// Pseudo-evaluate the given integer expression, estimating the
6207/// range of values it might take.
6208///
6209/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006210static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006211 E = E->IgnoreParens();
6212
6213 // Try a full evaluation first.
6214 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006215 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006216 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006217
6218 // I think we only want to look through implicit casts here; if the
6219 // user has an explicit widening cast, we should treat the value as
6220 // being of the new, wider type.
6221 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006222 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006223 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6224
Eli Friedmane6d33952013-07-08 20:20:06 +00006225 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006226
John McCalle3027922010-08-25 11:45:40 +00006227 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006228
John McCall70aa5392010-01-06 05:24:50 +00006229 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006230 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006231 return OutputTypeRange;
6232
6233 IntRange SubRange
6234 = GetExprRange(C, CE->getSubExpr(),
6235 std::min(MaxWidth, OutputTypeRange.Width));
6236
6237 // Bail out if the subexpr's range is as wide as the cast type.
6238 if (SubRange.Width >= OutputTypeRange.Width)
6239 return OutputTypeRange;
6240
6241 // Otherwise, we take the smaller width, and we're non-negative if
6242 // either the output type or the subexpr is.
6243 return IntRange(SubRange.Width,
6244 SubRange.NonNegative || OutputTypeRange.NonNegative);
6245 }
6246
6247 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6248 // If we can fold the condition, just take that operand.
6249 bool CondResult;
6250 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6251 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6252 : CO->getFalseExpr(),
6253 MaxWidth);
6254
6255 // Otherwise, conservatively merge.
6256 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6257 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6258 return IntRange::join(L, R);
6259 }
6260
6261 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6262 switch (BO->getOpcode()) {
6263
6264 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006265 case BO_LAnd:
6266 case BO_LOr:
6267 case BO_LT:
6268 case BO_GT:
6269 case BO_LE:
6270 case BO_GE:
6271 case BO_EQ:
6272 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006273 return IntRange::forBoolType();
6274
John McCallc3688382011-07-13 06:35:24 +00006275 // The type of the assignments is the type of the LHS, so the RHS
6276 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006277 case BO_MulAssign:
6278 case BO_DivAssign:
6279 case BO_RemAssign:
6280 case BO_AddAssign:
6281 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006282 case BO_XorAssign:
6283 case BO_OrAssign:
6284 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006285 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006286
John McCallc3688382011-07-13 06:35:24 +00006287 // Simple assignments just pass through the RHS, which will have
6288 // been coerced to the LHS type.
6289 case BO_Assign:
6290 // TODO: bitfields?
6291 return GetExprRange(C, BO->getRHS(), MaxWidth);
6292
John McCall70aa5392010-01-06 05:24:50 +00006293 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006294 case BO_PtrMemD:
6295 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006296 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006297
John McCall2ce81ad2010-01-06 22:07:33 +00006298 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006299 case BO_And:
6300 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006301 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6302 GetExprRange(C, BO->getRHS(), MaxWidth));
6303
John McCall70aa5392010-01-06 05:24:50 +00006304 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006305 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006306 // ...except that we want to treat '1 << (blah)' as logically
6307 // positive. It's an important idiom.
6308 if (IntegerLiteral *I
6309 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6310 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006311 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006312 return IntRange(R.Width, /*NonNegative*/ true);
6313 }
6314 }
6315 // fallthrough
6316
John McCalle3027922010-08-25 11:45:40 +00006317 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006318 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006319
John McCall2ce81ad2010-01-06 22:07:33 +00006320 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006321 case BO_Shr:
6322 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006323 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6324
6325 // If the shift amount is a positive constant, drop the width by
6326 // that much.
6327 llvm::APSInt shift;
6328 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6329 shift.isNonNegative()) {
6330 unsigned zext = shift.getZExtValue();
6331 if (zext >= L.Width)
6332 L.Width = (L.NonNegative ? 0 : 1);
6333 else
6334 L.Width -= zext;
6335 }
6336
6337 return L;
6338 }
6339
6340 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006341 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006342 return GetExprRange(C, BO->getRHS(), MaxWidth);
6343
John McCall2ce81ad2010-01-06 22:07:33 +00006344 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006345 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006346 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006347 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006348 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006349
John McCall51431812011-07-14 22:39:48 +00006350 // The width of a division result is mostly determined by the size
6351 // of the LHS.
6352 case BO_Div: {
6353 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006354 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006355 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6356
6357 // If the divisor is constant, use that.
6358 llvm::APSInt divisor;
6359 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6360 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6361 if (log2 >= L.Width)
6362 L.Width = (L.NonNegative ? 0 : 1);
6363 else
6364 L.Width = std::min(L.Width - log2, MaxWidth);
6365 return L;
6366 }
6367
6368 // Otherwise, just use the LHS's width.
6369 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6370 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6371 }
6372
6373 // The result of a remainder can't be larger than the result of
6374 // either side.
6375 case BO_Rem: {
6376 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006377 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006378 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6379 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6380
6381 IntRange meet = IntRange::meet(L, R);
6382 meet.Width = std::min(meet.Width, MaxWidth);
6383 return meet;
6384 }
6385
6386 // The default behavior is okay for these.
6387 case BO_Mul:
6388 case BO_Add:
6389 case BO_Xor:
6390 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006391 break;
6392 }
6393
John McCall51431812011-07-14 22:39:48 +00006394 // The default case is to treat the operation as if it were closed
6395 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006396 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6397 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6398 return IntRange::join(L, R);
6399 }
6400
6401 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6402 switch (UO->getOpcode()) {
6403 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006404 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006405 return IntRange::forBoolType();
6406
6407 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006408 case UO_Deref:
6409 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006410 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006411
6412 default:
6413 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6414 }
6415 }
6416
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006417 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6418 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6419
John McCalld25db7e2013-05-06 21:39:12 +00006420 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006421 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006422 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006423
Eli Friedmane6d33952013-07-08 20:20:06 +00006424 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006425}
John McCall263a48b2010-01-04 23:31:57 +00006426
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006427static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006428 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006429}
6430
John McCall263a48b2010-01-04 23:31:57 +00006431/// Checks whether the given value, which currently has the given
6432/// source semantics, has the same value when coerced through the
6433/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006434static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6435 const llvm::fltSemantics &Src,
6436 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006437 llvm::APFloat truncated = value;
6438
6439 bool ignored;
6440 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6441 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6442
6443 return truncated.bitwiseIsEqual(value);
6444}
6445
6446/// Checks whether the given value, which currently has the given
6447/// source semantics, has the same value when coerced through the
6448/// target semantics.
6449///
6450/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006451static bool IsSameFloatAfterCast(const APValue &value,
6452 const llvm::fltSemantics &Src,
6453 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006454 if (value.isFloat())
6455 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6456
6457 if (value.isVector()) {
6458 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6459 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6460 return false;
6461 return true;
6462 }
6463
6464 assert(value.isComplexFloat());
6465 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6466 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6467}
6468
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006469static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006470
Ted Kremenek6274be42010-09-23 21:43:44 +00006471static bool IsZero(Sema &S, Expr *E) {
6472 // Suppress cases where we are comparing against an enum constant.
6473 if (const DeclRefExpr *DR =
6474 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6475 if (isa<EnumConstantDecl>(DR->getDecl()))
6476 return false;
6477
6478 // Suppress cases where the '0' value is expanded from a macro.
6479 if (E->getLocStart().isMacroID())
6480 return false;
6481
John McCallcc7e5bf2010-05-06 08:58:33 +00006482 llvm::APSInt Value;
6483 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6484}
6485
John McCall2551c1b2010-10-06 00:25:24 +00006486static bool HasEnumType(Expr *E) {
6487 // Strip off implicit integral promotions.
6488 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006489 if (ICE->getCastKind() != CK_IntegralCast &&
6490 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006491 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006492 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006493 }
6494
6495 return E->getType()->isEnumeralType();
6496}
6497
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006498static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006499 // Disable warning in template instantiations.
6500 if (!S.ActiveTemplateInstantiations.empty())
6501 return;
6502
John McCalle3027922010-08-25 11:45:40 +00006503 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006504 if (E->isValueDependent())
6505 return;
6506
John McCalle3027922010-08-25 11:45:40 +00006507 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006508 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006509 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006510 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006511 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006512 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006513 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006514 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006515 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006516 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006517 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006518 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006519 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006520 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006521 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006522 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6523 }
6524}
6525
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006526static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006527 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006528 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006529 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006530 // Disable warning in template instantiations.
6531 if (!S.ActiveTemplateInstantiations.empty())
6532 return;
6533
Richard Trieu0f097742014-04-04 04:13:47 +00006534 // TODO: Investigate using GetExprRange() to get tighter bounds
6535 // on the bit ranges.
6536 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006537 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006538 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006539 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6540 unsigned OtherWidth = OtherRange.Width;
6541
6542 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6543
Richard Trieu560910c2012-11-14 22:50:24 +00006544 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006545 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006546 return;
6547
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006548 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006549 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006550
Richard Trieu0f097742014-04-04 04:13:47 +00006551 // Used for diagnostic printout.
6552 enum {
6553 LiteralConstant = 0,
6554 CXXBoolLiteralTrue,
6555 CXXBoolLiteralFalse
6556 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006557
Richard Trieu0f097742014-04-04 04:13:47 +00006558 if (!OtherIsBooleanType) {
6559 QualType ConstantT = Constant->getType();
6560 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006561
Richard Trieu0f097742014-04-04 04:13:47 +00006562 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6563 return;
6564 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6565 "comparison with non-integer type");
6566
6567 bool ConstantSigned = ConstantT->isSignedIntegerType();
6568 bool CommonSigned = CommonT->isSignedIntegerType();
6569
6570 bool EqualityOnly = false;
6571
6572 if (CommonSigned) {
6573 // The common type is signed, therefore no signed to unsigned conversion.
6574 if (!OtherRange.NonNegative) {
6575 // Check that the constant is representable in type OtherT.
6576 if (ConstantSigned) {
6577 if (OtherWidth >= Value.getMinSignedBits())
6578 return;
6579 } else { // !ConstantSigned
6580 if (OtherWidth >= Value.getActiveBits() + 1)
6581 return;
6582 }
6583 } else { // !OtherSigned
6584 // Check that the constant is representable in type OtherT.
6585 // Negative values are out of range.
6586 if (ConstantSigned) {
6587 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6588 return;
6589 } else { // !ConstantSigned
6590 if (OtherWidth >= Value.getActiveBits())
6591 return;
6592 }
Richard Trieu560910c2012-11-14 22:50:24 +00006593 }
Richard Trieu0f097742014-04-04 04:13:47 +00006594 } else { // !CommonSigned
6595 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006596 if (OtherWidth >= Value.getActiveBits())
6597 return;
Craig Toppercf360162014-06-18 05:13:11 +00006598 } else { // OtherSigned
6599 assert(!ConstantSigned &&
6600 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006601 // Check to see if the constant is representable in OtherT.
6602 if (OtherWidth > Value.getActiveBits())
6603 return;
6604 // Check to see if the constant is equivalent to a negative value
6605 // cast to CommonT.
6606 if (S.Context.getIntWidth(ConstantT) ==
6607 S.Context.getIntWidth(CommonT) &&
6608 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6609 return;
6610 // The constant value rests between values that OtherT can represent
6611 // after conversion. Relational comparison still works, but equality
6612 // comparisons will be tautological.
6613 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006614 }
6615 }
Richard Trieu0f097742014-04-04 04:13:47 +00006616
6617 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6618
6619 if (op == BO_EQ || op == BO_NE) {
6620 IsTrue = op == BO_NE;
6621 } else if (EqualityOnly) {
6622 return;
6623 } else if (RhsConstant) {
6624 if (op == BO_GT || op == BO_GE)
6625 IsTrue = !PositiveConstant;
6626 else // op == BO_LT || op == BO_LE
6627 IsTrue = PositiveConstant;
6628 } else {
6629 if (op == BO_LT || op == BO_LE)
6630 IsTrue = !PositiveConstant;
6631 else // op == BO_GT || op == BO_GE
6632 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006633 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006634 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006635 // Other isKnownToHaveBooleanValue
6636 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6637 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6638 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6639
6640 static const struct LinkedConditions {
6641 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6642 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6643 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6644 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6645 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6646 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6647
6648 } TruthTable = {
6649 // Constant on LHS. | Constant on RHS. |
6650 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6651 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6652 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6653 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6654 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6655 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6656 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6657 };
6658
6659 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6660
6661 enum ConstantValue ConstVal = Zero;
6662 if (Value.isUnsigned() || Value.isNonNegative()) {
6663 if (Value == 0) {
6664 LiteralOrBoolConstant =
6665 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6666 ConstVal = Zero;
6667 } else if (Value == 1) {
6668 LiteralOrBoolConstant =
6669 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6670 ConstVal = One;
6671 } else {
6672 LiteralOrBoolConstant = LiteralConstant;
6673 ConstVal = GT_One;
6674 }
6675 } else {
6676 ConstVal = LT_Zero;
6677 }
6678
6679 CompareBoolWithConstantResult CmpRes;
6680
6681 switch (op) {
6682 case BO_LT:
6683 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6684 break;
6685 case BO_GT:
6686 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6687 break;
6688 case BO_LE:
6689 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6690 break;
6691 case BO_GE:
6692 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6693 break;
6694 case BO_EQ:
6695 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6696 break;
6697 case BO_NE:
6698 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6699 break;
6700 default:
6701 CmpRes = Unkwn;
6702 break;
6703 }
6704
6705 if (CmpRes == AFals) {
6706 IsTrue = false;
6707 } else if (CmpRes == ATrue) {
6708 IsTrue = true;
6709 } else {
6710 return;
6711 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006712 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006713
6714 // If this is a comparison to an enum constant, include that
6715 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006716 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006717 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6718 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6719
6720 SmallString<64> PrettySourceValue;
6721 llvm::raw_svector_ostream OS(PrettySourceValue);
6722 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006723 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006724 else
6725 OS << Value;
6726
Richard Trieu0f097742014-04-04 04:13:47 +00006727 S.DiagRuntimeBehavior(
6728 E->getOperatorLoc(), E,
6729 S.PDiag(diag::warn_out_of_range_compare)
6730 << OS.str() << LiteralOrBoolConstant
6731 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6732 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006733}
6734
John McCallcc7e5bf2010-05-06 08:58:33 +00006735/// Analyze the operands of the given comparison. Implements the
6736/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006737static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006738 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6739 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006740}
John McCall263a48b2010-01-04 23:31:57 +00006741
John McCallca01b222010-01-04 23:21:16 +00006742/// \brief Implements -Wsign-compare.
6743///
Richard Trieu82402a02011-09-15 21:56:47 +00006744/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006745static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006746 // The type the comparison is being performed in.
6747 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006748
6749 // Only analyze comparison operators where both sides have been converted to
6750 // the same type.
6751 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6752 return AnalyzeImpConvsInComparison(S, E);
6753
6754 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006755 if (E->isValueDependent())
6756 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006757
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006758 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6759 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006760
6761 bool IsComparisonConstant = false;
6762
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006763 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006764 // of 'true' or 'false'.
6765 if (T->isIntegralType(S.Context)) {
6766 llvm::APSInt RHSValue;
6767 bool IsRHSIntegralLiteral =
6768 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6769 llvm::APSInt LHSValue;
6770 bool IsLHSIntegralLiteral =
6771 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6772 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6773 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6774 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6775 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6776 else
6777 IsComparisonConstant =
6778 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006779 } else if (!T->hasUnsignedIntegerRepresentation())
6780 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006781
John McCallcc7e5bf2010-05-06 08:58:33 +00006782 // We don't do anything special if this isn't an unsigned integral
6783 // comparison: we're only interested in integral comparisons, and
6784 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006785 //
6786 // We also don't care about value-dependent expressions or expressions
6787 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006788 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006790
John McCallcc7e5bf2010-05-06 08:58:33 +00006791 // Check to see if one of the (unmodified) operands is of different
6792 // signedness.
6793 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006794 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6795 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006796 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006797 signedOperand = LHS;
6798 unsignedOperand = RHS;
6799 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6800 signedOperand = RHS;
6801 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006802 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006803 CheckTrivialUnsignedComparison(S, E);
6804 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006805 }
6806
John McCallcc7e5bf2010-05-06 08:58:33 +00006807 // Otherwise, calculate the effective range of the signed operand.
6808 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006809
John McCallcc7e5bf2010-05-06 08:58:33 +00006810 // Go ahead and analyze implicit conversions in the operands. Note
6811 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006812 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6813 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006814
John McCallcc7e5bf2010-05-06 08:58:33 +00006815 // If the signed range is non-negative, -Wsign-compare won't fire,
6816 // but we should still check for comparisons which are always true
6817 // or false.
6818 if (signedRange.NonNegative)
6819 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006820
6821 // For (in)equality comparisons, if the unsigned operand is a
6822 // constant which cannot collide with a overflowed signed operand,
6823 // then reinterpreting the signed operand as unsigned will not
6824 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006825 if (E->isEqualityOp()) {
6826 unsigned comparisonWidth = S.Context.getIntWidth(T);
6827 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006828
John McCallcc7e5bf2010-05-06 08:58:33 +00006829 // We should never be unable to prove that the unsigned operand is
6830 // non-negative.
6831 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6832
6833 if (unsignedRange.Width < comparisonWidth)
6834 return;
6835 }
6836
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006837 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6838 S.PDiag(diag::warn_mixed_sign_comparison)
6839 << LHS->getType() << RHS->getType()
6840 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006841}
6842
John McCall1f425642010-11-11 03:21:53 +00006843/// Analyzes an attempt to assign the given value to a bitfield.
6844///
6845/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006846static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6847 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006848 assert(Bitfield->isBitField());
6849 if (Bitfield->isInvalidDecl())
6850 return false;
6851
John McCalldeebbcf2010-11-11 05:33:51 +00006852 // White-list bool bitfields.
6853 if (Bitfield->getType()->isBooleanType())
6854 return false;
6855
Douglas Gregor789adec2011-02-04 13:09:01 +00006856 // Ignore value- or type-dependent expressions.
6857 if (Bitfield->getBitWidth()->isValueDependent() ||
6858 Bitfield->getBitWidth()->isTypeDependent() ||
6859 Init->isValueDependent() ||
6860 Init->isTypeDependent())
6861 return false;
6862
John McCall1f425642010-11-11 03:21:53 +00006863 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6864
Richard Smith5fab0c92011-12-28 19:48:30 +00006865 llvm::APSInt Value;
6866 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006867 return false;
6868
John McCall1f425642010-11-11 03:21:53 +00006869 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006870 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006871
6872 if (OriginalWidth <= FieldWidth)
6873 return false;
6874
Eli Friedmanc267a322012-01-26 23:11:39 +00006875 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006876 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006877 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006878
Eli Friedmanc267a322012-01-26 23:11:39 +00006879 // Check whether the stored value is equal to the original value.
6880 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006881 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006882 return false;
6883
Eli Friedmanc267a322012-01-26 23:11:39 +00006884 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006885 // therefore don't strictly fit into a signed bitfield of width 1.
6886 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006887 return false;
6888
John McCall1f425642010-11-11 03:21:53 +00006889 std::string PrettyValue = Value.toString(10);
6890 std::string PrettyTrunc = TruncatedValue.toString(10);
6891
6892 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6893 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6894 << Init->getSourceRange();
6895
6896 return true;
6897}
6898
John McCalld2a53122010-11-09 23:24:47 +00006899/// Analyze the given simple or compound assignment for warning-worthy
6900/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006901static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006902 // Just recurse on the LHS.
6903 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6904
6905 // We want to recurse on the RHS as normal unless we're assigning to
6906 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006907 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006908 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006909 E->getOperatorLoc())) {
6910 // Recurse, ignoring any implicit conversions on the RHS.
6911 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6912 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006913 }
6914 }
6915
6916 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6917}
6918
John McCall263a48b2010-01-04 23:31:57 +00006919/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006920static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006921 SourceLocation CContext, unsigned diag,
6922 bool pruneControlFlow = false) {
6923 if (pruneControlFlow) {
6924 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6925 S.PDiag(diag)
6926 << SourceType << T << E->getSourceRange()
6927 << SourceRange(CContext));
6928 return;
6929 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006930 S.Diag(E->getExprLoc(), diag)
6931 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6932}
6933
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006934/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006935static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006936 SourceLocation CContext, unsigned diag,
6937 bool pruneControlFlow = false) {
6938 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006939}
6940
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006941/// Diagnose an implicit cast from a literal expression. Does not warn when the
6942/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006943void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6944 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006945 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006946 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006947 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006948 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6949 T->hasUnsignedIntegerRepresentation());
6950 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006951 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006952 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006953 return;
6954
Eli Friedman07185912013-08-29 23:44:43 +00006955 // FIXME: Force the precision of the source value down so we don't print
6956 // digits which are usually useless (we don't really care here if we
6957 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6958 // would automatically print the shortest representation, but it's a bit
6959 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006960 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006961 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6962 precision = (precision * 59 + 195) / 196;
6963 Value.toString(PrettySourceValue, precision);
6964
David Blaikie9b88cc02012-05-15 17:18:27 +00006965 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006966 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6967 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6968 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006969 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006970
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006971 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006972 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6973 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006974}
6975
John McCall18a2c2c2010-11-09 22:22:12 +00006976std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6977 if (!Range.Width) return "0";
6978
6979 llvm::APSInt ValueInRange = Value;
6980 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006981 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006982 return ValueInRange.toString(10);
6983}
6984
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006985static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6986 if (!isa<ImplicitCastExpr>(Ex))
6987 return false;
6988
6989 Expr *InnerE = Ex->IgnoreParenImpCasts();
6990 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6991 const Type *Source =
6992 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6993 if (Target->isDependentType())
6994 return false;
6995
6996 const BuiltinType *FloatCandidateBT =
6997 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6998 const Type *BoolCandidateType = ToBool ? Target : Source;
6999
7000 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7001 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7002}
7003
7004void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7005 SourceLocation CC) {
7006 unsigned NumArgs = TheCall->getNumArgs();
7007 for (unsigned i = 0; i < NumArgs; ++i) {
7008 Expr *CurrA = TheCall->getArg(i);
7009 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7010 continue;
7011
7012 bool IsSwapped = ((i > 0) &&
7013 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7014 IsSwapped |= ((i < (NumArgs - 1)) &&
7015 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7016 if (IsSwapped) {
7017 // Warn on this floating-point to bool conversion.
7018 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7019 CurrA->getType(), CC,
7020 diag::warn_impcast_floating_point_to_bool);
7021 }
7022 }
7023}
7024
Richard Trieu5b993502014-10-15 03:42:06 +00007025static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7026 SourceLocation CC) {
7027 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7028 E->getExprLoc()))
7029 return;
7030
7031 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7032 const Expr::NullPointerConstantKind NullKind =
7033 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7034 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7035 return;
7036
7037 // Return if target type is a safe conversion.
7038 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7039 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7040 return;
7041
7042 SourceLocation Loc = E->getSourceRange().getBegin();
7043
7044 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7045 if (NullKind == Expr::NPCK_GNUNull) {
7046 if (Loc.isMacroID())
7047 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7048 }
7049
7050 // Only warn if the null and context location are in the same macro expansion.
7051 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7052 return;
7053
7054 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7055 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7056 << FixItHint::CreateReplacement(Loc,
7057 S.getFixItZeroLiteralForType(T, Loc));
7058}
7059
Douglas Gregor5054cb02015-07-07 03:58:22 +00007060static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7061 ObjCArrayLiteral *ArrayLiteral);
7062static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7063 ObjCDictionaryLiteral *DictionaryLiteral);
7064
7065/// Check a single element within a collection literal against the
7066/// target element type.
7067static void checkObjCCollectionLiteralElement(Sema &S,
7068 QualType TargetElementType,
7069 Expr *Element,
7070 unsigned ElementKind) {
7071 // Skip a bitcast to 'id' or qualified 'id'.
7072 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7073 if (ICE->getCastKind() == CK_BitCast &&
7074 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7075 Element = ICE->getSubExpr();
7076 }
7077
7078 QualType ElementType = Element->getType();
7079 ExprResult ElementResult(Element);
7080 if (ElementType->getAs<ObjCObjectPointerType>() &&
7081 S.CheckSingleAssignmentConstraints(TargetElementType,
7082 ElementResult,
7083 false, false)
7084 != Sema::Compatible) {
7085 S.Diag(Element->getLocStart(),
7086 diag::warn_objc_collection_literal_element)
7087 << ElementType << ElementKind << TargetElementType
7088 << Element->getSourceRange();
7089 }
7090
7091 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7092 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7093 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7094 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7095}
7096
7097/// Check an Objective-C array literal being converted to the given
7098/// target type.
7099static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7100 ObjCArrayLiteral *ArrayLiteral) {
7101 if (!S.NSArrayDecl)
7102 return;
7103
7104 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7105 if (!TargetObjCPtr)
7106 return;
7107
7108 if (TargetObjCPtr->isUnspecialized() ||
7109 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7110 != S.NSArrayDecl->getCanonicalDecl())
7111 return;
7112
7113 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7114 if (TypeArgs.size() != 1)
7115 return;
7116
7117 QualType TargetElementType = TypeArgs[0];
7118 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7119 checkObjCCollectionLiteralElement(S, TargetElementType,
7120 ArrayLiteral->getElement(I),
7121 0);
7122 }
7123}
7124
7125/// Check an Objective-C dictionary literal being converted to the given
7126/// target type.
7127static void checkObjCDictionaryLiteral(
7128 Sema &S, QualType TargetType,
7129 ObjCDictionaryLiteral *DictionaryLiteral) {
7130 if (!S.NSDictionaryDecl)
7131 return;
7132
7133 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7134 if (!TargetObjCPtr)
7135 return;
7136
7137 if (TargetObjCPtr->isUnspecialized() ||
7138 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7139 != S.NSDictionaryDecl->getCanonicalDecl())
7140 return;
7141
7142 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7143 if (TypeArgs.size() != 2)
7144 return;
7145
7146 QualType TargetKeyType = TypeArgs[0];
7147 QualType TargetObjectType = TypeArgs[1];
7148 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7149 auto Element = DictionaryLiteral->getKeyValueElement(I);
7150 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7151 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7152 }
7153}
7154
John McCallcc7e5bf2010-05-06 08:58:33 +00007155void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007156 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007157 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007158
John McCallcc7e5bf2010-05-06 08:58:33 +00007159 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7160 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7161 if (Source == Target) return;
7162 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007163
Chandler Carruthc22845a2011-07-26 05:40:03 +00007164 // If the conversion context location is invalid don't complain. We also
7165 // don't want to emit a warning if the issue occurs from the expansion of
7166 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7167 // delay this check as long as possible. Once we detect we are in that
7168 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007169 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007170 return;
7171
Richard Trieu021baa32011-09-23 20:10:00 +00007172 // Diagnose implicit casts to bool.
7173 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7174 if (isa<StringLiteral>(E))
7175 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007176 // and expressions, for instance, assert(0 && "error here"), are
7177 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007178 return DiagnoseImpCast(S, E, T, CC,
7179 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007180 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7181 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7182 // This covers the literal expressions that evaluate to Objective-C
7183 // objects.
7184 return DiagnoseImpCast(S, E, T, CC,
7185 diag::warn_impcast_objective_c_literal_to_bool);
7186 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007187 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7188 // Warn on pointer to bool conversion that is always true.
7189 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7190 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007191 }
Richard Trieu021baa32011-09-23 20:10:00 +00007192 }
John McCall263a48b2010-01-04 23:31:57 +00007193
Douglas Gregor5054cb02015-07-07 03:58:22 +00007194 // Check implicit casts from Objective-C collection literals to specialized
7195 // collection types, e.g., NSArray<NSString *> *.
7196 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7197 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7198 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7199 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7200
John McCall263a48b2010-01-04 23:31:57 +00007201 // Strip vector types.
7202 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007203 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007204 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007205 return;
John McCallacf0ee52010-10-08 02:01:28 +00007206 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007207 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007208
7209 // If the vector cast is cast between two vectors of the same size, it is
7210 // a bitcast, not a conversion.
7211 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7212 return;
John McCall263a48b2010-01-04 23:31:57 +00007213
7214 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7215 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7216 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007217 if (auto VecTy = dyn_cast<VectorType>(Target))
7218 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007219
7220 // Strip complex types.
7221 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007222 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007223 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007224 return;
7225
John McCallacf0ee52010-10-08 02:01:28 +00007226 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007227 }
John McCall263a48b2010-01-04 23:31:57 +00007228
7229 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7230 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7231 }
7232
7233 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7234 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7235
7236 // If the source is floating point...
7237 if (SourceBT && SourceBT->isFloatingPoint()) {
7238 // ...and the target is floating point...
7239 if (TargetBT && TargetBT->isFloatingPoint()) {
7240 // ...then warn if we're dropping FP rank.
7241
7242 // Builtin FP kinds are ordered by increasing FP rank.
7243 if (SourceBT->getKind() > TargetBT->getKind()) {
7244 // Don't warn about float constants that are precisely
7245 // representable in the target type.
7246 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007247 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007248 // Value might be a float, a float vector, or a float complex.
7249 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007250 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7251 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007252 return;
7253 }
7254
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007255 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007256 return;
7257
John McCallacf0ee52010-10-08 02:01:28 +00007258 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007259
7260 }
7261 // ... or possibly if we're increasing rank, too
7262 else if (TargetBT->getKind() > SourceBT->getKind()) {
7263 if (S.SourceMgr.isInSystemMacro(CC))
7264 return;
7265
7266 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007267 }
7268 return;
7269 }
7270
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007271 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007272 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007273 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007274 return;
7275
Chandler Carruth22c7a792011-02-17 11:05:49 +00007276 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007277 // We also want to warn on, e.g., "int i = -1.234"
7278 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7279 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7280 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7281
Chandler Carruth016ef402011-04-10 08:36:24 +00007282 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7283 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007284 } else {
7285 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7286 }
7287 }
John McCall263a48b2010-01-04 23:31:57 +00007288
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007289 // If the target is bool, warn if expr is a function or method call.
7290 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7291 isa<CallExpr>(E)) {
7292 // Check last argument of function call to see if it is an
7293 // implicit cast from a type matching the type the result
7294 // is being cast to.
7295 CallExpr *CEx = cast<CallExpr>(E);
7296 unsigned NumArgs = CEx->getNumArgs();
7297 if (NumArgs > 0) {
7298 Expr *LastA = CEx->getArg(NumArgs - 1);
7299 Expr *InnerE = LastA->IgnoreParenImpCasts();
7300 const Type *InnerType =
7301 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7302 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7303 // Warn on this floating-point to bool conversion
7304 DiagnoseImpCast(S, E, T, CC,
7305 diag::warn_impcast_floating_point_to_bool);
7306 }
7307 }
7308 }
John McCall263a48b2010-01-04 23:31:57 +00007309 return;
7310 }
7311
Richard Trieu5b993502014-10-15 03:42:06 +00007312 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007313
David Blaikie9366d2b2012-06-19 21:19:06 +00007314 if (!Source->isIntegerType() || !Target->isIntegerType())
7315 return;
7316
David Blaikie7555b6a2012-05-15 16:56:36 +00007317 // TODO: remove this early return once the false positives for constant->bool
7318 // in templates, macros, etc, are reduced or removed.
7319 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7320 return;
7321
John McCallcc7e5bf2010-05-06 08:58:33 +00007322 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007323 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007324
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007325 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007326 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007327 // TODO: this should happen for bitfield stores, too.
7328 llvm::APSInt Value(32);
7329 if (E->isIntegerConstantExpr(Value, S.Context)) {
7330 if (S.SourceMgr.isInSystemMacro(CC))
7331 return;
7332
John McCall18a2c2c2010-11-09 22:22:12 +00007333 std::string PrettySourceValue = Value.toString(10);
7334 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007335
Ted Kremenek33ba9952011-10-22 02:37:33 +00007336 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7337 S.PDiag(diag::warn_impcast_integer_precision_constant)
7338 << PrettySourceValue << PrettyTargetValue
7339 << E->getType() << T << E->getSourceRange()
7340 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007341 return;
7342 }
7343
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007344 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7345 if (S.SourceMgr.isInSystemMacro(CC))
7346 return;
7347
David Blaikie9455da02012-04-12 22:40:54 +00007348 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007349 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7350 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007351 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007352 }
7353
7354 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7355 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7356 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007357
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007358 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007359 return;
7360
John McCallcc7e5bf2010-05-06 08:58:33 +00007361 unsigned DiagID = diag::warn_impcast_integer_sign;
7362
7363 // Traditionally, gcc has warned about this under -Wsign-compare.
7364 // We also want to warn about it in -Wconversion.
7365 // So if -Wconversion is off, use a completely identical diagnostic
7366 // in the sign-compare group.
7367 // The conditional-checking code will
7368 if (ICContext) {
7369 DiagID = diag::warn_impcast_integer_sign_conditional;
7370 *ICContext = true;
7371 }
7372
John McCallacf0ee52010-10-08 02:01:28 +00007373 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007374 }
7375
Douglas Gregora78f1932011-02-22 02:45:07 +00007376 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007377 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7378 // type, to give us better diagnostics.
7379 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007380 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007381 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7382 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7383 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7384 SourceType = S.Context.getTypeDeclType(Enum);
7385 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7386 }
7387 }
7388
Douglas Gregora78f1932011-02-22 02:45:07 +00007389 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7390 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007391 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7392 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007393 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007394 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007395 return;
7396
Douglas Gregor364f7db2011-03-12 00:14:31 +00007397 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007398 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007399 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007400
John McCall263a48b2010-01-04 23:31:57 +00007401 return;
7402}
7403
David Blaikie18e9ac72012-05-15 21:57:38 +00007404void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7405 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007406
7407void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007408 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007409 E = E->IgnoreParenImpCasts();
7410
7411 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007412 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007413
John McCallacf0ee52010-10-08 02:01:28 +00007414 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007415 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007416 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007417 return;
7418}
7419
David Blaikie18e9ac72012-05-15 21:57:38 +00007420void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7421 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007422 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007423
7424 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007425 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7426 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007427
7428 // If -Wconversion would have warned about either of the candidates
7429 // for a signedness conversion to the context type...
7430 if (!Suspicious) return;
7431
7432 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007433 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007434 return;
7435
John McCallcc7e5bf2010-05-06 08:58:33 +00007436 // ...then check whether it would have warned about either of the
7437 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007438 if (E->getType() == T) return;
7439
7440 Suspicious = false;
7441 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7442 E->getType(), CC, &Suspicious);
7443 if (!Suspicious)
7444 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007445 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007446}
7447
Richard Trieu65724892014-11-15 06:37:39 +00007448/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7449/// Input argument E is a logical expression.
7450static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7451 if (S.getLangOpts().Bool)
7452 return;
7453 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7454}
7455
John McCallcc7e5bf2010-05-06 08:58:33 +00007456/// AnalyzeImplicitConversions - Find and report any interesting
7457/// implicit conversions in the given expression. There are a couple
7458/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007459void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007460 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007461 Expr *E = OrigE->IgnoreParenImpCasts();
7462
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007463 if (E->isTypeDependent() || E->isValueDependent())
7464 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007465
John McCallcc7e5bf2010-05-06 08:58:33 +00007466 // For conditional operators, we analyze the arguments as if they
7467 // were being fed directly into the output.
7468 if (isa<ConditionalOperator>(E)) {
7469 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007470 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007471 return;
7472 }
7473
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007474 // Check implicit argument conversions for function calls.
7475 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7476 CheckImplicitArgumentConversions(S, Call, CC);
7477
John McCallcc7e5bf2010-05-06 08:58:33 +00007478 // Go ahead and check any implicit conversions we might have skipped.
7479 // The non-canonical typecheck is just an optimization;
7480 // CheckImplicitConversion will filter out dead implicit conversions.
7481 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007482 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007483
7484 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007485
7486 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007487 if (POE->getResultExpr())
7488 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007489 }
7490
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007491 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7492 if (OVE->getSourceExpr())
7493 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7494 return;
7495 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007496
John McCallcc7e5bf2010-05-06 08:58:33 +00007497 // Skip past explicit casts.
7498 if (isa<ExplicitCastExpr>(E)) {
7499 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007500 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007501 }
7502
John McCalld2a53122010-11-09 23:24:47 +00007503 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7504 // Do a somewhat different check with comparison operators.
7505 if (BO->isComparisonOp())
7506 return AnalyzeComparison(S, BO);
7507
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007508 // And with simple assignments.
7509 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007510 return AnalyzeAssignment(S, BO);
7511 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007512
7513 // These break the otherwise-useful invariant below. Fortunately,
7514 // we don't really need to recurse into them, because any internal
7515 // expressions should have been analyzed already when they were
7516 // built into statements.
7517 if (isa<StmtExpr>(E)) return;
7518
7519 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007520 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007521
7522 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007523 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007524 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007525 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007526 for (Stmt *SubStmt : E->children()) {
7527 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007528 if (!ChildExpr)
7529 continue;
7530
Richard Trieu955231d2014-01-25 01:10:35 +00007531 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007532 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007533 // Ignore checking string literals that are in logical and operators.
7534 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007535 continue;
7536 AnalyzeImplicitConversions(S, ChildExpr, CC);
7537 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007538
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007539 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007540 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7541 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007542 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007543
7544 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7545 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007546 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007547 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007548
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007549 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7550 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007551 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007552}
7553
7554} // end anonymous namespace
7555
Richard Trieu3bb8b562014-02-26 02:36:06 +00007556enum {
7557 AddressOf,
7558 FunctionPointer,
7559 ArrayPointer
7560};
7561
Richard Trieuc1888e02014-06-28 23:25:37 +00007562// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7563// Returns true when emitting a warning about taking the address of a reference.
7564static bool CheckForReference(Sema &SemaRef, const Expr *E,
7565 PartialDiagnostic PD) {
7566 E = E->IgnoreParenImpCasts();
7567
7568 const FunctionDecl *FD = nullptr;
7569
7570 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7571 if (!DRE->getDecl()->getType()->isReferenceType())
7572 return false;
7573 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7574 if (!M->getMemberDecl()->getType()->isReferenceType())
7575 return false;
7576 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007577 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007578 return false;
7579 FD = Call->getDirectCallee();
7580 } else {
7581 return false;
7582 }
7583
7584 SemaRef.Diag(E->getExprLoc(), PD);
7585
7586 // If possible, point to location of function.
7587 if (FD) {
7588 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7589 }
7590
7591 return true;
7592}
7593
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007594// Returns true if the SourceLocation is expanded from any macro body.
7595// Returns false if the SourceLocation is invalid, is from not in a macro
7596// expansion, or is from expanded from a top-level macro argument.
7597static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7598 if (Loc.isInvalid())
7599 return false;
7600
7601 while (Loc.isMacroID()) {
7602 if (SM.isMacroBodyExpansion(Loc))
7603 return true;
7604 Loc = SM.getImmediateMacroCallerLoc(Loc);
7605 }
7606
7607 return false;
7608}
7609
Richard Trieu3bb8b562014-02-26 02:36:06 +00007610/// \brief Diagnose pointers that are always non-null.
7611/// \param E the expression containing the pointer
7612/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7613/// compared to a null pointer
7614/// \param IsEqual True when the comparison is equal to a null pointer
7615/// \param Range Extra SourceRange to highlight in the diagnostic
7616void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7617 Expr::NullPointerConstantKind NullKind,
7618 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007619 if (!E)
7620 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007621
7622 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007623 if (E->getExprLoc().isMacroID()) {
7624 const SourceManager &SM = getSourceManager();
7625 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7626 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007627 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007628 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007629 E = E->IgnoreImpCasts();
7630
7631 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7632
Richard Trieuf7432752014-06-06 21:39:26 +00007633 if (isa<CXXThisExpr>(E)) {
7634 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7635 : diag::warn_this_bool_conversion;
7636 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7637 return;
7638 }
7639
Richard Trieu3bb8b562014-02-26 02:36:06 +00007640 bool IsAddressOf = false;
7641
7642 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7643 if (UO->getOpcode() != UO_AddrOf)
7644 return;
7645 IsAddressOf = true;
7646 E = UO->getSubExpr();
7647 }
7648
Richard Trieuc1888e02014-06-28 23:25:37 +00007649 if (IsAddressOf) {
7650 unsigned DiagID = IsCompare
7651 ? diag::warn_address_of_reference_null_compare
7652 : diag::warn_address_of_reference_bool_conversion;
7653 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7654 << IsEqual;
7655 if (CheckForReference(*this, E, PD)) {
7656 return;
7657 }
7658 }
7659
Richard Trieu3bb8b562014-02-26 02:36:06 +00007660 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007661 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007662 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7663 D = R->getDecl();
7664 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7665 D = M->getMemberDecl();
7666 }
7667
7668 // Weak Decls can be null.
7669 if (!D || D->isWeak())
7670 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007671
7672 // Check for parameter decl with nonnull attribute
7673 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7674 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7675 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7676 unsigned NumArgs = FD->getNumParams();
7677 llvm::SmallBitVector AttrNonNull(NumArgs);
7678 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7679 if (!NonNull->args_size()) {
7680 AttrNonNull.set(0, NumArgs);
7681 break;
7682 }
7683 for (unsigned Val : NonNull->args()) {
7684 if (Val >= NumArgs)
7685 continue;
7686 AttrNonNull.set(Val);
7687 }
7688 }
7689 if (!AttrNonNull.empty())
7690 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007691 if (FD->getParamDecl(i) == PV &&
7692 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007693 std::string Str;
7694 llvm::raw_string_ostream S(Str);
7695 E->printPretty(S, nullptr, getPrintingPolicy());
7696 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7697 : diag::warn_cast_nonnull_to_bool;
7698 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7699 << Range << IsEqual;
7700 return;
7701 }
7702 }
7703 }
7704
Richard Trieu3bb8b562014-02-26 02:36:06 +00007705 QualType T = D->getType();
7706 const bool IsArray = T->isArrayType();
7707 const bool IsFunction = T->isFunctionType();
7708
Richard Trieuc1888e02014-06-28 23:25:37 +00007709 // Address of function is used to silence the function warning.
7710 if (IsAddressOf && IsFunction) {
7711 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007712 }
7713
7714 // Found nothing.
7715 if (!IsAddressOf && !IsFunction && !IsArray)
7716 return;
7717
7718 // Pretty print the expression for the diagnostic.
7719 std::string Str;
7720 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007721 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007722
7723 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7724 : diag::warn_impcast_pointer_to_bool;
7725 unsigned DiagType;
7726 if (IsAddressOf)
7727 DiagType = AddressOf;
7728 else if (IsFunction)
7729 DiagType = FunctionPointer;
7730 else if (IsArray)
7731 DiagType = ArrayPointer;
7732 else
7733 llvm_unreachable("Could not determine diagnostic.");
7734 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7735 << Range << IsEqual;
7736
7737 if (!IsFunction)
7738 return;
7739
7740 // Suggest '&' to silence the function warning.
7741 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7742 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7743
7744 // Check to see if '()' fixit should be emitted.
7745 QualType ReturnType;
7746 UnresolvedSet<4> NonTemplateOverloads;
7747 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7748 if (ReturnType.isNull())
7749 return;
7750
7751 if (IsCompare) {
7752 // There are two cases here. If there is null constant, the only suggest
7753 // for a pointer return type. If the null is 0, then suggest if the return
7754 // type is a pointer or an integer type.
7755 if (!ReturnType->isPointerType()) {
7756 if (NullKind == Expr::NPCK_ZeroExpression ||
7757 NullKind == Expr::NPCK_ZeroLiteral) {
7758 if (!ReturnType->isIntegerType())
7759 return;
7760 } else {
7761 return;
7762 }
7763 }
7764 } else { // !IsCompare
7765 // For function to bool, only suggest if the function pointer has bool
7766 // return type.
7767 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7768 return;
7769 }
7770 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007771 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007772}
7773
7774
John McCallcc7e5bf2010-05-06 08:58:33 +00007775/// Diagnoses "dangerous" implicit conversions within the given
7776/// expression (which is a full expression). Implements -Wconversion
7777/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007778///
7779/// \param CC the "context" location of the implicit conversion, i.e.
7780/// the most location of the syntactic entity requiring the implicit
7781/// conversion
7782void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007783 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007784 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007785 return;
7786
7787 // Don't diagnose for value- or type-dependent expressions.
7788 if (E->isTypeDependent() || E->isValueDependent())
7789 return;
7790
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007791 // Check for array bounds violations in cases where the check isn't triggered
7792 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7793 // ArraySubscriptExpr is on the RHS of a variable initialization.
7794 CheckArrayAccess(E);
7795
John McCallacf0ee52010-10-08 02:01:28 +00007796 // This is not the right CC for (e.g.) a variable initialization.
7797 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007798}
7799
Richard Trieu65724892014-11-15 06:37:39 +00007800/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7801/// Input argument E is a logical expression.
7802void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7803 ::CheckBoolLikeConversion(*this, E, CC);
7804}
7805
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007806/// Diagnose when expression is an integer constant expression and its evaluation
7807/// results in integer overflow
7808void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007809 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7810 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007811}
7812
Richard Smithc406cb72013-01-17 01:17:56 +00007813namespace {
7814/// \brief Visitor for expressions which looks for unsequenced operations on the
7815/// same object.
7816class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007817 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7818
Richard Smithc406cb72013-01-17 01:17:56 +00007819 /// \brief A tree of sequenced regions within an expression. Two regions are
7820 /// unsequenced if one is an ancestor or a descendent of the other. When we
7821 /// finish processing an expression with sequencing, such as a comma
7822 /// expression, we fold its tree nodes into its parent, since they are
7823 /// unsequenced with respect to nodes we will visit later.
7824 class SequenceTree {
7825 struct Value {
7826 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7827 unsigned Parent : 31;
7828 bool Merged : 1;
7829 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007830 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007831
7832 public:
7833 /// \brief A region within an expression which may be sequenced with respect
7834 /// to some other region.
7835 class Seq {
7836 explicit Seq(unsigned N) : Index(N) {}
7837 unsigned Index;
7838 friend class SequenceTree;
7839 public:
7840 Seq() : Index(0) {}
7841 };
7842
7843 SequenceTree() { Values.push_back(Value(0)); }
7844 Seq root() const { return Seq(0); }
7845
7846 /// \brief Create a new sequence of operations, which is an unsequenced
7847 /// subset of \p Parent. This sequence of operations is sequenced with
7848 /// respect to other children of \p Parent.
7849 Seq allocate(Seq Parent) {
7850 Values.push_back(Value(Parent.Index));
7851 return Seq(Values.size() - 1);
7852 }
7853
7854 /// \brief Merge a sequence of operations into its parent.
7855 void merge(Seq S) {
7856 Values[S.Index].Merged = true;
7857 }
7858
7859 /// \brief Determine whether two operations are unsequenced. This operation
7860 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7861 /// should have been merged into its parent as appropriate.
7862 bool isUnsequenced(Seq Cur, Seq Old) {
7863 unsigned C = representative(Cur.Index);
7864 unsigned Target = representative(Old.Index);
7865 while (C >= Target) {
7866 if (C == Target)
7867 return true;
7868 C = Values[C].Parent;
7869 }
7870 return false;
7871 }
7872
7873 private:
7874 /// \brief Pick a representative for a sequence.
7875 unsigned representative(unsigned K) {
7876 if (Values[K].Merged)
7877 // Perform path compression as we go.
7878 return Values[K].Parent = representative(Values[K].Parent);
7879 return K;
7880 }
7881 };
7882
7883 /// An object for which we can track unsequenced uses.
7884 typedef NamedDecl *Object;
7885
7886 /// Different flavors of object usage which we track. We only track the
7887 /// least-sequenced usage of each kind.
7888 enum UsageKind {
7889 /// A read of an object. Multiple unsequenced reads are OK.
7890 UK_Use,
7891 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007892 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007893 UK_ModAsValue,
7894 /// A modification of an object which is not sequenced before the value
7895 /// computation of the expression, such as n++.
7896 UK_ModAsSideEffect,
7897
7898 UK_Count = UK_ModAsSideEffect + 1
7899 };
7900
7901 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007902 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007903 Expr *Use;
7904 SequenceTree::Seq Seq;
7905 };
7906
7907 struct UsageInfo {
7908 UsageInfo() : Diagnosed(false) {}
7909 Usage Uses[UK_Count];
7910 /// Have we issued a diagnostic for this variable already?
7911 bool Diagnosed;
7912 };
7913 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7914
7915 Sema &SemaRef;
7916 /// Sequenced regions within the expression.
7917 SequenceTree Tree;
7918 /// Declaration modifications and references which we have seen.
7919 UsageInfoMap UsageMap;
7920 /// The region we are currently within.
7921 SequenceTree::Seq Region;
7922 /// Filled in with declarations which were modified as a side-effect
7923 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007924 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007925 /// Expressions to check later. We defer checking these to reduce
7926 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007927 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007928
7929 /// RAII object wrapping the visitation of a sequenced subexpression of an
7930 /// expression. At the end of this process, the side-effects of the evaluation
7931 /// become sequenced with respect to the value computation of the result, so
7932 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7933 /// UK_ModAsValue.
7934 struct SequencedSubexpression {
7935 SequencedSubexpression(SequenceChecker &Self)
7936 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7937 Self.ModAsSideEffect = &ModAsSideEffect;
7938 }
7939 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007940 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7941 MI != ME; ++MI) {
7942 UsageInfo &U = Self.UsageMap[MI->first];
7943 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7944 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7945 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007946 }
7947 Self.ModAsSideEffect = OldModAsSideEffect;
7948 }
7949
7950 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007951 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7952 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007953 };
7954
Richard Smith40238f02013-06-20 22:21:56 +00007955 /// RAII object wrapping the visitation of a subexpression which we might
7956 /// choose to evaluate as a constant. If any subexpression is evaluated and
7957 /// found to be non-constant, this allows us to suppress the evaluation of
7958 /// the outer expression.
7959 class EvaluationTracker {
7960 public:
7961 EvaluationTracker(SequenceChecker &Self)
7962 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7963 Self.EvalTracker = this;
7964 }
7965 ~EvaluationTracker() {
7966 Self.EvalTracker = Prev;
7967 if (Prev)
7968 Prev->EvalOK &= EvalOK;
7969 }
7970
7971 bool evaluate(const Expr *E, bool &Result) {
7972 if (!EvalOK || E->isValueDependent())
7973 return false;
7974 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7975 return EvalOK;
7976 }
7977
7978 private:
7979 SequenceChecker &Self;
7980 EvaluationTracker *Prev;
7981 bool EvalOK;
7982 } *EvalTracker;
7983
Richard Smithc406cb72013-01-17 01:17:56 +00007984 /// \brief Find the object which is produced by the specified expression,
7985 /// if any.
7986 Object getObject(Expr *E, bool Mod) const {
7987 E = E->IgnoreParenCasts();
7988 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7989 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7990 return getObject(UO->getSubExpr(), Mod);
7991 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7992 if (BO->getOpcode() == BO_Comma)
7993 return getObject(BO->getRHS(), Mod);
7994 if (Mod && BO->isAssignmentOp())
7995 return getObject(BO->getLHS(), Mod);
7996 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7997 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7998 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7999 return ME->getMemberDecl();
8000 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8001 // FIXME: If this is a reference, map through to its value.
8002 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008003 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008004 }
8005
8006 /// \brief Note that an object was modified or used by an expression.
8007 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8008 Usage &U = UI.Uses[UK];
8009 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8010 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8011 ModAsSideEffect->push_back(std::make_pair(O, U));
8012 U.Use = Ref;
8013 U.Seq = Region;
8014 }
8015 }
8016 /// \brief Check whether a modification or use conflicts with a prior usage.
8017 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8018 bool IsModMod) {
8019 if (UI.Diagnosed)
8020 return;
8021
8022 const Usage &U = UI.Uses[OtherKind];
8023 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8024 return;
8025
8026 Expr *Mod = U.Use;
8027 Expr *ModOrUse = Ref;
8028 if (OtherKind == UK_Use)
8029 std::swap(Mod, ModOrUse);
8030
8031 SemaRef.Diag(Mod->getExprLoc(),
8032 IsModMod ? diag::warn_unsequenced_mod_mod
8033 : diag::warn_unsequenced_mod_use)
8034 << O << SourceRange(ModOrUse->getExprLoc());
8035 UI.Diagnosed = true;
8036 }
8037
8038 void notePreUse(Object O, Expr *Use) {
8039 UsageInfo &U = UsageMap[O];
8040 // Uses conflict with other modifications.
8041 checkUsage(O, U, Use, UK_ModAsValue, false);
8042 }
8043 void notePostUse(Object O, Expr *Use) {
8044 UsageInfo &U = UsageMap[O];
8045 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8046 addUsage(U, O, Use, UK_Use);
8047 }
8048
8049 void notePreMod(Object O, Expr *Mod) {
8050 UsageInfo &U = UsageMap[O];
8051 // Modifications conflict with other modifications and with uses.
8052 checkUsage(O, U, Mod, UK_ModAsValue, true);
8053 checkUsage(O, U, Mod, UK_Use, false);
8054 }
8055 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8056 UsageInfo &U = UsageMap[O];
8057 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8058 addUsage(U, O, Use, UK);
8059 }
8060
8061public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008062 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008063 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8064 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008065 Visit(E);
8066 }
8067
8068 void VisitStmt(Stmt *S) {
8069 // Skip all statements which aren't expressions for now.
8070 }
8071
8072 void VisitExpr(Expr *E) {
8073 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008074 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008075 }
8076
8077 void VisitCastExpr(CastExpr *E) {
8078 Object O = Object();
8079 if (E->getCastKind() == CK_LValueToRValue)
8080 O = getObject(E->getSubExpr(), false);
8081
8082 if (O)
8083 notePreUse(O, E);
8084 VisitExpr(E);
8085 if (O)
8086 notePostUse(O, E);
8087 }
8088
8089 void VisitBinComma(BinaryOperator *BO) {
8090 // C++11 [expr.comma]p1:
8091 // Every value computation and side effect associated with the left
8092 // expression is sequenced before every value computation and side
8093 // effect associated with the right expression.
8094 SequenceTree::Seq LHS = Tree.allocate(Region);
8095 SequenceTree::Seq RHS = Tree.allocate(Region);
8096 SequenceTree::Seq OldRegion = Region;
8097
8098 {
8099 SequencedSubexpression SeqLHS(*this);
8100 Region = LHS;
8101 Visit(BO->getLHS());
8102 }
8103
8104 Region = RHS;
8105 Visit(BO->getRHS());
8106
8107 Region = OldRegion;
8108
8109 // Forget that LHS and RHS are sequenced. They are both unsequenced
8110 // with respect to other stuff.
8111 Tree.merge(LHS);
8112 Tree.merge(RHS);
8113 }
8114
8115 void VisitBinAssign(BinaryOperator *BO) {
8116 // The modification is sequenced after the value computation of the LHS
8117 // and RHS, so check it before inspecting the operands and update the
8118 // map afterwards.
8119 Object O = getObject(BO->getLHS(), true);
8120 if (!O)
8121 return VisitExpr(BO);
8122
8123 notePreMod(O, BO);
8124
8125 // C++11 [expr.ass]p7:
8126 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8127 // only once.
8128 //
8129 // Therefore, for a compound assignment operator, O is considered used
8130 // everywhere except within the evaluation of E1 itself.
8131 if (isa<CompoundAssignOperator>(BO))
8132 notePreUse(O, BO);
8133
8134 Visit(BO->getLHS());
8135
8136 if (isa<CompoundAssignOperator>(BO))
8137 notePostUse(O, BO);
8138
8139 Visit(BO->getRHS());
8140
Richard Smith83e37bee2013-06-26 23:16:51 +00008141 // C++11 [expr.ass]p1:
8142 // the assignment is sequenced [...] before the value computation of the
8143 // assignment expression.
8144 // C11 6.5.16/3 has no such rule.
8145 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8146 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008147 }
8148 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8149 VisitBinAssign(CAO);
8150 }
8151
8152 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8153 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8154 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8155 Object O = getObject(UO->getSubExpr(), true);
8156 if (!O)
8157 return VisitExpr(UO);
8158
8159 notePreMod(O, UO);
8160 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008161 // C++11 [expr.pre.incr]p1:
8162 // the expression ++x is equivalent to x+=1
8163 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8164 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008165 }
8166
8167 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8168 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8169 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8170 Object O = getObject(UO->getSubExpr(), true);
8171 if (!O)
8172 return VisitExpr(UO);
8173
8174 notePreMod(O, UO);
8175 Visit(UO->getSubExpr());
8176 notePostMod(O, UO, UK_ModAsSideEffect);
8177 }
8178
8179 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8180 void VisitBinLOr(BinaryOperator *BO) {
8181 // The side-effects of the LHS of an '&&' are sequenced before the
8182 // value computation of the RHS, and hence before the value computation
8183 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8184 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008185 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008186 {
8187 SequencedSubexpression Sequenced(*this);
8188 Visit(BO->getLHS());
8189 }
8190
8191 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008192 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008193 if (!Result)
8194 Visit(BO->getRHS());
8195 } else {
8196 // Check for unsequenced operations in the RHS, treating it as an
8197 // entirely separate evaluation.
8198 //
8199 // FIXME: If there are operations in the RHS which are unsequenced
8200 // with respect to operations outside the RHS, and those operations
8201 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008202 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008203 }
Richard Smithc406cb72013-01-17 01:17:56 +00008204 }
8205 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008206 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008207 {
8208 SequencedSubexpression Sequenced(*this);
8209 Visit(BO->getLHS());
8210 }
8211
8212 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008213 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008214 if (Result)
8215 Visit(BO->getRHS());
8216 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008217 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008218 }
Richard Smithc406cb72013-01-17 01:17:56 +00008219 }
8220
8221 // Only visit the condition, unless we can be sure which subexpression will
8222 // be chosen.
8223 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008224 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008225 {
8226 SequencedSubexpression Sequenced(*this);
8227 Visit(CO->getCond());
8228 }
Richard Smithc406cb72013-01-17 01:17:56 +00008229
8230 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008231 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008232 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008233 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008234 WorkList.push_back(CO->getTrueExpr());
8235 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008236 }
Richard Smithc406cb72013-01-17 01:17:56 +00008237 }
8238
Richard Smithe3dbfe02013-06-30 10:40:20 +00008239 void VisitCallExpr(CallExpr *CE) {
8240 // C++11 [intro.execution]p15:
8241 // When calling a function [...], every value computation and side effect
8242 // associated with any argument expression, or with the postfix expression
8243 // designating the called function, is sequenced before execution of every
8244 // expression or statement in the body of the function [and thus before
8245 // the value computation of its result].
8246 SequencedSubexpression Sequenced(*this);
8247 Base::VisitCallExpr(CE);
8248
8249 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8250 }
8251
Richard Smithc406cb72013-01-17 01:17:56 +00008252 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008253 // This is a call, so all subexpressions are sequenced before the result.
8254 SequencedSubexpression Sequenced(*this);
8255
Richard Smithc406cb72013-01-17 01:17:56 +00008256 if (!CCE->isListInitialization())
8257 return VisitExpr(CCE);
8258
8259 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008260 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008261 SequenceTree::Seq Parent = Region;
8262 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8263 E = CCE->arg_end();
8264 I != E; ++I) {
8265 Region = Tree.allocate(Parent);
8266 Elts.push_back(Region);
8267 Visit(*I);
8268 }
8269
8270 // Forget that the initializers are sequenced.
8271 Region = Parent;
8272 for (unsigned I = 0; I < Elts.size(); ++I)
8273 Tree.merge(Elts[I]);
8274 }
8275
8276 void VisitInitListExpr(InitListExpr *ILE) {
8277 if (!SemaRef.getLangOpts().CPlusPlus11)
8278 return VisitExpr(ILE);
8279
8280 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008281 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008282 SequenceTree::Seq Parent = Region;
8283 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8284 Expr *E = ILE->getInit(I);
8285 if (!E) continue;
8286 Region = Tree.allocate(Parent);
8287 Elts.push_back(Region);
8288 Visit(E);
8289 }
8290
8291 // Forget that the initializers are sequenced.
8292 Region = Parent;
8293 for (unsigned I = 0; I < Elts.size(); ++I)
8294 Tree.merge(Elts[I]);
8295 }
8296};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008297}
Richard Smithc406cb72013-01-17 01:17:56 +00008298
8299void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008300 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008301 WorkList.push_back(E);
8302 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008303 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008304 SequenceChecker(*this, Item, WorkList);
8305 }
Richard Smithc406cb72013-01-17 01:17:56 +00008306}
8307
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008308void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8309 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008310 CheckImplicitConversions(E, CheckLoc);
8311 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008312 if (!IsConstexpr && !E->isValueDependent())
8313 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008314}
8315
John McCall1f425642010-11-11 03:21:53 +00008316void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8317 FieldDecl *BitField,
8318 Expr *Init) {
8319 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8320}
8321
David Majnemer61a5bbf2015-04-07 22:08:51 +00008322static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8323 SourceLocation Loc) {
8324 if (!PType->isVariablyModifiedType())
8325 return;
8326 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8327 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8328 return;
8329 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008330 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8331 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8332 return;
8333 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008334 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8335 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8336 return;
8337 }
8338
8339 const ArrayType *AT = S.Context.getAsArrayType(PType);
8340 if (!AT)
8341 return;
8342
8343 if (AT->getSizeModifier() != ArrayType::Star) {
8344 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8345 return;
8346 }
8347
8348 S.Diag(Loc, diag::err_array_star_in_function_definition);
8349}
8350
Mike Stump0c2ec772010-01-21 03:59:47 +00008351/// CheckParmsForFunctionDef - Check that the parameters of the given
8352/// function are appropriate for the definition of a function. This
8353/// takes care of any checks that cannot be performed on the
8354/// declaration itself, e.g., that the types of each of the function
8355/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008356bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8357 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008358 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008359 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008360 for (; P != PEnd; ++P) {
8361 ParmVarDecl *Param = *P;
8362
Mike Stump0c2ec772010-01-21 03:59:47 +00008363 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8364 // function declarator that is part of a function definition of
8365 // that function shall not have incomplete type.
8366 //
8367 // This is also C++ [dcl.fct]p6.
8368 if (!Param->isInvalidDecl() &&
8369 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008370 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008371 Param->setInvalidDecl();
8372 HasInvalidParm = true;
8373 }
8374
8375 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8376 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008377 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008378 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008379 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008380 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008381 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008382
8383 // C99 6.7.5.3p12:
8384 // If the function declarator is not part of a definition of that
8385 // function, parameters may have incomplete type and may use the [*]
8386 // notation in their sequences of declarator specifiers to specify
8387 // variable length array types.
8388 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008389 // FIXME: This diagnostic should point the '[*]' if source-location
8390 // information is added for it.
8391 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008392
8393 // MSVC destroys objects passed by value in the callee. Therefore a
8394 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008395 // object's destructor. However, we don't perform any direct access check
8396 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008397 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8398 .getCXXABI()
8399 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008400 if (!Param->isInvalidDecl()) {
8401 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8402 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8403 if (!ClassDecl->isInvalidDecl() &&
8404 !ClassDecl->hasIrrelevantDestructor() &&
8405 !ClassDecl->isDependentContext()) {
8406 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8407 MarkFunctionReferenced(Param->getLocation(), Destructor);
8408 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8409 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008410 }
8411 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008412 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008413 }
8414
8415 return HasInvalidParm;
8416}
John McCall2b5c1b22010-08-12 21:44:57 +00008417
8418/// CheckCastAlign - Implements -Wcast-align, which warns when a
8419/// pointer cast increases the alignment requirements.
8420void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8421 // This is actually a lot of work to potentially be doing on every
8422 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008423 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008424 return;
8425
8426 // Ignore dependent types.
8427 if (T->isDependentType() || Op->getType()->isDependentType())
8428 return;
8429
8430 // Require that the destination be a pointer type.
8431 const PointerType *DestPtr = T->getAs<PointerType>();
8432 if (!DestPtr) return;
8433
8434 // If the destination has alignment 1, we're done.
8435 QualType DestPointee = DestPtr->getPointeeType();
8436 if (DestPointee->isIncompleteType()) return;
8437 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8438 if (DestAlign.isOne()) return;
8439
8440 // Require that the source be a pointer type.
8441 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8442 if (!SrcPtr) return;
8443 QualType SrcPointee = SrcPtr->getPointeeType();
8444
8445 // Whitelist casts from cv void*. We already implicitly
8446 // whitelisted casts to cv void*, since they have alignment 1.
8447 // Also whitelist casts involving incomplete types, which implicitly
8448 // includes 'void'.
8449 if (SrcPointee->isIncompleteType()) return;
8450
8451 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8452 if (SrcAlign >= DestAlign) return;
8453
8454 Diag(TRange.getBegin(), diag::warn_cast_align)
8455 << Op->getType() << T
8456 << static_cast<unsigned>(SrcAlign.getQuantity())
8457 << static_cast<unsigned>(DestAlign.getQuantity())
8458 << TRange << Op->getSourceRange();
8459}
8460
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008461static const Type* getElementType(const Expr *BaseExpr) {
8462 const Type* EltType = BaseExpr->getType().getTypePtr();
8463 if (EltType->isAnyPointerType())
8464 return EltType->getPointeeType().getTypePtr();
8465 else if (EltType->isArrayType())
8466 return EltType->getBaseElementTypeUnsafe();
8467 return EltType;
8468}
8469
Chandler Carruth28389f02011-08-05 09:10:50 +00008470/// \brief Check whether this array fits the idiom of a size-one tail padded
8471/// array member of a struct.
8472///
8473/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8474/// commonly used to emulate flexible arrays in C89 code.
8475static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8476 const NamedDecl *ND) {
8477 if (Size != 1 || !ND) return false;
8478
8479 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8480 if (!FD) return false;
8481
8482 // Don't consider sizes resulting from macro expansions or template argument
8483 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008484
8485 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008486 while (TInfo) {
8487 TypeLoc TL = TInfo->getTypeLoc();
8488 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008489 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8490 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008491 TInfo = TDL->getTypeSourceInfo();
8492 continue;
8493 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008494 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8495 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008496 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8497 return false;
8498 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008499 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008500 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008501
8502 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008503 if (!RD) return false;
8504 if (RD->isUnion()) return false;
8505 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8506 if (!CRD->isStandardLayout()) return false;
8507 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008508
Benjamin Kramer8c543672011-08-06 03:04:42 +00008509 // See if this is the last field decl in the record.
8510 const Decl *D = FD;
8511 while ((D = D->getNextDeclInContext()))
8512 if (isa<FieldDecl>(D))
8513 return false;
8514 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008515}
8516
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008517void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008518 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008519 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008520 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008521 if (IndexExpr->isValueDependent())
8522 return;
8523
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008524 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008525 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008526 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008527 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008528 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008529 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008530
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008531 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008532 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008533 return;
Richard Smith13f67182011-12-16 19:31:14 +00008534 if (IndexNegated)
8535 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008536
Craig Topperc3ec1492014-05-26 06:22:03 +00008537 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008538 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8539 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008540 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008541 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008542
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008543 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008544 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008545 if (!size.isStrictlyPositive())
8546 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008547
8548 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008549 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008550 // Make sure we're comparing apples to apples when comparing index to size
8551 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8552 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008553 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008554 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008555 if (ptrarith_typesize != array_typesize) {
8556 // There's a cast to a different size type involved
8557 uint64_t ratio = array_typesize / ptrarith_typesize;
8558 // TODO: Be smarter about handling cases where array_typesize is not a
8559 // multiple of ptrarith_typesize
8560 if (ptrarith_typesize * ratio == array_typesize)
8561 size *= llvm::APInt(size.getBitWidth(), ratio);
8562 }
8563 }
8564
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008565 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008566 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008567 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008568 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008569
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008570 // For array subscripting the index must be less than size, but for pointer
8571 // arithmetic also allow the index (offset) to be equal to size since
8572 // computing the next address after the end of the array is legal and
8573 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008574 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008575 return;
8576
8577 // Also don't warn for arrays of size 1 which are members of some
8578 // structure. These are often used to approximate flexible arrays in C89
8579 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008580 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008581 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008582
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008583 // Suppress the warning if the subscript expression (as identified by the
8584 // ']' location) and the index expression are both from macro expansions
8585 // within a system header.
8586 if (ASE) {
8587 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8588 ASE->getRBracketLoc());
8589 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8590 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8591 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008592 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008593 return;
8594 }
8595 }
8596
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008597 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008598 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008599 DiagID = diag::warn_array_index_exceeds_bounds;
8600
8601 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8602 PDiag(DiagID) << index.toString(10, true)
8603 << size.toString(10, true)
8604 << (unsigned)size.getLimitedValue(~0U)
8605 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008606 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008607 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008608 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008609 DiagID = diag::warn_ptr_arith_precedes_bounds;
8610 if (index.isNegative()) index = -index;
8611 }
8612
8613 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8614 PDiag(DiagID) << index.toString(10, true)
8615 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008616 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008617
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008618 if (!ND) {
8619 // Try harder to find a NamedDecl to point at in the note.
8620 while (const ArraySubscriptExpr *ASE =
8621 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8622 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8623 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8624 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8625 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8626 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8627 }
8628
Chandler Carruth1af88f12011-02-17 21:10:52 +00008629 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008630 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8631 PDiag(diag::note_array_index_out_of_bounds)
8632 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008633}
8634
Ted Kremenekdf26df72011-03-01 18:41:00 +00008635void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008636 int AllowOnePastEnd = 0;
8637 while (expr) {
8638 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008639 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008640 case Stmt::ArraySubscriptExprClass: {
8641 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008642 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008643 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008644 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008645 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008646 case Stmt::OMPArraySectionExprClass: {
8647 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8648 if (ASE->getLowerBound())
8649 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8650 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8651 return;
8652 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008653 case Stmt::UnaryOperatorClass: {
8654 // Only unwrap the * and & unary operators
8655 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8656 expr = UO->getSubExpr();
8657 switch (UO->getOpcode()) {
8658 case UO_AddrOf:
8659 AllowOnePastEnd++;
8660 break;
8661 case UO_Deref:
8662 AllowOnePastEnd--;
8663 break;
8664 default:
8665 return;
8666 }
8667 break;
8668 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008669 case Stmt::ConditionalOperatorClass: {
8670 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8671 if (const Expr *lhs = cond->getLHS())
8672 CheckArrayAccess(lhs);
8673 if (const Expr *rhs = cond->getRHS())
8674 CheckArrayAccess(rhs);
8675 return;
8676 }
8677 default:
8678 return;
8679 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008680 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008681}
John McCall31168b02011-06-15 23:02:42 +00008682
8683//===--- CHECK: Objective-C retain cycles ----------------------------------//
8684
8685namespace {
8686 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008687 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008688 VarDecl *Variable;
8689 SourceRange Range;
8690 SourceLocation Loc;
8691 bool Indirect;
8692
8693 void setLocsFrom(Expr *e) {
8694 Loc = e->getExprLoc();
8695 Range = e->getSourceRange();
8696 }
8697 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008698}
John McCall31168b02011-06-15 23:02:42 +00008699
8700/// Consider whether capturing the given variable can possibly lead to
8701/// a retain cycle.
8702static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008703 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008704 // lifetime. In MRR, it's captured strongly if the variable is
8705 // __block and has an appropriate type.
8706 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8707 return false;
8708
8709 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008710 if (ref)
8711 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008712 return true;
8713}
8714
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008715static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008716 while (true) {
8717 e = e->IgnoreParens();
8718 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8719 switch (cast->getCastKind()) {
8720 case CK_BitCast:
8721 case CK_LValueBitCast:
8722 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008723 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008724 e = cast->getSubExpr();
8725 continue;
8726
John McCall31168b02011-06-15 23:02:42 +00008727 default:
8728 return false;
8729 }
8730 }
8731
8732 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8733 ObjCIvarDecl *ivar = ref->getDecl();
8734 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8735 return false;
8736
8737 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008738 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008739 return false;
8740
8741 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8742 owner.Indirect = true;
8743 return true;
8744 }
8745
8746 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8747 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8748 if (!var) return false;
8749 return considerVariable(var, ref, owner);
8750 }
8751
John McCall31168b02011-06-15 23:02:42 +00008752 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8753 if (member->isArrow()) return false;
8754
8755 // Don't count this as an indirect ownership.
8756 e = member->getBase();
8757 continue;
8758 }
8759
John McCallfe96e0b2011-11-06 09:01:30 +00008760 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8761 // Only pay attention to pseudo-objects on property references.
8762 ObjCPropertyRefExpr *pre
8763 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8764 ->IgnoreParens());
8765 if (!pre) return false;
8766 if (pre->isImplicitProperty()) return false;
8767 ObjCPropertyDecl *property = pre->getExplicitProperty();
8768 if (!property->isRetaining() &&
8769 !(property->getPropertyIvarDecl() &&
8770 property->getPropertyIvarDecl()->getType()
8771 .getObjCLifetime() == Qualifiers::OCL_Strong))
8772 return false;
8773
8774 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008775 if (pre->isSuperReceiver()) {
8776 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8777 if (!owner.Variable)
8778 return false;
8779 owner.Loc = pre->getLocation();
8780 owner.Range = pre->getSourceRange();
8781 return true;
8782 }
John McCallfe96e0b2011-11-06 09:01:30 +00008783 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8784 ->getSourceExpr());
8785 continue;
8786 }
8787
John McCall31168b02011-06-15 23:02:42 +00008788 // Array ivars?
8789
8790 return false;
8791 }
8792}
8793
8794namespace {
8795 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8796 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8797 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008798 Context(Context), Variable(variable), Capturer(nullptr),
8799 VarWillBeReased(false) {}
8800 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008801 VarDecl *Variable;
8802 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008803 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008804
8805 void VisitDeclRefExpr(DeclRefExpr *ref) {
8806 if (ref->getDecl() == Variable && !Capturer)
8807 Capturer = ref;
8808 }
8809
John McCall31168b02011-06-15 23:02:42 +00008810 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8811 if (Capturer) return;
8812 Visit(ref->getBase());
8813 if (Capturer && ref->isFreeIvar())
8814 Capturer = ref;
8815 }
8816
8817 void VisitBlockExpr(BlockExpr *block) {
8818 // Look inside nested blocks
8819 if (block->getBlockDecl()->capturesVariable(Variable))
8820 Visit(block->getBlockDecl()->getBody());
8821 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008822
8823 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8824 if (Capturer) return;
8825 if (OVE->getSourceExpr())
8826 Visit(OVE->getSourceExpr());
8827 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008828 void VisitBinaryOperator(BinaryOperator *BinOp) {
8829 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8830 return;
8831 Expr *LHS = BinOp->getLHS();
8832 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8833 if (DRE->getDecl() != Variable)
8834 return;
8835 if (Expr *RHS = BinOp->getRHS()) {
8836 RHS = RHS->IgnoreParenCasts();
8837 llvm::APSInt Value;
8838 VarWillBeReased =
8839 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8840 }
8841 }
8842 }
John McCall31168b02011-06-15 23:02:42 +00008843 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008844}
John McCall31168b02011-06-15 23:02:42 +00008845
8846/// Check whether the given argument is a block which captures a
8847/// variable.
8848static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8849 assert(owner.Variable && owner.Loc.isValid());
8850
8851 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008852
8853 // Look through [^{...} copy] and Block_copy(^{...}).
8854 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8855 Selector Cmd = ME->getSelector();
8856 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8857 e = ME->getInstanceReceiver();
8858 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008859 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008860 e = e->IgnoreParenCasts();
8861 }
8862 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8863 if (CE->getNumArgs() == 1) {
8864 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008865 if (Fn) {
8866 const IdentifierInfo *FnI = Fn->getIdentifier();
8867 if (FnI && FnI->isStr("_Block_copy")) {
8868 e = CE->getArg(0)->IgnoreParenCasts();
8869 }
8870 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008871 }
8872 }
8873
John McCall31168b02011-06-15 23:02:42 +00008874 BlockExpr *block = dyn_cast<BlockExpr>(e);
8875 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008876 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008877
8878 FindCaptureVisitor visitor(S.Context, owner.Variable);
8879 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008880 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008881}
8882
8883static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8884 RetainCycleOwner &owner) {
8885 assert(capturer);
8886 assert(owner.Variable && owner.Loc.isValid());
8887
8888 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8889 << owner.Variable << capturer->getSourceRange();
8890 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8891 << owner.Indirect << owner.Range;
8892}
8893
8894/// Check for a keyword selector that starts with the word 'add' or
8895/// 'set'.
8896static bool isSetterLikeSelector(Selector sel) {
8897 if (sel.isUnarySelector()) return false;
8898
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008899 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008900 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008901 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008902 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008903 else if (str.startswith("add")) {
8904 // Specially whitelist 'addOperationWithBlock:'.
8905 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8906 return false;
8907 str = str.substr(3);
8908 }
John McCall31168b02011-06-15 23:02:42 +00008909 else
8910 return false;
8911
8912 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008913 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008914}
8915
Benjamin Kramer3a743452015-03-09 15:03:32 +00008916static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8917 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008918 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8919 Message->getReceiverInterface(),
8920 NSAPI::ClassId_NSMutableArray);
8921 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008922 return None;
8923 }
8924
8925 Selector Sel = Message->getSelector();
8926
8927 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8928 S.NSAPIObj->getNSArrayMethodKind(Sel);
8929 if (!MKOpt) {
8930 return None;
8931 }
8932
8933 NSAPI::NSArrayMethodKind MK = *MKOpt;
8934
8935 switch (MK) {
8936 case NSAPI::NSMutableArr_addObject:
8937 case NSAPI::NSMutableArr_insertObjectAtIndex:
8938 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8939 return 0;
8940 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8941 return 1;
8942
8943 default:
8944 return None;
8945 }
8946
8947 return None;
8948}
8949
8950static
8951Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8952 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008953 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8954 Message->getReceiverInterface(),
8955 NSAPI::ClassId_NSMutableDictionary);
8956 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008957 return None;
8958 }
8959
8960 Selector Sel = Message->getSelector();
8961
8962 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8963 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8964 if (!MKOpt) {
8965 return None;
8966 }
8967
8968 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8969
8970 switch (MK) {
8971 case NSAPI::NSMutableDict_setObjectForKey:
8972 case NSAPI::NSMutableDict_setValueForKey:
8973 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8974 return 0;
8975
8976 default:
8977 return None;
8978 }
8979
8980 return None;
8981}
8982
8983static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008984 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8985 Message->getReceiverInterface(),
8986 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008987
Alex Denisov5dfac812015-08-06 04:51:14 +00008988 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8989 Message->getReceiverInterface(),
8990 NSAPI::ClassId_NSMutableOrderedSet);
8991 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008992 return None;
8993 }
8994
8995 Selector Sel = Message->getSelector();
8996
8997 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8998 if (!MKOpt) {
8999 return None;
9000 }
9001
9002 NSAPI::NSSetMethodKind MK = *MKOpt;
9003
9004 switch (MK) {
9005 case NSAPI::NSMutableSet_addObject:
9006 case NSAPI::NSOrderedSet_setObjectAtIndex:
9007 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9008 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9009 return 0;
9010 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9011 return 1;
9012 }
9013
9014 return None;
9015}
9016
9017void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9018 if (!Message->isInstanceMessage()) {
9019 return;
9020 }
9021
9022 Optional<int> ArgOpt;
9023
9024 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9025 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9026 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9027 return;
9028 }
9029
9030 int ArgIndex = *ArgOpt;
9031
Alex Denisove1d882c2015-03-04 17:55:52 +00009032 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9033 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9034 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9035 }
9036
Alex Denisov5dfac812015-08-06 04:51:14 +00009037 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009038 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009039 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009040 Diag(Message->getSourceRange().getBegin(),
9041 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009042 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009043 }
9044 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009045 } else {
9046 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9047
9048 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9049 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9050 }
9051
9052 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9053 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9054 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9055 ValueDecl *Decl = ReceiverRE->getDecl();
9056 Diag(Message->getSourceRange().getBegin(),
9057 diag::warn_objc_circular_container)
9058 << Decl->getName() << Decl->getName();
9059 if (!ArgRE->isObjCSelfExpr()) {
9060 Diag(Decl->getLocation(),
9061 diag::note_objc_circular_container_declared_here)
9062 << Decl->getName();
9063 }
9064 }
9065 }
9066 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9067 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9068 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9069 ObjCIvarDecl *Decl = IvarRE->getDecl();
9070 Diag(Message->getSourceRange().getBegin(),
9071 diag::warn_objc_circular_container)
9072 << Decl->getName() << Decl->getName();
9073 Diag(Decl->getLocation(),
9074 diag::note_objc_circular_container_declared_here)
9075 << Decl->getName();
9076 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009077 }
9078 }
9079 }
9080
9081}
9082
John McCall31168b02011-06-15 23:02:42 +00009083/// Check a message send to see if it's likely to cause a retain cycle.
9084void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9085 // Only check instance methods whose selector looks like a setter.
9086 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9087 return;
9088
9089 // Try to find a variable that the receiver is strongly owned by.
9090 RetainCycleOwner owner;
9091 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009092 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009093 return;
9094 } else {
9095 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9096 owner.Variable = getCurMethodDecl()->getSelfDecl();
9097 owner.Loc = msg->getSuperLoc();
9098 owner.Range = msg->getSuperLoc();
9099 }
9100
9101 // Check whether the receiver is captured by any of the arguments.
9102 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9103 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9104 return diagnoseRetainCycle(*this, capturer, owner);
9105}
9106
9107/// Check a property assign to see if it's likely to cause a retain cycle.
9108void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9109 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009110 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009111 return;
9112
9113 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9114 diagnoseRetainCycle(*this, capturer, owner);
9115}
9116
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009117void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9118 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009119 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009120 return;
9121
9122 // Because we don't have an expression for the variable, we have to set the
9123 // location explicitly here.
9124 Owner.Loc = Var->getLocation();
9125 Owner.Range = Var->getSourceRange();
9126
9127 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9128 diagnoseRetainCycle(*this, Capturer, Owner);
9129}
9130
Ted Kremenek9304da92012-12-21 08:04:28 +00009131static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9132 Expr *RHS, bool isProperty) {
9133 // Check if RHS is an Objective-C object literal, which also can get
9134 // immediately zapped in a weak reference. Note that we explicitly
9135 // allow ObjCStringLiterals, since those are designed to never really die.
9136 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009137
Ted Kremenek64873352012-12-21 22:46:35 +00009138 // This enum needs to match with the 'select' in
9139 // warn_objc_arc_literal_assign (off-by-1).
9140 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9141 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9142 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009143
9144 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009145 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009146 << (isProperty ? 0 : 1)
9147 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009148
9149 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009150}
9151
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009152static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9153 Qualifiers::ObjCLifetime LT,
9154 Expr *RHS, bool isProperty) {
9155 // Strip off any implicit cast added to get to the one ARC-specific.
9156 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9157 if (cast->getCastKind() == CK_ARCConsumeObject) {
9158 S.Diag(Loc, diag::warn_arc_retained_assign)
9159 << (LT == Qualifiers::OCL_ExplicitNone)
9160 << (isProperty ? 0 : 1)
9161 << RHS->getSourceRange();
9162 return true;
9163 }
9164 RHS = cast->getSubExpr();
9165 }
9166
9167 if (LT == Qualifiers::OCL_Weak &&
9168 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9169 return true;
9170
9171 return false;
9172}
9173
Ted Kremenekb36234d2012-12-21 08:04:20 +00009174bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9175 QualType LHS, Expr *RHS) {
9176 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9177
9178 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9179 return false;
9180
9181 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9182 return true;
9183
9184 return false;
9185}
9186
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009187void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9188 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009189 QualType LHSType;
9190 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009191 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009192 ObjCPropertyRefExpr *PRE
9193 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9194 if (PRE && !PRE->isImplicitProperty()) {
9195 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9196 if (PD)
9197 LHSType = PD->getType();
9198 }
9199
9200 if (LHSType.isNull())
9201 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009202
9203 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9204
9205 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009206 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009207 getCurFunction()->markSafeWeakUse(LHS);
9208 }
9209
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009210 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9211 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009212
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009213 // FIXME. Check for other life times.
9214 if (LT != Qualifiers::OCL_None)
9215 return;
9216
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009217 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009218 if (PRE->isImplicitProperty())
9219 return;
9220 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9221 if (!PD)
9222 return;
9223
Bill Wendling44426052012-12-20 19:22:21 +00009224 unsigned Attributes = PD->getPropertyAttributes();
9225 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009226 // when 'assign' attribute was not explicitly specified
9227 // by user, ignore it and rely on property type itself
9228 // for lifetime info.
9229 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9230 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9231 LHSType->isObjCRetainableType())
9232 return;
9233
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009234 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009235 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009236 Diag(Loc, diag::warn_arc_retained_property_assign)
9237 << RHS->getSourceRange();
9238 return;
9239 }
9240 RHS = cast->getSubExpr();
9241 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009242 }
Bill Wendling44426052012-12-20 19:22:21 +00009243 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009244 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9245 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009246 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009247 }
9248}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009249
9250//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9251
9252namespace {
9253bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9254 SourceLocation StmtLoc,
9255 const NullStmt *Body) {
9256 // Do not warn if the body is a macro that expands to nothing, e.g:
9257 //
9258 // #define CALL(x)
9259 // if (condition)
9260 // CALL(0);
9261 //
9262 if (Body->hasLeadingEmptyMacro())
9263 return false;
9264
9265 // Get line numbers of statement and body.
9266 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009267 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009268 &StmtLineInvalid);
9269 if (StmtLineInvalid)
9270 return false;
9271
9272 bool BodyLineInvalid;
9273 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9274 &BodyLineInvalid);
9275 if (BodyLineInvalid)
9276 return false;
9277
9278 // Warn if null statement and body are on the same line.
9279 if (StmtLine != BodyLine)
9280 return false;
9281
9282 return true;
9283}
9284} // Unnamed namespace
9285
9286void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9287 const Stmt *Body,
9288 unsigned DiagID) {
9289 // Since this is a syntactic check, don't emit diagnostic for template
9290 // instantiations, this just adds noise.
9291 if (CurrentInstantiationScope)
9292 return;
9293
9294 // The body should be a null statement.
9295 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9296 if (!NBody)
9297 return;
9298
9299 // Do the usual checks.
9300 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9301 return;
9302
9303 Diag(NBody->getSemiLoc(), DiagID);
9304 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9305}
9306
9307void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9308 const Stmt *PossibleBody) {
9309 assert(!CurrentInstantiationScope); // Ensured by caller
9310
9311 SourceLocation StmtLoc;
9312 const Stmt *Body;
9313 unsigned DiagID;
9314 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9315 StmtLoc = FS->getRParenLoc();
9316 Body = FS->getBody();
9317 DiagID = diag::warn_empty_for_body;
9318 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9319 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9320 Body = WS->getBody();
9321 DiagID = diag::warn_empty_while_body;
9322 } else
9323 return; // Neither `for' nor `while'.
9324
9325 // The body should be a null statement.
9326 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9327 if (!NBody)
9328 return;
9329
9330 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009331 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009332 return;
9333
9334 // Do the usual checks.
9335 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9336 return;
9337
9338 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9339 // noise level low, emit diagnostics only if for/while is followed by a
9340 // CompoundStmt, e.g.:
9341 // for (int i = 0; i < n; i++);
9342 // {
9343 // a(i);
9344 // }
9345 // or if for/while is followed by a statement with more indentation
9346 // than for/while itself:
9347 // for (int i = 0; i < n; i++);
9348 // a(i);
9349 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9350 if (!ProbableTypo) {
9351 bool BodyColInvalid;
9352 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9353 PossibleBody->getLocStart(),
9354 &BodyColInvalid);
9355 if (BodyColInvalid)
9356 return;
9357
9358 bool StmtColInvalid;
9359 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9360 S->getLocStart(),
9361 &StmtColInvalid);
9362 if (StmtColInvalid)
9363 return;
9364
9365 if (BodyCol > StmtCol)
9366 ProbableTypo = true;
9367 }
9368
9369 if (ProbableTypo) {
9370 Diag(NBody->getSemiLoc(), DiagID);
9371 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9372 }
9373}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009374
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009375//===--- CHECK: Warn on self move with std::move. -------------------------===//
9376
9377/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9378void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9379 SourceLocation OpLoc) {
9380
9381 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9382 return;
9383
9384 if (!ActiveTemplateInstantiations.empty())
9385 return;
9386
9387 // Strip parens and casts away.
9388 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9389 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9390
9391 // Check for a call expression
9392 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9393 if (!CE || CE->getNumArgs() != 1)
9394 return;
9395
9396 // Check for a call to std::move
9397 const FunctionDecl *FD = CE->getDirectCallee();
9398 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9399 !FD->getIdentifier()->isStr("move"))
9400 return;
9401
9402 // Get argument from std::move
9403 RHSExpr = CE->getArg(0);
9404
9405 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9406 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9407
9408 // Two DeclRefExpr's, check that the decls are the same.
9409 if (LHSDeclRef && RHSDeclRef) {
9410 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9411 return;
9412 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9413 RHSDeclRef->getDecl()->getCanonicalDecl())
9414 return;
9415
9416 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9417 << LHSExpr->getSourceRange()
9418 << RHSExpr->getSourceRange();
9419 return;
9420 }
9421
9422 // Member variables require a different approach to check for self moves.
9423 // MemberExpr's are the same if every nested MemberExpr refers to the same
9424 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9425 // the base Expr's are CXXThisExpr's.
9426 const Expr *LHSBase = LHSExpr;
9427 const Expr *RHSBase = RHSExpr;
9428 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9429 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9430 if (!LHSME || !RHSME)
9431 return;
9432
9433 while (LHSME && RHSME) {
9434 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9435 RHSME->getMemberDecl()->getCanonicalDecl())
9436 return;
9437
9438 LHSBase = LHSME->getBase();
9439 RHSBase = RHSME->getBase();
9440 LHSME = dyn_cast<MemberExpr>(LHSBase);
9441 RHSME = dyn_cast<MemberExpr>(RHSBase);
9442 }
9443
9444 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9445 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9446 if (LHSDeclRef && RHSDeclRef) {
9447 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9448 return;
9449 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9450 RHSDeclRef->getDecl()->getCanonicalDecl())
9451 return;
9452
9453 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9454 << LHSExpr->getSourceRange()
9455 << RHSExpr->getSourceRange();
9456 return;
9457 }
9458
9459 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9460 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9461 << LHSExpr->getSourceRange()
9462 << RHSExpr->getSourceRange();
9463}
9464
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009465//===--- Layout compatibility ----------------------------------------------//
9466
9467namespace {
9468
9469bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9470
9471/// \brief Check if two enumeration types are layout-compatible.
9472bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9473 // C++11 [dcl.enum] p8:
9474 // Two enumeration types are layout-compatible if they have the same
9475 // underlying type.
9476 return ED1->isComplete() && ED2->isComplete() &&
9477 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9478}
9479
9480/// \brief Check if two fields are layout-compatible.
9481bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9482 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9483 return false;
9484
9485 if (Field1->isBitField() != Field2->isBitField())
9486 return false;
9487
9488 if (Field1->isBitField()) {
9489 // Make sure that the bit-fields are the same length.
9490 unsigned Bits1 = Field1->getBitWidthValue(C);
9491 unsigned Bits2 = Field2->getBitWidthValue(C);
9492
9493 if (Bits1 != Bits2)
9494 return false;
9495 }
9496
9497 return true;
9498}
9499
9500/// \brief Check if two standard-layout structs are layout-compatible.
9501/// (C++11 [class.mem] p17)
9502bool isLayoutCompatibleStruct(ASTContext &C,
9503 RecordDecl *RD1,
9504 RecordDecl *RD2) {
9505 // If both records are C++ classes, check that base classes match.
9506 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9507 // If one of records is a CXXRecordDecl we are in C++ mode,
9508 // thus the other one is a CXXRecordDecl, too.
9509 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9510 // Check number of base classes.
9511 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9512 return false;
9513
9514 // Check the base classes.
9515 for (CXXRecordDecl::base_class_const_iterator
9516 Base1 = D1CXX->bases_begin(),
9517 BaseEnd1 = D1CXX->bases_end(),
9518 Base2 = D2CXX->bases_begin();
9519 Base1 != BaseEnd1;
9520 ++Base1, ++Base2) {
9521 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9522 return false;
9523 }
9524 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9525 // If only RD2 is a C++ class, it should have zero base classes.
9526 if (D2CXX->getNumBases() > 0)
9527 return false;
9528 }
9529
9530 // Check the fields.
9531 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9532 Field2End = RD2->field_end(),
9533 Field1 = RD1->field_begin(),
9534 Field1End = RD1->field_end();
9535 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9536 if (!isLayoutCompatible(C, *Field1, *Field2))
9537 return false;
9538 }
9539 if (Field1 != Field1End || Field2 != Field2End)
9540 return false;
9541
9542 return true;
9543}
9544
9545/// \brief Check if two standard-layout unions are layout-compatible.
9546/// (C++11 [class.mem] p18)
9547bool isLayoutCompatibleUnion(ASTContext &C,
9548 RecordDecl *RD1,
9549 RecordDecl *RD2) {
9550 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009551 for (auto *Field2 : RD2->fields())
9552 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009553
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009554 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009555 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9556 I = UnmatchedFields.begin(),
9557 E = UnmatchedFields.end();
9558
9559 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009560 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009561 bool Result = UnmatchedFields.erase(*I);
9562 (void) Result;
9563 assert(Result);
9564 break;
9565 }
9566 }
9567 if (I == E)
9568 return false;
9569 }
9570
9571 return UnmatchedFields.empty();
9572}
9573
9574bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9575 if (RD1->isUnion() != RD2->isUnion())
9576 return false;
9577
9578 if (RD1->isUnion())
9579 return isLayoutCompatibleUnion(C, RD1, RD2);
9580 else
9581 return isLayoutCompatibleStruct(C, RD1, RD2);
9582}
9583
9584/// \brief Check if two types are layout-compatible in C++11 sense.
9585bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9586 if (T1.isNull() || T2.isNull())
9587 return false;
9588
9589 // C++11 [basic.types] p11:
9590 // If two types T1 and T2 are the same type, then T1 and T2 are
9591 // layout-compatible types.
9592 if (C.hasSameType(T1, T2))
9593 return true;
9594
9595 T1 = T1.getCanonicalType().getUnqualifiedType();
9596 T2 = T2.getCanonicalType().getUnqualifiedType();
9597
9598 const Type::TypeClass TC1 = T1->getTypeClass();
9599 const Type::TypeClass TC2 = T2->getTypeClass();
9600
9601 if (TC1 != TC2)
9602 return false;
9603
9604 if (TC1 == Type::Enum) {
9605 return isLayoutCompatible(C,
9606 cast<EnumType>(T1)->getDecl(),
9607 cast<EnumType>(T2)->getDecl());
9608 } else if (TC1 == Type::Record) {
9609 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9610 return false;
9611
9612 return isLayoutCompatible(C,
9613 cast<RecordType>(T1)->getDecl(),
9614 cast<RecordType>(T2)->getDecl());
9615 }
9616
9617 return false;
9618}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009619}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009620
9621//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9622
9623namespace {
9624/// \brief Given a type tag expression find the type tag itself.
9625///
9626/// \param TypeExpr Type tag expression, as it appears in user's code.
9627///
9628/// \param VD Declaration of an identifier that appears in a type tag.
9629///
9630/// \param MagicValue Type tag magic value.
9631bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9632 const ValueDecl **VD, uint64_t *MagicValue) {
9633 while(true) {
9634 if (!TypeExpr)
9635 return false;
9636
9637 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9638
9639 switch (TypeExpr->getStmtClass()) {
9640 case Stmt::UnaryOperatorClass: {
9641 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9642 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9643 TypeExpr = UO->getSubExpr();
9644 continue;
9645 }
9646 return false;
9647 }
9648
9649 case Stmt::DeclRefExprClass: {
9650 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9651 *VD = DRE->getDecl();
9652 return true;
9653 }
9654
9655 case Stmt::IntegerLiteralClass: {
9656 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9657 llvm::APInt MagicValueAPInt = IL->getValue();
9658 if (MagicValueAPInt.getActiveBits() <= 64) {
9659 *MagicValue = MagicValueAPInt.getZExtValue();
9660 return true;
9661 } else
9662 return false;
9663 }
9664
9665 case Stmt::BinaryConditionalOperatorClass:
9666 case Stmt::ConditionalOperatorClass: {
9667 const AbstractConditionalOperator *ACO =
9668 cast<AbstractConditionalOperator>(TypeExpr);
9669 bool Result;
9670 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9671 if (Result)
9672 TypeExpr = ACO->getTrueExpr();
9673 else
9674 TypeExpr = ACO->getFalseExpr();
9675 continue;
9676 }
9677 return false;
9678 }
9679
9680 case Stmt::BinaryOperatorClass: {
9681 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9682 if (BO->getOpcode() == BO_Comma) {
9683 TypeExpr = BO->getRHS();
9684 continue;
9685 }
9686 return false;
9687 }
9688
9689 default:
9690 return false;
9691 }
9692 }
9693}
9694
9695/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9696///
9697/// \param TypeExpr Expression that specifies a type tag.
9698///
9699/// \param MagicValues Registered magic values.
9700///
9701/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9702/// kind.
9703///
9704/// \param TypeInfo Information about the corresponding C type.
9705///
9706/// \returns true if the corresponding C type was found.
9707bool GetMatchingCType(
9708 const IdentifierInfo *ArgumentKind,
9709 const Expr *TypeExpr, const ASTContext &Ctx,
9710 const llvm::DenseMap<Sema::TypeTagMagicValue,
9711 Sema::TypeTagData> *MagicValues,
9712 bool &FoundWrongKind,
9713 Sema::TypeTagData &TypeInfo) {
9714 FoundWrongKind = false;
9715
9716 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009717 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009718
9719 uint64_t MagicValue;
9720
9721 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9722 return false;
9723
9724 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009725 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009726 if (I->getArgumentKind() != ArgumentKind) {
9727 FoundWrongKind = true;
9728 return false;
9729 }
9730 TypeInfo.Type = I->getMatchingCType();
9731 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9732 TypeInfo.MustBeNull = I->getMustBeNull();
9733 return true;
9734 }
9735 return false;
9736 }
9737
9738 if (!MagicValues)
9739 return false;
9740
9741 llvm::DenseMap<Sema::TypeTagMagicValue,
9742 Sema::TypeTagData>::const_iterator I =
9743 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9744 if (I == MagicValues->end())
9745 return false;
9746
9747 TypeInfo = I->second;
9748 return true;
9749}
9750} // unnamed namespace
9751
9752void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9753 uint64_t MagicValue, QualType Type,
9754 bool LayoutCompatible,
9755 bool MustBeNull) {
9756 if (!TypeTagForDatatypeMagicValues)
9757 TypeTagForDatatypeMagicValues.reset(
9758 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9759
9760 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9761 (*TypeTagForDatatypeMagicValues)[Magic] =
9762 TypeTagData(Type, LayoutCompatible, MustBeNull);
9763}
9764
9765namespace {
9766bool IsSameCharType(QualType T1, QualType T2) {
9767 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9768 if (!BT1)
9769 return false;
9770
9771 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9772 if (!BT2)
9773 return false;
9774
9775 BuiltinType::Kind T1Kind = BT1->getKind();
9776 BuiltinType::Kind T2Kind = BT2->getKind();
9777
9778 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9779 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9780 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9781 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9782}
9783} // unnamed namespace
9784
9785void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9786 const Expr * const *ExprArgs) {
9787 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9788 bool IsPointerAttr = Attr->getIsPointer();
9789
9790 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9791 bool FoundWrongKind;
9792 TypeTagData TypeInfo;
9793 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9794 TypeTagForDatatypeMagicValues.get(),
9795 FoundWrongKind, TypeInfo)) {
9796 if (FoundWrongKind)
9797 Diag(TypeTagExpr->getExprLoc(),
9798 diag::warn_type_tag_for_datatype_wrong_kind)
9799 << TypeTagExpr->getSourceRange();
9800 return;
9801 }
9802
9803 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9804 if (IsPointerAttr) {
9805 // Skip implicit cast of pointer to `void *' (as a function argument).
9806 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009807 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009808 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009809 ArgumentExpr = ICE->getSubExpr();
9810 }
9811 QualType ArgumentType = ArgumentExpr->getType();
9812
9813 // Passing a `void*' pointer shouldn't trigger a warning.
9814 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9815 return;
9816
9817 if (TypeInfo.MustBeNull) {
9818 // Type tag with matching void type requires a null pointer.
9819 if (!ArgumentExpr->isNullPointerConstant(Context,
9820 Expr::NPC_ValueDependentIsNotNull)) {
9821 Diag(ArgumentExpr->getExprLoc(),
9822 diag::warn_type_safety_null_pointer_required)
9823 << ArgumentKind->getName()
9824 << ArgumentExpr->getSourceRange()
9825 << TypeTagExpr->getSourceRange();
9826 }
9827 return;
9828 }
9829
9830 QualType RequiredType = TypeInfo.Type;
9831 if (IsPointerAttr)
9832 RequiredType = Context.getPointerType(RequiredType);
9833
9834 bool mismatch = false;
9835 if (!TypeInfo.LayoutCompatible) {
9836 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9837
9838 // C++11 [basic.fundamental] p1:
9839 // Plain char, signed char, and unsigned char are three distinct types.
9840 //
9841 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9842 // char' depending on the current char signedness mode.
9843 if (mismatch)
9844 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9845 RequiredType->getPointeeType())) ||
9846 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9847 mismatch = false;
9848 } else
9849 if (IsPointerAttr)
9850 mismatch = !isLayoutCompatible(Context,
9851 ArgumentType->getPointeeType(),
9852 RequiredType->getPointeeType());
9853 else
9854 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9855
9856 if (mismatch)
9857 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009858 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009859 << TypeInfo.LayoutCompatible << RequiredType
9860 << ArgumentExpr->getSourceRange()
9861 << TypeTagExpr->getSourceRange();
9862}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009863