blob: d5c80c9e201809c5338cb0fd0cbdf448f82a7026 [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:
Craig Toppera86e70d2015-11-07 06:16:14 +0000496 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
Craig Topper5ba2c502015-11-07 08:08:31 +00001073/// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1074/// This checks that the target supports __builtin_cpu_supports and
1075/// that the string argument is constant and valid.
1076static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1077 Expr *Arg = TheCall->getArg(0);
1078
1079 // Check if the argument is a string literal.
1080 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1081 return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1082 << Arg->getSourceRange();
1083
1084 // Check the contents of the string.
1085 StringRef Feature =
1086 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1087 if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1088 return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1089 << Arg->getSourceRange();
1090 return false;
1091}
1092
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001093bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001094 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001095 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001096 default: return false;
Eric Christopherd9832702015-06-29 21:00:05 +00001097 case X86::BI__builtin_cpu_supports:
Craig Topper5ba2c502015-11-07 08:08:31 +00001098 return SemaBuiltinCpuSupports(*this, TheCall);
Charles Davisc7d5c942015-09-17 20:55:33 +00001099 case X86::BI__builtin_ms_va_start:
1100 return SemaBuiltinMSVAStart(TheCall);
Craig Topperdd84ec52014-12-27 07:00:08 +00001101 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001102 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001103 case X86::BI__builtin_ia32_vpermil2pd:
1104 case X86::BI__builtin_ia32_vpermil2pd256:
1105 case X86::BI__builtin_ia32_vpermil2ps:
1106 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001107 case X86::BI__builtin_ia32_cmpb128_mask:
1108 case X86::BI__builtin_ia32_cmpw128_mask:
1109 case X86::BI__builtin_ia32_cmpd128_mask:
1110 case X86::BI__builtin_ia32_cmpq128_mask:
1111 case X86::BI__builtin_ia32_cmpb256_mask:
1112 case X86::BI__builtin_ia32_cmpw256_mask:
1113 case X86::BI__builtin_ia32_cmpd256_mask:
1114 case X86::BI__builtin_ia32_cmpq256_mask:
1115 case X86::BI__builtin_ia32_cmpb512_mask:
1116 case X86::BI__builtin_ia32_cmpw512_mask:
1117 case X86::BI__builtin_ia32_cmpd512_mask:
1118 case X86::BI__builtin_ia32_cmpq512_mask:
1119 case X86::BI__builtin_ia32_ucmpb128_mask:
1120 case X86::BI__builtin_ia32_ucmpw128_mask:
1121 case X86::BI__builtin_ia32_ucmpd128_mask:
1122 case X86::BI__builtin_ia32_ucmpq128_mask:
1123 case X86::BI__builtin_ia32_ucmpb256_mask:
1124 case X86::BI__builtin_ia32_ucmpw256_mask:
1125 case X86::BI__builtin_ia32_ucmpd256_mask:
1126 case X86::BI__builtin_ia32_ucmpq256_mask:
1127 case X86::BI__builtin_ia32_ucmpb512_mask:
1128 case X86::BI__builtin_ia32_ucmpw512_mask:
1129 case X86::BI__builtin_ia32_ucmpd512_mask:
1130 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001131 case X86::BI__builtin_ia32_roundps:
1132 case X86::BI__builtin_ia32_roundpd:
1133 case X86::BI__builtin_ia32_roundps256:
1134 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1135 case X86::BI__builtin_ia32_roundss:
1136 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1137 case X86::BI__builtin_ia32_cmpps:
1138 case X86::BI__builtin_ia32_cmpss:
1139 case X86::BI__builtin_ia32_cmppd:
1140 case X86::BI__builtin_ia32_cmpsd:
1141 case X86::BI__builtin_ia32_cmpps256:
1142 case X86::BI__builtin_ia32_cmppd256:
1143 case X86::BI__builtin_ia32_cmpps512_mask:
1144 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001145 case X86::BI__builtin_ia32_vpcomub:
1146 case X86::BI__builtin_ia32_vpcomuw:
1147 case X86::BI__builtin_ia32_vpcomud:
1148 case X86::BI__builtin_ia32_vpcomuq:
1149 case X86::BI__builtin_ia32_vpcomb:
1150 case X86::BI__builtin_ia32_vpcomw:
1151 case X86::BI__builtin_ia32_vpcomd:
1152 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001153 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001154 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001155}
1156
Richard Smith55ce3522012-06-25 20:30:08 +00001157/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1158/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1159/// Returns true when the format fits the function and the FormatStringInfo has
1160/// been populated.
1161bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1162 FormatStringInfo *FSI) {
1163 FSI->HasVAListArg = Format->getFirstArg() == 0;
1164 FSI->FormatIdx = Format->getFormatIdx() - 1;
1165 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001166
Richard Smith55ce3522012-06-25 20:30:08 +00001167 // The way the format attribute works in GCC, the implicit this argument
1168 // of member functions is counted. However, it doesn't appear in our own
1169 // lists, so decrement format_idx in that case.
1170 if (IsCXXMember) {
1171 if(FSI->FormatIdx == 0)
1172 return false;
1173 --FSI->FormatIdx;
1174 if (FSI->FirstDataArg != 0)
1175 --FSI->FirstDataArg;
1176 }
1177 return true;
1178}
Mike Stump11289f42009-09-09 15:08:12 +00001179
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001180/// Checks if a the given expression evaluates to null.
1181///
1182/// \brief Returns true if the value evaluates to null.
George Burgess IV850269a2015-12-08 22:02:00 +00001183static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001184 // If the expression has non-null type, it doesn't evaluate to null.
1185 if (auto nullability
1186 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1187 if (*nullability == NullabilityKind::NonNull)
1188 return false;
1189 }
1190
Ted Kremeneka146db32014-01-17 06:24:47 +00001191 // As a special case, transparent unions initialized with zero are
1192 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001193 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001194 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1195 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001196 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001197 if (const InitListExpr *ILE =
1198 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001199 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001200 }
1201
1202 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001203 return (!Expr->isValueDependent() &&
1204 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1205 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001206}
1207
1208static void CheckNonNullArgument(Sema &S,
1209 const Expr *ArgExpr,
1210 SourceLocation CallSiteLoc) {
1211 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001212 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1213 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001214}
1215
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001216bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1217 FormatStringInfo FSI;
1218 if ((GetFormatStringType(Format) == FST_NSString) &&
1219 getFormatStringInfo(Format, false, &FSI)) {
1220 Idx = FSI.FormatIdx;
1221 return true;
1222 }
1223 return false;
1224}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001225/// \brief Diagnose use of %s directive in an NSString which is being passed
1226/// as formatting string to formatting method.
1227static void
1228DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1229 const NamedDecl *FDecl,
1230 Expr **Args,
1231 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001232 unsigned Idx = 0;
1233 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001234 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1235 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001236 Idx = 2;
1237 Format = true;
1238 }
1239 else
1240 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1241 if (S.GetFormatNSStringIdx(I, Idx)) {
1242 Format = true;
1243 break;
1244 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001245 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001246 if (!Format || NumArgs <= Idx)
1247 return;
1248 const Expr *FormatExpr = Args[Idx];
1249 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1250 FormatExpr = CSCE->getSubExpr();
1251 const StringLiteral *FormatString;
1252 if (const ObjCStringLiteral *OSL =
1253 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1254 FormatString = OSL->getString();
1255 else
1256 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1257 if (!FormatString)
1258 return;
1259 if (S.FormatStringHasSArg(FormatString)) {
1260 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1261 << "%s" << 1 << 1;
1262 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1263 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001264 }
1265}
1266
Douglas Gregorb4866e82015-06-19 18:13:19 +00001267/// Determine whether the given type has a non-null nullability annotation.
1268static bool isNonNullType(ASTContext &ctx, QualType type) {
1269 if (auto nullability = type->getNullability(ctx))
1270 return *nullability == NullabilityKind::NonNull;
1271
1272 return false;
1273}
1274
Ted Kremenek2bc73332014-01-17 06:24:43 +00001275static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001276 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001277 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001278 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001279 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001280 assert((FDecl || Proto) && "Need a function declaration or prototype");
1281
Ted Kremenek9aedc152014-01-17 06:24:56 +00001282 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001283 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001284 if (FDecl) {
1285 // Handle the nonnull attribute on the function/method declaration itself.
1286 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1287 if (!NonNull->args_size()) {
1288 // Easy case: all pointer arguments are nonnull.
1289 for (const auto *Arg : Args)
1290 if (S.isValidPointerAttrType(Arg->getType()))
1291 CheckNonNullArgument(S, Arg, CallSiteLoc);
1292 return;
1293 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001294
Douglas Gregorb4866e82015-06-19 18:13:19 +00001295 for (unsigned Val : NonNull->args()) {
1296 if (Val >= Args.size())
1297 continue;
1298 if (NonNullArgs.empty())
1299 NonNullArgs.resize(Args.size());
1300 NonNullArgs.set(Val);
1301 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001302 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001303 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001304
Douglas Gregorb4866e82015-06-19 18:13:19 +00001305 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1306 // Handle the nonnull attribute on the parameters of the
1307 // function/method.
1308 ArrayRef<ParmVarDecl*> parms;
1309 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1310 parms = FD->parameters();
1311 else
1312 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1313
1314 unsigned ParamIndex = 0;
1315 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1316 I != E; ++I, ++ParamIndex) {
1317 const ParmVarDecl *PVD = *I;
1318 if (PVD->hasAttr<NonNullAttr>() ||
1319 isNonNullType(S.Context, PVD->getType())) {
1320 if (NonNullArgs.empty())
1321 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001322
Douglas Gregorb4866e82015-06-19 18:13:19 +00001323 NonNullArgs.set(ParamIndex);
1324 }
1325 }
1326 } else {
1327 // If we have a non-function, non-method declaration but no
1328 // function prototype, try to dig out the function prototype.
1329 if (!Proto) {
1330 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1331 QualType type = VD->getType().getNonReferenceType();
1332 if (auto pointerType = type->getAs<PointerType>())
1333 type = pointerType->getPointeeType();
1334 else if (auto blockType = type->getAs<BlockPointerType>())
1335 type = blockType->getPointeeType();
1336 // FIXME: data member pointers?
1337
1338 // Dig out the function prototype, if there is one.
1339 Proto = type->getAs<FunctionProtoType>();
1340 }
1341 }
1342
1343 // Fill in non-null argument information from the nullability
1344 // information on the parameter types (if we have them).
1345 if (Proto) {
1346 unsigned Index = 0;
1347 for (auto paramType : Proto->getParamTypes()) {
1348 if (isNonNullType(S.Context, paramType)) {
1349 if (NonNullArgs.empty())
1350 NonNullArgs.resize(Args.size());
1351
1352 NonNullArgs.set(Index);
1353 }
1354
1355 ++Index;
1356 }
1357 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001358 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001359
Douglas Gregorb4866e82015-06-19 18:13:19 +00001360 // Check for non-null arguments.
1361 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1362 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001363 if (NonNullArgs[ArgIndex])
1364 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001365 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001366}
1367
Richard Smith55ce3522012-06-25 20:30:08 +00001368/// Handles the checks for format strings, non-POD arguments to vararg
1369/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001370void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1371 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001372 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001373 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001374 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001375 if (CurContext->isDependentContext())
1376 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001377
Ted Kremenekb8176da2010-09-09 04:33:05 +00001378 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001379 llvm::SmallBitVector CheckedVarArgs;
1380 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001381 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001382 // Only create vector if there are format attributes.
1383 CheckedVarArgs.resize(Args.size());
1384
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001385 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001386 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001387 }
Richard Smithd7293d72013-08-05 18:49:43 +00001388 }
Richard Smith55ce3522012-06-25 20:30:08 +00001389
1390 // Refuse POD arguments that weren't caught by the format string
1391 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001392 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001393 unsigned NumParams = Proto ? Proto->getNumParams()
1394 : FDecl && isa<FunctionDecl>(FDecl)
1395 ? cast<FunctionDecl>(FDecl)->getNumParams()
1396 : FDecl && isa<ObjCMethodDecl>(FDecl)
1397 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1398 : 0;
1399
Alp Toker9cacbab2014-01-20 20:26:09 +00001400 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001401 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001402 if (const Expr *Arg = Args[ArgIdx]) {
1403 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1404 checkVariadicArgument(Arg, CallType);
1405 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001406 }
Richard Smithd7293d72013-08-05 18:49:43 +00001407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Douglas Gregorb4866e82015-06-19 18:13:19 +00001409 if (FDecl || Proto) {
1410 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001411
Richard Trieu41bc0992013-06-22 00:20:41 +00001412 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001413 if (FDecl) {
1414 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1415 CheckArgumentWithTypeTag(I, Args.data());
1416 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001417 }
Richard Smith55ce3522012-06-25 20:30:08 +00001418}
1419
1420/// CheckConstructorCall - Check a constructor call for correctness and safety
1421/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001422void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1423 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001424 const FunctionProtoType *Proto,
1425 SourceLocation Loc) {
1426 VariadicCallType CallType =
1427 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001428 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1429 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001430}
1431
1432/// CheckFunctionCall - Check a direct function call for various correctness
1433/// and safety properties not strictly enforced by the C type system.
1434bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1435 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001436 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1437 isa<CXXMethodDecl>(FDecl);
1438 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1439 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001440 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1441 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001442 Expr** Args = TheCall->getArgs();
1443 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001444 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001445 // If this is a call to a member operator, hide the first argument
1446 // from checkCall.
1447 // FIXME: Our choice of AST representation here is less than ideal.
1448 ++Args;
1449 --NumArgs;
1450 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001451 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001452 IsMemberFunction, TheCall->getRParenLoc(),
1453 TheCall->getCallee()->getSourceRange(), CallType);
1454
1455 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1456 // None of the checks below are needed for functions that don't have
1457 // simple names (e.g., C++ conversion functions).
1458 if (!FnInfo)
1459 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001460
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001461 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001462 if (getLangOpts().ObjC1)
1463 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001464
Anna Zaks22122702012-01-17 00:37:07 +00001465 unsigned CMId = FDecl->getMemoryFunctionKind();
1466 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001467 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001468
Anna Zaks201d4892012-01-13 21:52:01 +00001469 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001470 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001471 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001472 else if (CMId == Builtin::BIstrncat)
1473 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001474 else
Anna Zaks22122702012-01-17 00:37:07 +00001475 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001476
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001477 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001478}
1479
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001480bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001481 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001482 VariadicCallType CallType =
1483 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001484
Douglas Gregorb4866e82015-06-19 18:13:19 +00001485 checkCall(Method, nullptr, Args,
1486 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1487 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001488
1489 return false;
1490}
1491
Richard Trieu664c4c62013-06-20 21:03:13 +00001492bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1493 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001494 QualType Ty;
1495 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001496 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001497 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001498 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001499 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001500 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001501
Douglas Gregorb4866e82015-06-19 18:13:19 +00001502 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1503 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001504 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001505
Richard Trieu664c4c62013-06-20 21:03:13 +00001506 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001507 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001508 CallType = VariadicDoesNotApply;
1509 } else if (Ty->isBlockPointerType()) {
1510 CallType = VariadicBlock;
1511 } else { // Ty->isFunctionPointerType()
1512 CallType = VariadicFunction;
1513 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001514
Douglas Gregorb4866e82015-06-19 18:13:19 +00001515 checkCall(NDecl, Proto,
1516 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1517 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001518 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001519
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001520 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001521}
1522
Richard Trieu41bc0992013-06-22 00:20:41 +00001523/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1524/// such as function pointers returned from functions.
1525bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001526 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001527 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001528 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001529 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001530 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001531 TheCall->getCallee()->getSourceRange(), CallType);
1532
1533 return false;
1534}
1535
Tim Northovere94a34c2014-03-11 10:49:14 +00001536static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1537 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1538 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1539 return false;
1540
1541 switch (Op) {
1542 case AtomicExpr::AO__c11_atomic_init:
1543 llvm_unreachable("There is no ordering argument for an init");
1544
1545 case AtomicExpr::AO__c11_atomic_load:
1546 case AtomicExpr::AO__atomic_load_n:
1547 case AtomicExpr::AO__atomic_load:
1548 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1549 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1550
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_store:
1553 case AtomicExpr::AO__atomic_store_n:
1554 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1555 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1556 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1557
1558 default:
1559 return true;
1560 }
1561}
1562
Richard Smithfeea8832012-04-12 05:08:17 +00001563ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1564 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001565 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1566 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001567
Richard Smithfeea8832012-04-12 05:08:17 +00001568 // All these operations take one of the following forms:
1569 enum {
1570 // C __c11_atomic_init(A *, C)
1571 Init,
1572 // C __c11_atomic_load(A *, int)
1573 Load,
1574 // void __atomic_load(A *, CP, int)
1575 Copy,
1576 // C __c11_atomic_add(A *, M, int)
1577 Arithmetic,
1578 // C __atomic_exchange_n(A *, CP, int)
1579 Xchg,
1580 // void __atomic_exchange(A *, C *, CP, int)
1581 GNUXchg,
1582 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1583 C11CmpXchg,
1584 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1585 GNUCmpXchg
1586 } Form = Init;
1587 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1588 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1589 // where:
1590 // C is an appropriate type,
1591 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1592 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1593 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1594 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001595
Gabor Horvath98bd0982015-03-16 09:59:54 +00001596 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1597 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1598 AtomicExpr::AO__atomic_load,
1599 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001600 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1601 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1602 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1603 Op == AtomicExpr::AO__atomic_store_n ||
1604 Op == AtomicExpr::AO__atomic_exchange_n ||
1605 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1606 bool IsAddSub = false;
1607
1608 switch (Op) {
1609 case AtomicExpr::AO__c11_atomic_init:
1610 Form = Init;
1611 break;
1612
1613 case AtomicExpr::AO__c11_atomic_load:
1614 case AtomicExpr::AO__atomic_load_n:
1615 Form = Load;
1616 break;
1617
1618 case AtomicExpr::AO__c11_atomic_store:
1619 case AtomicExpr::AO__atomic_load:
1620 case AtomicExpr::AO__atomic_store:
1621 case AtomicExpr::AO__atomic_store_n:
1622 Form = Copy;
1623 break;
1624
1625 case AtomicExpr::AO__c11_atomic_fetch_add:
1626 case AtomicExpr::AO__c11_atomic_fetch_sub:
1627 case AtomicExpr::AO__atomic_fetch_add:
1628 case AtomicExpr::AO__atomic_fetch_sub:
1629 case AtomicExpr::AO__atomic_add_fetch:
1630 case AtomicExpr::AO__atomic_sub_fetch:
1631 IsAddSub = true;
1632 // Fall through.
1633 case AtomicExpr::AO__c11_atomic_fetch_and:
1634 case AtomicExpr::AO__c11_atomic_fetch_or:
1635 case AtomicExpr::AO__c11_atomic_fetch_xor:
1636 case AtomicExpr::AO__atomic_fetch_and:
1637 case AtomicExpr::AO__atomic_fetch_or:
1638 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001639 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001640 case AtomicExpr::AO__atomic_and_fetch:
1641 case AtomicExpr::AO__atomic_or_fetch:
1642 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001643 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001644 Form = Arithmetic;
1645 break;
1646
1647 case AtomicExpr::AO__c11_atomic_exchange:
1648 case AtomicExpr::AO__atomic_exchange_n:
1649 Form = Xchg;
1650 break;
1651
1652 case AtomicExpr::AO__atomic_exchange:
1653 Form = GNUXchg;
1654 break;
1655
1656 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1657 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1658 Form = C11CmpXchg;
1659 break;
1660
1661 case AtomicExpr::AO__atomic_compare_exchange:
1662 case AtomicExpr::AO__atomic_compare_exchange_n:
1663 Form = GNUCmpXchg;
1664 break;
1665 }
1666
1667 // Check we have the right number of arguments.
1668 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001669 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001670 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001671 << TheCall->getCallee()->getSourceRange();
1672 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001673 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1674 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001675 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001676 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001677 << TheCall->getCallee()->getSourceRange();
1678 return ExprError();
1679 }
1680
Richard Smithfeea8832012-04-12 05:08:17 +00001681 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001682 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001683 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1684 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1685 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001686 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001687 << Ptr->getType() << Ptr->getSourceRange();
1688 return ExprError();
1689 }
1690
Richard Smithfeea8832012-04-12 05:08:17 +00001691 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1692 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1693 QualType ValType = AtomTy; // 'C'
1694 if (IsC11) {
1695 if (!AtomTy->isAtomicType()) {
1696 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1697 << Ptr->getType() << Ptr->getSourceRange();
1698 return ExprError();
1699 }
Richard Smithe00921a2012-09-15 06:09:58 +00001700 if (AtomTy.isConstQualified()) {
1701 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1702 << Ptr->getType() << Ptr->getSourceRange();
1703 return ExprError();
1704 }
Richard Smithfeea8832012-04-12 05:08:17 +00001705 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001706 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1707 if (ValType.isConstQualified()) {
1708 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1709 << Ptr->getType() << Ptr->getSourceRange();
1710 return ExprError();
1711 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001712 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001713
Richard Smithfeea8832012-04-12 05:08:17 +00001714 // For an arithmetic operation, the implied arithmetic must be well-formed.
1715 if (Form == Arithmetic) {
1716 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1717 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1718 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1719 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1720 return ExprError();
1721 }
1722 if (!IsAddSub && !ValType->isIntegerType()) {
1723 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1724 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1725 return ExprError();
1726 }
David Majnemere85cff82015-01-28 05:48:06 +00001727 if (IsC11 && ValType->isPointerType() &&
1728 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1729 diag::err_incomplete_type)) {
1730 return ExprError();
1731 }
Richard Smithfeea8832012-04-12 05:08:17 +00001732 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1733 // For __atomic_*_n operations, the value type must be a scalar integral or
1734 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001735 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001736 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1737 return ExprError();
1738 }
1739
Eli Friedmanaa769812013-09-11 03:49:34 +00001740 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1741 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001742 // For GNU atomics, require a trivially-copyable type. This is not part of
1743 // the GNU atomics specification, but we enforce it for sanity.
1744 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001745 << Ptr->getType() << Ptr->getSourceRange();
1746 return ExprError();
1747 }
1748
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001749 switch (ValType.getObjCLifetime()) {
1750 case Qualifiers::OCL_None:
1751 case Qualifiers::OCL_ExplicitNone:
1752 // okay
1753 break;
1754
1755 case Qualifiers::OCL_Weak:
1756 case Qualifiers::OCL_Strong:
1757 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001758 // FIXME: Can this happen? By this point, ValType should be known
1759 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1761 << ValType << Ptr->getSourceRange();
1762 return ExprError();
1763 }
1764
David Majnemerc6eb6502015-06-03 00:26:35 +00001765 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1766 // volatile-ness of the pointee-type inject itself into the result or the
1767 // other operands.
1768 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001769 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001770 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001771 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001772 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001773 ResultType = Context.BoolTy;
1774
Richard Smithfeea8832012-04-12 05:08:17 +00001775 // The type of a parameter passed 'by value'. In the GNU atomics, such
1776 // arguments are actually passed as pointers.
1777 QualType ByValType = ValType; // 'CP'
1778 if (!IsC11 && !IsN)
1779 ByValType = Ptr->getType();
1780
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001781 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1782 // but not the second argument. We need to manually remove possible const
1783 // qualifiers.
1784
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001785 // The first argument --- the pointer --- has a fixed type; we
1786 // deduce the types of the rest of the arguments accordingly. Walk
1787 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001788 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001789 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001790 if (i < NumVals[Form] + 1) {
1791 switch (i) {
1792 case 1:
1793 // The second argument is the non-atomic operand. For arithmetic, this
1794 // is always passed by value, and for a compare_exchange it is always
1795 // passed by address. For the rest, GNU uses by-address and C11 uses
1796 // by-value.
1797 assert(Form != Load);
1798 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1799 Ty = ValType;
1800 else if (Form == Copy || Form == Xchg)
1801 Ty = ByValType;
1802 else if (Form == Arithmetic)
1803 Ty = Context.getPointerDiffType();
1804 else
1805 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1806 break;
1807 case 2:
1808 // The third argument to compare_exchange / GNU exchange is a
1809 // (pointer to a) desired value.
1810 Ty = ByValType;
1811 break;
1812 case 3:
1813 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1814 Ty = Context.BoolTy;
1815 break;
1816 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001817 } else {
1818 // The order(s) are always converted to int.
1819 Ty = Context.IntTy;
1820 }
Richard Smithfeea8832012-04-12 05:08:17 +00001821
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001822 InitializedEntity Entity =
1823 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001824 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001825 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1826 if (Arg.isInvalid())
1827 return true;
1828 TheCall->setArg(i, Arg.get());
1829 }
1830
Richard Smithfeea8832012-04-12 05:08:17 +00001831 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001832 SmallVector<Expr*, 5> SubExprs;
1833 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001834 switch (Form) {
1835 case Init:
1836 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001837 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001838 break;
1839 case Load:
1840 SubExprs.push_back(TheCall->getArg(1)); // Order
1841 break;
1842 case Copy:
1843 case Arithmetic:
1844 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001845 SubExprs.push_back(TheCall->getArg(2)); // Order
1846 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001847 break;
1848 case GNUXchg:
1849 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1850 SubExprs.push_back(TheCall->getArg(3)); // Order
1851 SubExprs.push_back(TheCall->getArg(1)); // Val1
1852 SubExprs.push_back(TheCall->getArg(2)); // Val2
1853 break;
1854 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001855 SubExprs.push_back(TheCall->getArg(3)); // Order
1856 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001857 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001858 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001859 break;
1860 case GNUCmpXchg:
1861 SubExprs.push_back(TheCall->getArg(4)); // Order
1862 SubExprs.push_back(TheCall->getArg(1)); // Val1
1863 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1864 SubExprs.push_back(TheCall->getArg(2)); // Val2
1865 SubExprs.push_back(TheCall->getArg(3)); // Weak
1866 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001867 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001868
1869 if (SubExprs.size() >= 2 && Form != Init) {
1870 llvm::APSInt Result(32);
1871 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1872 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001873 Diag(SubExprs[1]->getLocStart(),
1874 diag::warn_atomic_op_has_invalid_memory_order)
1875 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001876 }
1877
Fariborz Jahanian615de762013-05-28 17:37:39 +00001878 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1879 SubExprs, ResultType, Op,
1880 TheCall->getRParenLoc());
1881
1882 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1883 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1884 Context.AtomicUsesUnsupportedLibcall(AE))
1885 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1886 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001887
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001888 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001889}
1890
1891
John McCall29ad95b2011-08-27 01:09:30 +00001892/// checkBuiltinArgument - Given a call to a builtin function, perform
1893/// normal type-checking on the given argument, updating the call in
1894/// place. This is useful when a builtin function requires custom
1895/// type-checking for some of its arguments but not necessarily all of
1896/// them.
1897///
1898/// Returns true on error.
1899static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1900 FunctionDecl *Fn = E->getDirectCallee();
1901 assert(Fn && "builtin call without direct callee!");
1902
1903 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1904 InitializedEntity Entity =
1905 InitializedEntity::InitializeParameter(S.Context, Param);
1906
1907 ExprResult Arg = E->getArg(0);
1908 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1909 if (Arg.isInvalid())
1910 return true;
1911
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001912 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001913 return false;
1914}
1915
Chris Lattnerdc046542009-05-08 06:58:22 +00001916/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1917/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1918/// type of its first argument. The main ActOnCallExpr routines have already
1919/// promoted the types of arguments because all of these calls are prototyped as
1920/// void(...).
1921///
1922/// This function goes through and does final semantic checking for these
1923/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001924ExprResult
1925Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001926 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001927 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1928 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1929
1930 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001931 if (TheCall->getNumArgs() < 1) {
1932 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1933 << 0 << 1 << TheCall->getNumArgs()
1934 << TheCall->getCallee()->getSourceRange();
1935 return ExprError();
1936 }
Mike Stump11289f42009-09-09 15:08:12 +00001937
Chris Lattnerdc046542009-05-08 06:58:22 +00001938 // Inspect the first argument of the atomic builtin. This should always be
1939 // a pointer type, whose element is an integral scalar or pointer type.
1940 // Because it is a pointer type, we don't have to worry about any implicit
1941 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001942 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001943 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001944 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1945 if (FirstArgResult.isInvalid())
1946 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001947 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001948 TheCall->setArg(0, FirstArg);
1949
John McCall31168b02011-06-15 23:02:42 +00001950 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1951 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001952 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1953 << FirstArg->getType() << FirstArg->getSourceRange();
1954 return ExprError();
1955 }
Mike Stump11289f42009-09-09 15:08:12 +00001956
John McCall31168b02011-06-15 23:02:42 +00001957 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001958 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001959 !ValType->isBlockPointerType()) {
1960 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1961 << FirstArg->getType() << FirstArg->getSourceRange();
1962 return ExprError();
1963 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001964
John McCall31168b02011-06-15 23:02:42 +00001965 switch (ValType.getObjCLifetime()) {
1966 case Qualifiers::OCL_None:
1967 case Qualifiers::OCL_ExplicitNone:
1968 // okay
1969 break;
1970
1971 case Qualifiers::OCL_Weak:
1972 case Qualifiers::OCL_Strong:
1973 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001974 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001975 << ValType << FirstArg->getSourceRange();
1976 return ExprError();
1977 }
1978
John McCallb50451a2011-10-05 07:41:44 +00001979 // Strip any qualifiers off ValType.
1980 ValType = ValType.getUnqualifiedType();
1981
Chandler Carruth3973af72010-07-18 20:54:12 +00001982 // The majority of builtins return a value, but a few have special return
1983 // types, so allow them to override appropriately below.
1984 QualType ResultType = ValType;
1985
Chris Lattnerdc046542009-05-08 06:58:22 +00001986 // We need to figure out which concrete builtin this maps onto. For example,
1987 // __sync_fetch_and_add with a 2 byte object turns into
1988 // __sync_fetch_and_add_2.
1989#define BUILTIN_ROW(x) \
1990 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1991 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001992
Chris Lattnerdc046542009-05-08 06:58:22 +00001993 static const unsigned BuiltinIndices[][5] = {
1994 BUILTIN_ROW(__sync_fetch_and_add),
1995 BUILTIN_ROW(__sync_fetch_and_sub),
1996 BUILTIN_ROW(__sync_fetch_and_or),
1997 BUILTIN_ROW(__sync_fetch_and_and),
1998 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001999 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002000
Chris Lattnerdc046542009-05-08 06:58:22 +00002001 BUILTIN_ROW(__sync_add_and_fetch),
2002 BUILTIN_ROW(__sync_sub_and_fetch),
2003 BUILTIN_ROW(__sync_and_and_fetch),
2004 BUILTIN_ROW(__sync_or_and_fetch),
2005 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002006 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002007
Chris Lattnerdc046542009-05-08 06:58:22 +00002008 BUILTIN_ROW(__sync_val_compare_and_swap),
2009 BUILTIN_ROW(__sync_bool_compare_and_swap),
2010 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002011 BUILTIN_ROW(__sync_lock_release),
2012 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002013 };
Mike Stump11289f42009-09-09 15:08:12 +00002014#undef BUILTIN_ROW
2015
Chris Lattnerdc046542009-05-08 06:58:22 +00002016 // Determine the index of the size.
2017 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002018 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002019 case 1: SizeIndex = 0; break;
2020 case 2: SizeIndex = 1; break;
2021 case 4: SizeIndex = 2; break;
2022 case 8: SizeIndex = 3; break;
2023 case 16: SizeIndex = 4; break;
2024 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002025 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2026 << FirstArg->getType() << FirstArg->getSourceRange();
2027 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Chris Lattnerdc046542009-05-08 06:58:22 +00002030 // Each of these builtins has one pointer argument, followed by some number of
2031 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2032 // that we ignore. Find out which row of BuiltinIndices to read from as well
2033 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002034 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002035 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002036 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002037 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002038 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002039 case Builtin::BI__sync_fetch_and_add:
2040 case Builtin::BI__sync_fetch_and_add_1:
2041 case Builtin::BI__sync_fetch_and_add_2:
2042 case Builtin::BI__sync_fetch_and_add_4:
2043 case Builtin::BI__sync_fetch_and_add_8:
2044 case Builtin::BI__sync_fetch_and_add_16:
2045 BuiltinIndex = 0;
2046 break;
2047
2048 case Builtin::BI__sync_fetch_and_sub:
2049 case Builtin::BI__sync_fetch_and_sub_1:
2050 case Builtin::BI__sync_fetch_and_sub_2:
2051 case Builtin::BI__sync_fetch_and_sub_4:
2052 case Builtin::BI__sync_fetch_and_sub_8:
2053 case Builtin::BI__sync_fetch_and_sub_16:
2054 BuiltinIndex = 1;
2055 break;
2056
2057 case Builtin::BI__sync_fetch_and_or:
2058 case Builtin::BI__sync_fetch_and_or_1:
2059 case Builtin::BI__sync_fetch_and_or_2:
2060 case Builtin::BI__sync_fetch_and_or_4:
2061 case Builtin::BI__sync_fetch_and_or_8:
2062 case Builtin::BI__sync_fetch_and_or_16:
2063 BuiltinIndex = 2;
2064 break;
2065
2066 case Builtin::BI__sync_fetch_and_and:
2067 case Builtin::BI__sync_fetch_and_and_1:
2068 case Builtin::BI__sync_fetch_and_and_2:
2069 case Builtin::BI__sync_fetch_and_and_4:
2070 case Builtin::BI__sync_fetch_and_and_8:
2071 case Builtin::BI__sync_fetch_and_and_16:
2072 BuiltinIndex = 3;
2073 break;
Mike Stump11289f42009-09-09 15:08:12 +00002074
Douglas Gregor73722482011-11-28 16:30:08 +00002075 case Builtin::BI__sync_fetch_and_xor:
2076 case Builtin::BI__sync_fetch_and_xor_1:
2077 case Builtin::BI__sync_fetch_and_xor_2:
2078 case Builtin::BI__sync_fetch_and_xor_4:
2079 case Builtin::BI__sync_fetch_and_xor_8:
2080 case Builtin::BI__sync_fetch_and_xor_16:
2081 BuiltinIndex = 4;
2082 break;
2083
Hal Finkeld2208b52014-10-02 20:53:50 +00002084 case Builtin::BI__sync_fetch_and_nand:
2085 case Builtin::BI__sync_fetch_and_nand_1:
2086 case Builtin::BI__sync_fetch_and_nand_2:
2087 case Builtin::BI__sync_fetch_and_nand_4:
2088 case Builtin::BI__sync_fetch_and_nand_8:
2089 case Builtin::BI__sync_fetch_and_nand_16:
2090 BuiltinIndex = 5;
2091 WarnAboutSemanticsChange = true;
2092 break;
2093
Douglas Gregor73722482011-11-28 16:30:08 +00002094 case Builtin::BI__sync_add_and_fetch:
2095 case Builtin::BI__sync_add_and_fetch_1:
2096 case Builtin::BI__sync_add_and_fetch_2:
2097 case Builtin::BI__sync_add_and_fetch_4:
2098 case Builtin::BI__sync_add_and_fetch_8:
2099 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002100 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002101 break;
2102
2103 case Builtin::BI__sync_sub_and_fetch:
2104 case Builtin::BI__sync_sub_and_fetch_1:
2105 case Builtin::BI__sync_sub_and_fetch_2:
2106 case Builtin::BI__sync_sub_and_fetch_4:
2107 case Builtin::BI__sync_sub_and_fetch_8:
2108 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002109 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002110 break;
2111
2112 case Builtin::BI__sync_and_and_fetch:
2113 case Builtin::BI__sync_and_and_fetch_1:
2114 case Builtin::BI__sync_and_and_fetch_2:
2115 case Builtin::BI__sync_and_and_fetch_4:
2116 case Builtin::BI__sync_and_and_fetch_8:
2117 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002118 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002119 break;
2120
2121 case Builtin::BI__sync_or_and_fetch:
2122 case Builtin::BI__sync_or_and_fetch_1:
2123 case Builtin::BI__sync_or_and_fetch_2:
2124 case Builtin::BI__sync_or_and_fetch_4:
2125 case Builtin::BI__sync_or_and_fetch_8:
2126 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002127 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002128 break;
2129
2130 case Builtin::BI__sync_xor_and_fetch:
2131 case Builtin::BI__sync_xor_and_fetch_1:
2132 case Builtin::BI__sync_xor_and_fetch_2:
2133 case Builtin::BI__sync_xor_and_fetch_4:
2134 case Builtin::BI__sync_xor_and_fetch_8:
2135 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002136 BuiltinIndex = 10;
2137 break;
2138
2139 case Builtin::BI__sync_nand_and_fetch:
2140 case Builtin::BI__sync_nand_and_fetch_1:
2141 case Builtin::BI__sync_nand_and_fetch_2:
2142 case Builtin::BI__sync_nand_and_fetch_4:
2143 case Builtin::BI__sync_nand_and_fetch_8:
2144 case Builtin::BI__sync_nand_and_fetch_16:
2145 BuiltinIndex = 11;
2146 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002147 break;
Mike Stump11289f42009-09-09 15:08:12 +00002148
Chris Lattnerdc046542009-05-08 06:58:22 +00002149 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002150 case Builtin::BI__sync_val_compare_and_swap_1:
2151 case Builtin::BI__sync_val_compare_and_swap_2:
2152 case Builtin::BI__sync_val_compare_and_swap_4:
2153 case Builtin::BI__sync_val_compare_and_swap_8:
2154 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002155 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002156 NumFixed = 2;
2157 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002158
Chris Lattnerdc046542009-05-08 06:58:22 +00002159 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002160 case Builtin::BI__sync_bool_compare_and_swap_1:
2161 case Builtin::BI__sync_bool_compare_and_swap_2:
2162 case Builtin::BI__sync_bool_compare_and_swap_4:
2163 case Builtin::BI__sync_bool_compare_and_swap_8:
2164 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002165 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002166 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002167 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002168 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002169
2170 case Builtin::BI__sync_lock_test_and_set:
2171 case Builtin::BI__sync_lock_test_and_set_1:
2172 case Builtin::BI__sync_lock_test_and_set_2:
2173 case Builtin::BI__sync_lock_test_and_set_4:
2174 case Builtin::BI__sync_lock_test_and_set_8:
2175 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002176 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002177 break;
2178
Chris Lattnerdc046542009-05-08 06:58:22 +00002179 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002180 case Builtin::BI__sync_lock_release_1:
2181 case Builtin::BI__sync_lock_release_2:
2182 case Builtin::BI__sync_lock_release_4:
2183 case Builtin::BI__sync_lock_release_8:
2184 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002185 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002186 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002187 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002188 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002189
2190 case Builtin::BI__sync_swap:
2191 case Builtin::BI__sync_swap_1:
2192 case Builtin::BI__sync_swap_2:
2193 case Builtin::BI__sync_swap_4:
2194 case Builtin::BI__sync_swap_8:
2195 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002196 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002197 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002198 }
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattnerdc046542009-05-08 06:58:22 +00002200 // Now that we know how many fixed arguments we expect, first check that we
2201 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002202 if (TheCall->getNumArgs() < 1+NumFixed) {
2203 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2204 << 0 << 1+NumFixed << TheCall->getNumArgs()
2205 << TheCall->getCallee()->getSourceRange();
2206 return ExprError();
2207 }
Mike Stump11289f42009-09-09 15:08:12 +00002208
Hal Finkeld2208b52014-10-02 20:53:50 +00002209 if (WarnAboutSemanticsChange) {
2210 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2211 << TheCall->getCallee()->getSourceRange();
2212 }
2213
Chris Lattner5b9241b2009-05-08 15:36:58 +00002214 // Get the decl for the concrete builtin from this, we can tell what the
2215 // concrete integer type we should convert to is.
2216 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002217 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002218 FunctionDecl *NewBuiltinDecl;
2219 if (NewBuiltinID == BuiltinID)
2220 NewBuiltinDecl = FDecl;
2221 else {
2222 // Perform builtin lookup to avoid redeclaring it.
2223 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2224 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2225 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2226 assert(Res.getFoundDecl());
2227 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002228 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002229 return ExprError();
2230 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002231
John McCallcf142162010-08-07 06:22:56 +00002232 // The first argument --- the pointer --- has a fixed type; we
2233 // deduce the types of the rest of the arguments accordingly. Walk
2234 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002235 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002236 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002237
Chris Lattnerdc046542009-05-08 06:58:22 +00002238 // GCC does an implicit conversion to the pointer or integer ValType. This
2239 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002240 // Initialize the argument.
2241 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2242 ValType, /*consume*/ false);
2243 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002244 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002245 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002246
Chris Lattnerdc046542009-05-08 06:58:22 +00002247 // Okay, we have something that *can* be converted to the right type. Check
2248 // to see if there is a potentially weird extension going on here. This can
2249 // happen when you do an atomic operation on something like an char* and
2250 // pass in 42. The 42 gets converted to char. This is even more strange
2251 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002252 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002253 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002254 }
Mike Stump11289f42009-09-09 15:08:12 +00002255
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002256 ASTContext& Context = this->getASTContext();
2257
2258 // Create a new DeclRefExpr to refer to the new decl.
2259 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2260 Context,
2261 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002262 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002263 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002264 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002265 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002266 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002267 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002268
Chris Lattnerdc046542009-05-08 06:58:22 +00002269 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002270 // FIXME: This loses syntactic information.
2271 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2272 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2273 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002274 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002276 // Change the result type of the call to match the original value type. This
2277 // is arbitrary, but the codegen for these builtins ins design to handle it
2278 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002279 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002280
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002281 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002282}
2283
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002284/// SemaBuiltinNontemporalOverloaded - We have a call to
2285/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2286/// overloaded function based on the pointer type of its last argument.
2287///
2288/// This function goes through and does final semantic checking for these
2289/// builtins.
2290ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2291 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2292 DeclRefExpr *DRE =
2293 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2294 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2295 unsigned BuiltinID = FDecl->getBuiltinID();
2296 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2297 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2298 "Unexpected nontemporal load/store builtin!");
2299 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2300 unsigned numArgs = isStore ? 2 : 1;
2301
2302 // Ensure that we have the proper number of arguments.
2303 if (checkArgCount(*this, TheCall, numArgs))
2304 return ExprError();
2305
2306 // Inspect the last argument of the nontemporal builtin. This should always
2307 // be a pointer type, from which we imply the type of the memory access.
2308 // Because it is a pointer type, we don't have to worry about any implicit
2309 // casts here.
2310 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2311 ExprResult PointerArgResult =
2312 DefaultFunctionArrayLvalueConversion(PointerArg);
2313
2314 if (PointerArgResult.isInvalid())
2315 return ExprError();
2316 PointerArg = PointerArgResult.get();
2317 TheCall->setArg(numArgs - 1, PointerArg);
2318
2319 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2320 if (!pointerType) {
2321 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2322 << PointerArg->getType() << PointerArg->getSourceRange();
2323 return ExprError();
2324 }
2325
2326 QualType ValType = pointerType->getPointeeType();
2327
2328 // Strip any qualifiers off ValType.
2329 ValType = ValType.getUnqualifiedType();
2330 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2331 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2332 !ValType->isVectorType()) {
2333 Diag(DRE->getLocStart(),
2334 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2335 << PointerArg->getType() << PointerArg->getSourceRange();
2336 return ExprError();
2337 }
2338
2339 if (!isStore) {
2340 TheCall->setType(ValType);
2341 return TheCallResult;
2342 }
2343
2344 ExprResult ValArg = TheCall->getArg(0);
2345 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2346 Context, ValType, /*consume*/ false);
2347 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2348 if (ValArg.isInvalid())
2349 return ExprError();
2350
2351 TheCall->setArg(0, ValArg.get());
2352 TheCall->setType(Context.VoidTy);
2353 return TheCallResult;
2354}
2355
Chris Lattner6436fb62009-02-18 06:01:06 +00002356/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002357/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002358/// Note: It might also make sense to do the UTF-16 conversion here (would
2359/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002360bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002361 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002362 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2363
Douglas Gregorfb65e592011-07-27 05:40:30 +00002364 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002365 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2366 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002367 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002370 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002371 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002372 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002373 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002374 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002375 UTF16 *ToPtr = &ToBuf[0];
2376
2377 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2378 &ToPtr, ToPtr + NumBytes,
2379 strictConversion);
2380 // Check for conversion failure.
2381 if (Result != conversionOK)
2382 Diag(Arg->getLocStart(),
2383 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2384 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002385 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002386}
2387
Charles Davisc7d5c942015-09-17 20:55:33 +00002388/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2389/// for validity. Emit an error and return true on failure; return false
2390/// on success.
2391bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002392 Expr *Fn = TheCall->getCallee();
2393 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002394 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002395 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002396 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2397 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002398 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002399 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002400 return true;
2401 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002402
2403 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002404 return Diag(TheCall->getLocEnd(),
2405 diag::err_typecheck_call_too_few_args_at_least)
2406 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002407 }
2408
John McCall29ad95b2011-08-27 01:09:30 +00002409 // Type-check the first argument normally.
2410 if (checkBuiltinArgument(*this, TheCall, 0))
2411 return true;
2412
Chris Lattnere202e6a2007-12-20 00:05:45 +00002413 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002414 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002415 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002416 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002417 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002418 else if (FunctionDecl *FD = getCurFunctionDecl())
2419 isVariadic = FD->isVariadic();
2420 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002421 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002422
Chris Lattnere202e6a2007-12-20 00:05:45 +00002423 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002424 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2425 return true;
2426 }
Mike Stump11289f42009-09-09 15:08:12 +00002427
Chris Lattner43be2e62007-12-19 23:59:04 +00002428 // Verify that the second argument to the builtin is the last argument of the
2429 // current function or method.
2430 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002431 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002432
Nico Weber9eea7642013-05-24 23:31:57 +00002433 // These are valid if SecondArgIsLastNamedArgument is false after the next
2434 // block.
2435 QualType Type;
2436 SourceLocation ParamLoc;
2437
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002438 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2439 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002440 // FIXME: This isn't correct for methods (results in bogus warning).
2441 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002442 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002443 if (CurBlock)
2444 LastArg = *(CurBlock->TheDecl->param_end()-1);
2445 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002446 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002447 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002448 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002449 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002450
2451 Type = PV->getType();
2452 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002453 }
2454 }
Mike Stump11289f42009-09-09 15:08:12 +00002455
Chris Lattner43be2e62007-12-19 23:59:04 +00002456 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002457 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002458 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002459 else if (Type->isReferenceType()) {
2460 Diag(Arg->getLocStart(),
2461 diag::warn_va_start_of_reference_type_is_undefined);
2462 Diag(ParamLoc, diag::note_parameter_type) << Type;
2463 }
2464
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002465 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002466 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002467}
Chris Lattner43be2e62007-12-19 23:59:04 +00002468
Charles Davisc7d5c942015-09-17 20:55:33 +00002469/// Check the arguments to '__builtin_va_start' for validity, and that
2470/// it was called from a function of the native ABI.
2471/// Emit an error and return true on failure; return false on success.
2472bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2473 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2474 // On x64 Windows, don't allow this in System V ABI functions.
2475 // (Yes, that means there's no corresponding way to support variadic
2476 // System V ABI functions on Windows.)
2477 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2478 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2479 clang::CallingConv CC = CC_C;
2480 if (const FunctionDecl *FD = getCurFunctionDecl())
2481 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2482 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2483 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2484 return Diag(TheCall->getCallee()->getLocStart(),
2485 diag::err_va_start_used_in_wrong_abi_function)
2486 << (OS != llvm::Triple::Win32);
2487 }
2488 return SemaBuiltinVAStartImpl(TheCall);
2489}
2490
2491/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2492/// it was called from a Win64 ABI function.
2493/// Emit an error and return true on failure; return false on success.
2494bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2495 // This only makes sense for x86-64.
2496 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2497 Expr *Callee = TheCall->getCallee();
2498 if (TT.getArch() != llvm::Triple::x86_64)
2499 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2500 // Don't allow this in System V ABI functions.
2501 clang::CallingConv CC = CC_C;
2502 if (const FunctionDecl *FD = getCurFunctionDecl())
2503 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2504 if (CC == CC_X86_64SysV ||
2505 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2506 return Diag(Callee->getLocStart(),
2507 diag::err_ms_va_start_used_in_sysv_function);
2508 return SemaBuiltinVAStartImpl(TheCall);
2509}
2510
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002511bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2512 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2513 // const char *named_addr);
2514
2515 Expr *Func = Call->getCallee();
2516
2517 if (Call->getNumArgs() < 3)
2518 return Diag(Call->getLocEnd(),
2519 diag::err_typecheck_call_too_few_args_at_least)
2520 << 0 /*function call*/ << 3 << Call->getNumArgs();
2521
2522 // Determine whether the current function is variadic or not.
2523 bool IsVariadic;
2524 if (BlockScopeInfo *CurBlock = getCurBlock())
2525 IsVariadic = CurBlock->TheDecl->isVariadic();
2526 else if (FunctionDecl *FD = getCurFunctionDecl())
2527 IsVariadic = FD->isVariadic();
2528 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2529 IsVariadic = MD->isVariadic();
2530 else
2531 llvm_unreachable("unexpected statement type");
2532
2533 if (!IsVariadic) {
2534 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2535 return true;
2536 }
2537
2538 // Type-check the first argument normally.
2539 if (checkBuiltinArgument(*this, Call, 0))
2540 return true;
2541
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002542 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002543 unsigned ArgNo;
2544 QualType Type;
2545 } ArgumentTypes[] = {
2546 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2547 { 2, Context.getSizeType() },
2548 };
2549
2550 for (const auto &AT : ArgumentTypes) {
2551 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2552 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2553 continue;
2554 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2555 << Arg->getType() << AT.Type << 1 /* different class */
2556 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2557 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2558 }
2559
2560 return false;
2561}
2562
Chris Lattner2da14fb2007-12-20 00:26:33 +00002563/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2564/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002565bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2566 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002567 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002568 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002569 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002570 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002571 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002572 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002573 << SourceRange(TheCall->getArg(2)->getLocStart(),
2574 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002575
John Wiegley01296292011-04-08 18:41:53 +00002576 ExprResult OrigArg0 = TheCall->getArg(0);
2577 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002578
Chris Lattner2da14fb2007-12-20 00:26:33 +00002579 // Do standard promotions between the two arguments, returning their common
2580 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002581 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002582 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2583 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002584
2585 // Make sure any conversions are pushed back into the call; this is
2586 // type safe since unordered compare builtins are declared as "_Bool
2587 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002588 TheCall->setArg(0, OrigArg0.get());
2589 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002590
John Wiegley01296292011-04-08 18:41:53 +00002591 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002592 return false;
2593
Chris Lattner2da14fb2007-12-20 00:26:33 +00002594 // If the common type isn't a real floating type, then the arguments were
2595 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002596 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002597 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002598 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002599 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2600 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002601
Chris Lattner2da14fb2007-12-20 00:26:33 +00002602 return false;
2603}
2604
Benjamin Kramer634fc102010-02-15 22:42:31 +00002605/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2606/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002607/// to check everything. We expect the last argument to be a floating point
2608/// value.
2609bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2610 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002611 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002612 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002613 if (TheCall->getNumArgs() > NumArgs)
2614 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002615 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002616 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002617 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002618 (*(TheCall->arg_end()-1))->getLocEnd());
2619
Benjamin Kramer64aae502010-02-16 10:07:31 +00002620 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002621
Eli Friedman7e4faac2009-08-31 20:06:00 +00002622 if (OrigArg->isTypeDependent())
2623 return false;
2624
Chris Lattner68784ef2010-05-06 05:50:07 +00002625 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002626 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002627 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002628 diag::err_typecheck_call_invalid_unary_fp)
2629 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002630
Chris Lattner68784ef2010-05-06 05:50:07 +00002631 // If this is an implicit conversion from float -> double, remove it.
2632 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2633 Expr *CastArg = Cast->getSubExpr();
2634 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2635 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2636 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002637 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002638 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002639 }
2640 }
2641
Eli Friedman7e4faac2009-08-31 20:06:00 +00002642 return false;
2643}
2644
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002645/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2646// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002647ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002648 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002649 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002650 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002651 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2652 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002653
Nate Begemana0110022010-06-08 00:16:34 +00002654 // Determine which of the following types of shufflevector we're checking:
2655 // 1) unary, vector mask: (lhs, mask)
2656 // 2) binary, vector mask: (lhs, rhs, mask)
2657 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2658 QualType resType = TheCall->getArg(0)->getType();
2659 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002660
Douglas Gregorc25f7662009-05-19 22:10:17 +00002661 if (!TheCall->getArg(0)->isTypeDependent() &&
2662 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002663 QualType LHSType = TheCall->getArg(0)->getType();
2664 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002665
Craig Topperbaca3892013-07-29 06:47:04 +00002666 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2667 return ExprError(Diag(TheCall->getLocStart(),
2668 diag::err_shufflevector_non_vector)
2669 << SourceRange(TheCall->getArg(0)->getLocStart(),
2670 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002671
Nate Begemana0110022010-06-08 00:16:34 +00002672 numElements = LHSType->getAs<VectorType>()->getNumElements();
2673 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002674
Nate Begemana0110022010-06-08 00:16:34 +00002675 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2676 // with mask. If so, verify that RHS is an integer vector type with the
2677 // same number of elts as lhs.
2678 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002679 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002680 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002681 return ExprError(Diag(TheCall->getLocStart(),
2682 diag::err_shufflevector_incompatible_vector)
2683 << SourceRange(TheCall->getArg(1)->getLocStart(),
2684 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002685 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002686 return ExprError(Diag(TheCall->getLocStart(),
2687 diag::err_shufflevector_incompatible_vector)
2688 << SourceRange(TheCall->getArg(0)->getLocStart(),
2689 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002690 } else if (numElements != numResElements) {
2691 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002692 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002693 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002694 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002695 }
2696
2697 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002698 if (TheCall->getArg(i)->isTypeDependent() ||
2699 TheCall->getArg(i)->isValueDependent())
2700 continue;
2701
Nate Begemana0110022010-06-08 00:16:34 +00002702 llvm::APSInt Result(32);
2703 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2704 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002705 diag::err_shufflevector_nonconstant_argument)
2706 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002707
Craig Topper50ad5b72013-08-03 17:40:38 +00002708 // Allow -1 which will be translated to undef in the IR.
2709 if (Result.isSigned() && Result.isAllOnesValue())
2710 continue;
2711
Chris Lattner7ab824e2008-08-10 02:05:13 +00002712 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002713 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002714 diag::err_shufflevector_argument_too_large)
2715 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002716 }
2717
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002718 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002719
Chris Lattner7ab824e2008-08-10 02:05:13 +00002720 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002721 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002722 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002723 }
2724
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002725 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2726 TheCall->getCallee()->getLocStart(),
2727 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002728}
Chris Lattner43be2e62007-12-19 23:59:04 +00002729
Hal Finkelc4d7c822013-09-18 03:29:45 +00002730/// SemaConvertVectorExpr - Handle __builtin_convertvector
2731ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2732 SourceLocation BuiltinLoc,
2733 SourceLocation RParenLoc) {
2734 ExprValueKind VK = VK_RValue;
2735 ExprObjectKind OK = OK_Ordinary;
2736 QualType DstTy = TInfo->getType();
2737 QualType SrcTy = E->getType();
2738
2739 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2740 return ExprError(Diag(BuiltinLoc,
2741 diag::err_convertvector_non_vector)
2742 << E->getSourceRange());
2743 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2744 return ExprError(Diag(BuiltinLoc,
2745 diag::err_convertvector_non_vector_type));
2746
2747 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2748 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2749 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2750 if (SrcElts != DstElts)
2751 return ExprError(Diag(BuiltinLoc,
2752 diag::err_convertvector_incompatible_vector)
2753 << E->getSourceRange());
2754 }
2755
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002756 return new (Context)
2757 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002758}
2759
Daniel Dunbarb7257262008-07-21 22:59:13 +00002760/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2761// This is declared to take (const void*, ...) and can take two
2762// optional constant int args.
2763bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002764 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002765
Chris Lattner3b054132008-11-19 05:08:23 +00002766 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002767 return Diag(TheCall->getLocEnd(),
2768 diag::err_typecheck_call_too_many_args_at_most)
2769 << 0 /*function call*/ << 3 << NumArgs
2770 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002771
2772 // Argument 0 is checked for us and the remaining arguments must be
2773 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002774 for (unsigned i = 1; i != NumArgs; ++i)
2775 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002776 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002777
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002778 return false;
2779}
2780
Hal Finkelf0417332014-07-17 14:25:55 +00002781/// SemaBuiltinAssume - Handle __assume (MS Extension).
2782// __assume does not evaluate its arguments, and should warn if its argument
2783// has side effects.
2784bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2785 Expr *Arg = TheCall->getArg(0);
2786 if (Arg->isInstantiationDependent()) return false;
2787
2788 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002789 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002790 << Arg->getSourceRange()
2791 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2792
2793 return false;
2794}
2795
2796/// Handle __builtin_assume_aligned. This is declared
2797/// as (const void*, size_t, ...) and can take one optional constant int arg.
2798bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2799 unsigned NumArgs = TheCall->getNumArgs();
2800
2801 if (NumArgs > 3)
2802 return Diag(TheCall->getLocEnd(),
2803 diag::err_typecheck_call_too_many_args_at_most)
2804 << 0 /*function call*/ << 3 << NumArgs
2805 << TheCall->getSourceRange();
2806
2807 // The alignment must be a constant integer.
2808 Expr *Arg = TheCall->getArg(1);
2809
2810 // We can't check the value of a dependent argument.
2811 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2812 llvm::APSInt Result;
2813 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2814 return true;
2815
2816 if (!Result.isPowerOf2())
2817 return Diag(TheCall->getLocStart(),
2818 diag::err_alignment_not_power_of_two)
2819 << Arg->getSourceRange();
2820 }
2821
2822 if (NumArgs > 2) {
2823 ExprResult Arg(TheCall->getArg(2));
2824 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2825 Context.getSizeType(), false);
2826 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2827 if (Arg.isInvalid()) return true;
2828 TheCall->setArg(2, Arg.get());
2829 }
Hal Finkelf0417332014-07-17 14:25:55 +00002830
2831 return false;
2832}
2833
Eric Christopher8d0c6212010-04-17 02:26:23 +00002834/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2835/// TheCall is a constant expression.
2836bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2837 llvm::APSInt &Result) {
2838 Expr *Arg = TheCall->getArg(ArgNum);
2839 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2840 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2841
2842 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2843
2844 if (!Arg->isIntegerConstantExpr(Result, Context))
2845 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002846 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002847
Chris Lattnerd545ad12009-09-23 06:06:36 +00002848 return false;
2849}
2850
Richard Sandiford28940af2014-04-16 08:47:51 +00002851/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2852/// TheCall is a constant expression in the range [Low, High].
2853bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2854 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002855 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002856
2857 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002858 Expr *Arg = TheCall->getArg(ArgNum);
2859 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002860 return false;
2861
Eric Christopher8d0c6212010-04-17 02:26:23 +00002862 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002863 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002864 return true;
2865
Richard Sandiford28940af2014-04-16 08:47:51 +00002866 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002867 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002868 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002869
2870 return false;
2871}
2872
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002873/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2874/// TheCall is an ARM/AArch64 special register string literal.
2875bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2876 int ArgNum, unsigned ExpectedFieldNum,
2877 bool AllowName) {
2878 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2879 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2880 BuiltinID == ARM::BI__builtin_arm_rsr ||
2881 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2882 BuiltinID == ARM::BI__builtin_arm_wsr ||
2883 BuiltinID == ARM::BI__builtin_arm_wsrp;
2884 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2885 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2886 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2887 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2888 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2889 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2890 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2891
2892 // We can't check the value of a dependent argument.
2893 Expr *Arg = TheCall->getArg(ArgNum);
2894 if (Arg->isTypeDependent() || Arg->isValueDependent())
2895 return false;
2896
2897 // Check if the argument is a string literal.
2898 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2899 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2900 << Arg->getSourceRange();
2901
2902 // Check the type of special register given.
2903 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2904 SmallVector<StringRef, 6> Fields;
2905 Reg.split(Fields, ":");
2906
2907 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2908 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2909 << Arg->getSourceRange();
2910
2911 // If the string is the name of a register then we cannot check that it is
2912 // valid here but if the string is of one the forms described in ACLE then we
2913 // can check that the supplied fields are integers and within the valid
2914 // ranges.
2915 if (Fields.size() > 1) {
2916 bool FiveFields = Fields.size() == 5;
2917
2918 bool ValidString = true;
2919 if (IsARMBuiltin) {
2920 ValidString &= Fields[0].startswith_lower("cp") ||
2921 Fields[0].startswith_lower("p");
2922 if (ValidString)
2923 Fields[0] =
2924 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2925
2926 ValidString &= Fields[2].startswith_lower("c");
2927 if (ValidString)
2928 Fields[2] = Fields[2].drop_front(1);
2929
2930 if (FiveFields) {
2931 ValidString &= Fields[3].startswith_lower("c");
2932 if (ValidString)
2933 Fields[3] = Fields[3].drop_front(1);
2934 }
2935 }
2936
2937 SmallVector<int, 5> Ranges;
2938 if (FiveFields)
2939 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2940 else
2941 Ranges.append({15, 7, 15});
2942
2943 for (unsigned i=0; i<Fields.size(); ++i) {
2944 int IntField;
2945 ValidString &= !Fields[i].getAsInteger(10, IntField);
2946 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2947 }
2948
2949 if (!ValidString)
2950 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2951 << Arg->getSourceRange();
2952
2953 } else if (IsAArch64Builtin && Fields.size() == 1) {
2954 // If the register name is one of those that appear in the condition below
2955 // and the special register builtin being used is one of the write builtins,
2956 // then we require that the argument provided for writing to the register
2957 // is an integer constant expression. This is because it will be lowered to
2958 // an MSR (immediate) instruction, so we need to know the immediate at
2959 // compile time.
2960 if (TheCall->getNumArgs() != 2)
2961 return false;
2962
2963 std::string RegLower = Reg.lower();
2964 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2965 RegLower != "pan" && RegLower != "uao")
2966 return false;
2967
2968 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2969 }
2970
2971 return false;
2972}
2973
Eli Friedmanc97d0142009-05-03 06:04:26 +00002974/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002975/// This checks that the target supports __builtin_longjmp and
2976/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002977bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002978 if (!Context.getTargetInfo().hasSjLjLowering())
2979 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2980 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2981
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002982 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002983 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002984
Eric Christopher8d0c6212010-04-17 02:26:23 +00002985 // TODO: This is less than ideal. Overload this to take a value.
2986 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2987 return true;
2988
2989 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002990 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2991 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2992
2993 return false;
2994}
2995
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002996
2997/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2998/// This checks that the target supports __builtin_setjmp.
2999bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3000 if (!Context.getTargetInfo().hasSjLjLowering())
3001 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3002 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3003 return false;
3004}
3005
Richard Smithd7293d72013-08-05 18:49:43 +00003006namespace {
3007enum StringLiteralCheckType {
3008 SLCT_NotALiteral,
3009 SLCT_UncheckedLiteral,
3010 SLCT_CheckedLiteral
3011};
3012}
3013
Richard Smith55ce3522012-06-25 20:30:08 +00003014// Determine if an expression is a string literal or constant string.
3015// If this function returns false on the arguments to a function expecting a
3016// format string, we will usually need to emit a warning.
3017// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003018static StringLiteralCheckType
3019checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3020 bool HasVAListArg, unsigned format_idx,
3021 unsigned firstDataArg, Sema::FormatStringType Type,
3022 Sema::VariadicCallType CallType, bool InFunctionCall,
3023 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003024 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003025 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003026 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003027
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003028 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003029
Richard Smithd7293d72013-08-05 18:49:43 +00003030 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003031 // Technically -Wformat-nonliteral does not warn about this case.
3032 // The behavior of printf and friends in this case is implementation
3033 // dependent. Ideally if the format string cannot be null then
3034 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003035 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003036
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003037 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003038 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003039 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003040 // The expression is a literal if both sub-expressions were, and it was
3041 // completely checked only if both sub-expressions were checked.
3042 const AbstractConditionalOperator *C =
3043 cast<AbstractConditionalOperator>(E);
3044 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003045 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003046 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003047 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003048 if (Left == SLCT_NotALiteral)
3049 return SLCT_NotALiteral;
3050 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003051 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003052 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003053 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003054 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003055 }
3056
3057 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003058 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3059 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003060 }
3061
John McCallc07a0c72011-02-17 10:25:35 +00003062 case Stmt::OpaqueValueExprClass:
3063 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3064 E = src;
3065 goto tryAgain;
3066 }
Richard Smith55ce3522012-06-25 20:30:08 +00003067 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003068
Ted Kremeneka8890832011-02-24 23:03:04 +00003069 case Stmt::PredefinedExprClass:
3070 // While __func__, etc., are technically not string literals, they
3071 // cannot contain format specifiers and thus are not a security
3072 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003073 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003074
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003075 case Stmt::DeclRefExprClass: {
3076 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003077
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003078 // As an exception, do not flag errors for variables binding to
3079 // const string literals.
3080 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3081 bool isConstant = false;
3082 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003083
Richard Smithd7293d72013-08-05 18:49:43 +00003084 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3085 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003086 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003087 isConstant = T.isConstant(S.Context) &&
3088 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003089 } else if (T->isObjCObjectPointerType()) {
3090 // In ObjC, there is usually no "const ObjectPointer" type,
3091 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003092 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003093 }
Mike Stump11289f42009-09-09 15:08:12 +00003094
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003095 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003096 if (const Expr *Init = VD->getAnyInitializer()) {
3097 // Look through initializers like const char c[] = { "foo" }
3098 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3099 if (InitList->isStringLiteralInit())
3100 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3101 }
Richard Smithd7293d72013-08-05 18:49:43 +00003102 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003103 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003104 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003105 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003106 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Anders Carlssonb012ca92009-06-28 19:55:58 +00003109 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3110 // special check to see if the format string is a function parameter
3111 // of the function calling the printf function. If the function
3112 // has an attribute indicating it is a printf-like function, then we
3113 // should suppress warnings concerning non-literals being used in a call
3114 // to a vprintf function. For example:
3115 //
3116 // void
3117 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3118 // va_list ap;
3119 // va_start(ap, fmt);
3120 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3121 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003122 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003123 if (HasVAListArg) {
3124 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3125 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3126 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003127 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003128 // adjust for implicit parameter
3129 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3130 if (MD->isInstance())
3131 ++PVIndex;
3132 // We also check if the formats are compatible.
3133 // We can't pass a 'scanf' string to a 'printf' function.
3134 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003135 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003136 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003137 }
3138 }
3139 }
3140 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003141 }
Mike Stump11289f42009-09-09 15:08:12 +00003142
Richard Smith55ce3522012-06-25 20:30:08 +00003143 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003144 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003145
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003146 case Stmt::CallExprClass:
3147 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003148 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003149 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3150 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3151 unsigned ArgIndex = FA->getFormatIdx();
3152 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3153 if (MD->isInstance())
3154 --ArgIndex;
3155 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003156
Richard Smithd7293d72013-08-05 18:49:43 +00003157 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003158 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003159 Type, CallType, InFunctionCall,
3160 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003161 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3162 unsigned BuiltinID = FD->getBuiltinID();
3163 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3164 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3165 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003166 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003167 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003168 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003169 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003170 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003171 }
3172 }
Mike Stump11289f42009-09-09 15:08:12 +00003173
Richard Smith55ce3522012-06-25 20:30:08 +00003174 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003175 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003176 case Stmt::ObjCStringLiteralClass:
3177 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003178 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003179
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003180 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003181 StrE = ObjCFExpr->getString();
3182 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003183 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003184
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003185 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003186 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3187 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003188 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003189 }
Mike Stump11289f42009-09-09 15:08:12 +00003190
Richard Smith55ce3522012-06-25 20:30:08 +00003191 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003192 }
Mike Stump11289f42009-09-09 15:08:12 +00003193
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003194 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003195 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003196 }
3197}
3198
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003199Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003200 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003201 .Case("scanf", FST_Scanf)
3202 .Cases("printf", "printf0", FST_Printf)
3203 .Cases("NSString", "CFString", FST_NSString)
3204 .Case("strftime", FST_Strftime)
3205 .Case("strfmon", FST_Strfmon)
3206 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003207 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003208 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003209 .Default(FST_Unknown);
3210}
3211
Jordan Rose3e0ec582012-07-19 18:10:23 +00003212/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003213/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003214/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003215bool Sema::CheckFormatArguments(const FormatAttr *Format,
3216 ArrayRef<const Expr *> Args,
3217 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003218 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003219 SourceLocation Loc, SourceRange Range,
3220 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003221 FormatStringInfo FSI;
3222 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003223 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003224 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003225 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003226 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003227}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003228
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003229bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003230 bool HasVAListArg, unsigned format_idx,
3231 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003232 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003233 SourceLocation Loc, SourceRange Range,
3234 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003235 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003236 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003237 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003238 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003239 }
Mike Stump11289f42009-09-09 15:08:12 +00003240
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003241 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003242
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003243 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003244 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003245 // Dynamically generated format strings are difficult to
3246 // automatically vet at compile time. Requiring that format strings
3247 // are string literals: (1) permits the checking of format strings by
3248 // the compiler and thereby (2) can practically remove the source of
3249 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003250
Mike Stump11289f42009-09-09 15:08:12 +00003251 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003252 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003253 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003254 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003255 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003256 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3257 format_idx, firstDataArg, Type, CallType,
3258 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003259 if (CT != SLCT_NotALiteral)
3260 // Literal format string found, check done!
3261 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003262
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003263 // Strftime is particular as it always uses a single 'time' argument,
3264 // so it is safe to pass a non-literal string.
3265 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003266 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003267
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003268 // Do not emit diag when the string param is a macro expansion and the
3269 // format is either NSString or CFString. This is a hack to prevent
3270 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3271 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003272 if (Type == FST_NSString &&
3273 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003274 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003275
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003276 // If there are no arguments specified, warn with -Wformat-security, otherwise
3277 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003278 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003279 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003280 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003281 << OrigFormatExpr->getSourceRange();
3282 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003283 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003284 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003285 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003286 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003287}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003288
Ted Kremenekab278de2010-01-28 23:39:18 +00003289namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003290class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3291protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003292 Sema &S;
3293 const StringLiteral *FExpr;
3294 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003295 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003296 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003297 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003298 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003299 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003300 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003301 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003302 bool usesPositionalArgs;
3303 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003304 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003305 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003306 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003307public:
Ted Kremenek02087932010-07-16 02:11:22 +00003308 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003309 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003310 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003311 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003312 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003313 Sema::VariadicCallType callType,
3314 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003315 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003316 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3317 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003318 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003319 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003320 inFunctionCall(inFunctionCall), CallType(callType),
3321 CheckedVarArgs(CheckedVarArgs) {
3322 CoveredArgs.resize(numDataArgs);
3323 CoveredArgs.reset();
3324 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003325
Ted Kremenek019d2242010-01-29 01:50:07 +00003326 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003327
Ted Kremenek02087932010-07-16 02:11:22 +00003328 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003329 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003330
Jordan Rose92303592012-09-08 04:00:03 +00003331 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003332 const analyze_format_string::FormatSpecifier &FS,
3333 const analyze_format_string::ConversionSpecifier &CS,
3334 const char *startSpecifier, unsigned specifierLen,
3335 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003336
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003337 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003338 const analyze_format_string::FormatSpecifier &FS,
3339 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003340
3341 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003342 const analyze_format_string::ConversionSpecifier &CS,
3343 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003344
Craig Toppere14c0f82014-03-12 04:55:44 +00003345 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003346
Craig Toppere14c0f82014-03-12 04:55:44 +00003347 void HandleInvalidPosition(const char *startSpecifier,
3348 unsigned specifierLen,
3349 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003350
Craig Toppere14c0f82014-03-12 04:55:44 +00003351 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003352
Craig Toppere14c0f82014-03-12 04:55:44 +00003353 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003354
Richard Trieu03cf7b72011-10-28 00:41:25 +00003355 template <typename Range>
3356 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3357 const Expr *ArgumentExpr,
3358 PartialDiagnostic PDiag,
3359 SourceLocation StringLoc,
3360 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003361 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003362
Ted Kremenek02087932010-07-16 02:11:22 +00003363protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003364 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3365 const char *startSpec,
3366 unsigned specifierLen,
3367 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003368
3369 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3370 const char *startSpec,
3371 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003372
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003373 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003374 CharSourceRange getSpecifierRange(const char *startSpecifier,
3375 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003376 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003377
Ted Kremenek5739de72010-01-29 01:06:55 +00003378 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003379
3380 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3381 const analyze_format_string::ConversionSpecifier &CS,
3382 const char *startSpecifier, unsigned specifierLen,
3383 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003384
3385 template <typename Range>
3386 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3387 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003388 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003389};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003390}
Ted Kremenekab278de2010-01-28 23:39:18 +00003391
Ted Kremenek02087932010-07-16 02:11:22 +00003392SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003393 return OrigFormatExpr->getSourceRange();
3394}
3395
Ted Kremenek02087932010-07-16 02:11:22 +00003396CharSourceRange CheckFormatHandler::
3397getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003398 SourceLocation Start = getLocationOfByte(startSpecifier);
3399 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3400
3401 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003402 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003403
3404 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003405}
3406
Ted Kremenek02087932010-07-16 02:11:22 +00003407SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003408 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003409}
3410
Ted Kremenek02087932010-07-16 02:11:22 +00003411void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3412 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003413 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3414 getLocationOfByte(startSpecifier),
3415 /*IsStringLocation*/true,
3416 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003417}
3418
Jordan Rose92303592012-09-08 04:00:03 +00003419void CheckFormatHandler::HandleInvalidLengthModifier(
3420 const analyze_format_string::FormatSpecifier &FS,
3421 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003422 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003423 using namespace analyze_format_string;
3424
3425 const LengthModifier &LM = FS.getLengthModifier();
3426 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3427
3428 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003429 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003430 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003431 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003432 getLocationOfByte(LM.getStart()),
3433 /*IsStringLocation*/true,
3434 getSpecifierRange(startSpecifier, specifierLen));
3435
3436 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3437 << FixedLM->toString()
3438 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3439
3440 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003441 FixItHint Hint;
3442 if (DiagID == diag::warn_format_nonsensical_length)
3443 Hint = FixItHint::CreateRemoval(LMRange);
3444
3445 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003446 getLocationOfByte(LM.getStart()),
3447 /*IsStringLocation*/true,
3448 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003449 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003450 }
3451}
3452
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003453void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003454 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003455 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003456 using namespace analyze_format_string;
3457
3458 const LengthModifier &LM = FS.getLengthModifier();
3459 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3460
3461 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003462 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003463 if (FixedLM) {
3464 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3465 << LM.toString() << 0,
3466 getLocationOfByte(LM.getStart()),
3467 /*IsStringLocation*/true,
3468 getSpecifierRange(startSpecifier, specifierLen));
3469
3470 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3471 << FixedLM->toString()
3472 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3473
3474 } else {
3475 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3476 << LM.toString() << 0,
3477 getLocationOfByte(LM.getStart()),
3478 /*IsStringLocation*/true,
3479 getSpecifierRange(startSpecifier, specifierLen));
3480 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003481}
3482
3483void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3484 const analyze_format_string::ConversionSpecifier &CS,
3485 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003486 using namespace analyze_format_string;
3487
3488 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003489 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003490 if (FixedCS) {
3491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3492 << CS.toString() << /*conversion specifier*/1,
3493 getLocationOfByte(CS.getStart()),
3494 /*IsStringLocation*/true,
3495 getSpecifierRange(startSpecifier, specifierLen));
3496
3497 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3498 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3499 << FixedCS->toString()
3500 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3501 } else {
3502 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3503 << CS.toString() << /*conversion specifier*/1,
3504 getLocationOfByte(CS.getStart()),
3505 /*IsStringLocation*/true,
3506 getSpecifierRange(startSpecifier, specifierLen));
3507 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003508}
3509
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003510void CheckFormatHandler::HandlePosition(const char *startPos,
3511 unsigned posLen) {
3512 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3513 getLocationOfByte(startPos),
3514 /*IsStringLocation*/true,
3515 getSpecifierRange(startPos, posLen));
3516}
3517
Ted Kremenekd1668192010-02-27 01:41:03 +00003518void
Ted Kremenek02087932010-07-16 02:11:22 +00003519CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3520 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003521 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3522 << (unsigned) p,
3523 getLocationOfByte(startPos), /*IsStringLocation*/true,
3524 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003525}
3526
Ted Kremenek02087932010-07-16 02:11:22 +00003527void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003528 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003529 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3530 getLocationOfByte(startPos),
3531 /*IsStringLocation*/true,
3532 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003533}
3534
Ted Kremenek02087932010-07-16 02:11:22 +00003535void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003536 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003537 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003538 EmitFormatDiagnostic(
3539 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3540 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3541 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003542 }
Ted Kremenek02087932010-07-16 02:11:22 +00003543}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003544
Jordan Rose58bbe422012-07-19 18:10:08 +00003545// Note that this may return NULL if there was an error parsing or building
3546// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003547const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003548 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003549}
3550
3551void CheckFormatHandler::DoneProcessing() {
3552 // Does the number of data arguments exceed the number of
3553 // format conversions in the format string?
3554 if (!HasVAListArg) {
3555 // Find any arguments that weren't covered.
3556 CoveredArgs.flip();
3557 signed notCoveredArg = CoveredArgs.find_first();
3558 if (notCoveredArg >= 0) {
3559 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003560 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3561 SourceLocation Loc = E->getLocStart();
3562 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3563 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3564 Loc, /*IsStringLocation*/false,
3565 getFormatStringRange());
3566 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003567 }
Ted Kremenek02087932010-07-16 02:11:22 +00003568 }
3569 }
3570}
3571
Ted Kremenekce815422010-07-19 21:25:57 +00003572bool
3573CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3574 SourceLocation Loc,
3575 const char *startSpec,
3576 unsigned specifierLen,
3577 const char *csStart,
3578 unsigned csLen) {
3579
3580 bool keepGoing = true;
3581 if (argIndex < NumDataArgs) {
3582 // Consider the argument coverered, even though the specifier doesn't
3583 // make sense.
3584 CoveredArgs.set(argIndex);
3585 }
3586 else {
3587 // If argIndex exceeds the number of data arguments we
3588 // don't issue a warning because that is just a cascade of warnings (and
3589 // they may have intended '%%' anyway). We don't want to continue processing
3590 // the format string after this point, however, as we will like just get
3591 // gibberish when trying to match arguments.
3592 keepGoing = false;
3593 }
3594
Richard Trieu03cf7b72011-10-28 00:41:25 +00003595 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3596 << StringRef(csStart, csLen),
3597 Loc, /*IsStringLocation*/true,
3598 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003599
3600 return keepGoing;
3601}
3602
Richard Trieu03cf7b72011-10-28 00:41:25 +00003603void
3604CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3605 const char *startSpec,
3606 unsigned specifierLen) {
3607 EmitFormatDiagnostic(
3608 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3609 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3610}
3611
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003612bool
3613CheckFormatHandler::CheckNumArgs(
3614 const analyze_format_string::FormatSpecifier &FS,
3615 const analyze_format_string::ConversionSpecifier &CS,
3616 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3617
3618 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003619 PartialDiagnostic PDiag = FS.usesPositionalArg()
3620 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3621 << (argIndex+1) << NumDataArgs)
3622 : S.PDiag(diag::warn_printf_insufficient_data_args);
3623 EmitFormatDiagnostic(
3624 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3625 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003626 return false;
3627 }
3628 return true;
3629}
3630
Richard Trieu03cf7b72011-10-28 00:41:25 +00003631template<typename Range>
3632void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3633 SourceLocation Loc,
3634 bool IsStringLocation,
3635 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003636 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003637 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003638 Loc, IsStringLocation, StringRange, FixIt);
3639}
3640
3641/// \brief If the format string is not within the funcion call, emit a note
3642/// so that the function call and string are in diagnostic messages.
3643///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003644/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003645/// call and only one diagnostic message will be produced. Otherwise, an
3646/// extra note will be emitted pointing to location of the format string.
3647///
3648/// \param ArgumentExpr the expression that is passed as the format string
3649/// argument in the function call. Used for getting locations when two
3650/// diagnostics are emitted.
3651///
3652/// \param PDiag the callee should already have provided any strings for the
3653/// diagnostic message. This function only adds locations and fixits
3654/// to diagnostics.
3655///
3656/// \param Loc primary location for diagnostic. If two diagnostics are
3657/// required, one will be at Loc and a new SourceLocation will be created for
3658/// the other one.
3659///
3660/// \param IsStringLocation if true, Loc points to the format string should be
3661/// used for the note. Otherwise, Loc points to the argument list and will
3662/// be used with PDiag.
3663///
3664/// \param StringRange some or all of the string to highlight. This is
3665/// templated so it can accept either a CharSourceRange or a SourceRange.
3666///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003667/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003668template<typename Range>
3669void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3670 const Expr *ArgumentExpr,
3671 PartialDiagnostic PDiag,
3672 SourceLocation Loc,
3673 bool IsStringLocation,
3674 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003675 ArrayRef<FixItHint> FixIt) {
3676 if (InFunctionCall) {
3677 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3678 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003679 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003680 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003681 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3682 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003683
3684 const Sema::SemaDiagnosticBuilder &Note =
3685 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3686 diag::note_format_string_defined);
3687
3688 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003689 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003690 }
3691}
3692
Ted Kremenek02087932010-07-16 02:11:22 +00003693//===--- CHECK: Printf format string checking ------------------------------===//
3694
3695namespace {
3696class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003697 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003698public:
3699 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3700 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003701 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003702 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003703 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003704 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003705 Sema::VariadicCallType CallType,
3706 llvm::SmallBitVector &CheckedVarArgs)
3707 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3708 numDataArgs, beg, hasVAListArg, Args,
3709 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3710 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003711 {}
3712
Craig Toppere14c0f82014-03-12 04:55:44 +00003713
Ted Kremenek02087932010-07-16 02:11:22 +00003714 bool HandleInvalidPrintfConversionSpecifier(
3715 const analyze_printf::PrintfSpecifier &FS,
3716 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003717 unsigned specifierLen) override;
3718
Ted Kremenek02087932010-07-16 02:11:22 +00003719 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3720 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003721 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003722 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3723 const char *StartSpecifier,
3724 unsigned SpecifierLen,
3725 const Expr *E);
3726
Ted Kremenek02087932010-07-16 02:11:22 +00003727 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3728 const char *startSpecifier, unsigned specifierLen);
3729 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3730 const analyze_printf::OptionalAmount &Amt,
3731 unsigned type,
3732 const char *startSpecifier, unsigned specifierLen);
3733 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3734 const analyze_printf::OptionalFlag &flag,
3735 const char *startSpecifier, unsigned specifierLen);
3736 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3737 const analyze_printf::OptionalFlag &ignoredFlag,
3738 const analyze_printf::OptionalFlag &flag,
3739 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003740 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003741 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003742
3743 void HandleEmptyObjCModifierFlag(const char *startFlag,
3744 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003745
Ted Kremenek2b417712015-07-02 05:39:16 +00003746 void HandleInvalidObjCModifierFlag(const char *startFlag,
3747 unsigned flagLen) override;
3748
3749 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3750 const char *flagsEnd,
3751 const char *conversionPosition)
3752 override;
3753};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003754}
Ted Kremenek02087932010-07-16 02:11:22 +00003755
3756bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3757 const analyze_printf::PrintfSpecifier &FS,
3758 const char *startSpecifier,
3759 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003760 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003761 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003762
Ted Kremenekce815422010-07-19 21:25:57 +00003763 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3764 getLocationOfByte(CS.getStart()),
3765 startSpecifier, specifierLen,
3766 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003767}
3768
Ted Kremenek02087932010-07-16 02:11:22 +00003769bool CheckPrintfHandler::HandleAmount(
3770 const analyze_format_string::OptionalAmount &Amt,
3771 unsigned k, const char *startSpecifier,
3772 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003773
3774 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003775 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003776 unsigned argIndex = Amt.getArgIndex();
3777 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003778 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3779 << k,
3780 getLocationOfByte(Amt.getStart()),
3781 /*IsStringLocation*/true,
3782 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003783 // Don't do any more checking. We will just emit
3784 // spurious errors.
3785 return false;
3786 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003787
Ted Kremenek5739de72010-01-29 01:06:55 +00003788 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003789 // Although not in conformance with C99, we also allow the argument to be
3790 // an 'unsigned int' as that is a reasonably safe case. GCC also
3791 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003792 CoveredArgs.set(argIndex);
3793 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003794 if (!Arg)
3795 return false;
3796
Ted Kremenek5739de72010-01-29 01:06:55 +00003797 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003798
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003799 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3800 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003801
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003802 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003803 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003804 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003805 << T << Arg->getSourceRange(),
3806 getLocationOfByte(Amt.getStart()),
3807 /*IsStringLocation*/true,
3808 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003809 // Don't do any more checking. We will just emit
3810 // spurious errors.
3811 return false;
3812 }
3813 }
3814 }
3815 return true;
3816}
Ted Kremenek5739de72010-01-29 01:06:55 +00003817
Tom Careb49ec692010-06-17 19:00:27 +00003818void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003819 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003820 const analyze_printf::OptionalAmount &Amt,
3821 unsigned type,
3822 const char *startSpecifier,
3823 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003824 const analyze_printf::PrintfConversionSpecifier &CS =
3825 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003826
Richard Trieu03cf7b72011-10-28 00:41:25 +00003827 FixItHint fixit =
3828 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3829 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3830 Amt.getConstantLength()))
3831 : FixItHint();
3832
3833 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3834 << type << CS.toString(),
3835 getLocationOfByte(Amt.getStart()),
3836 /*IsStringLocation*/true,
3837 getSpecifierRange(startSpecifier, specifierLen),
3838 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003839}
3840
Ted Kremenek02087932010-07-16 02:11:22 +00003841void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003842 const analyze_printf::OptionalFlag &flag,
3843 const char *startSpecifier,
3844 unsigned specifierLen) {
3845 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003846 const analyze_printf::PrintfConversionSpecifier &CS =
3847 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003848 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3849 << flag.toString() << CS.toString(),
3850 getLocationOfByte(flag.getPosition()),
3851 /*IsStringLocation*/true,
3852 getSpecifierRange(startSpecifier, specifierLen),
3853 FixItHint::CreateRemoval(
3854 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003855}
3856
3857void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003858 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003859 const analyze_printf::OptionalFlag &ignoredFlag,
3860 const analyze_printf::OptionalFlag &flag,
3861 const char *startSpecifier,
3862 unsigned specifierLen) {
3863 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003864 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3865 << ignoredFlag.toString() << flag.toString(),
3866 getLocationOfByte(ignoredFlag.getPosition()),
3867 /*IsStringLocation*/true,
3868 getSpecifierRange(startSpecifier, specifierLen),
3869 FixItHint::CreateRemoval(
3870 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003871}
3872
Ted Kremenek2b417712015-07-02 05:39:16 +00003873// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3874// bool IsStringLocation, Range StringRange,
3875// ArrayRef<FixItHint> Fixit = None);
3876
3877void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3878 unsigned flagLen) {
3879 // Warn about an empty flag.
3880 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3881 getLocationOfByte(startFlag),
3882 /*IsStringLocation*/true,
3883 getSpecifierRange(startFlag, flagLen));
3884}
3885
3886void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3887 unsigned flagLen) {
3888 // Warn about an invalid flag.
3889 auto Range = getSpecifierRange(startFlag, flagLen);
3890 StringRef flag(startFlag, flagLen);
3891 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3892 getLocationOfByte(startFlag),
3893 /*IsStringLocation*/true,
3894 Range, FixItHint::CreateRemoval(Range));
3895}
3896
3897void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3898 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3899 // Warn about using '[...]' without a '@' conversion.
3900 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3901 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3902 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3903 getLocationOfByte(conversionPosition),
3904 /*IsStringLocation*/true,
3905 Range, FixItHint::CreateRemoval(Range));
3906}
3907
Richard Smith55ce3522012-06-25 20:30:08 +00003908// Determines if the specified is a C++ class or struct containing
3909// a member with the specified name and kind (e.g. a CXXMethodDecl named
3910// "c_str()").
3911template<typename MemberKind>
3912static llvm::SmallPtrSet<MemberKind*, 1>
3913CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3914 const RecordType *RT = Ty->getAs<RecordType>();
3915 llvm::SmallPtrSet<MemberKind*, 1> Results;
3916
3917 if (!RT)
3918 return Results;
3919 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003920 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003921 return Results;
3922
Alp Tokerb6cc5922014-05-03 03:45:55 +00003923 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003924 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003925 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003926
3927 // We just need to include all members of the right kind turned up by the
3928 // filter, at this point.
3929 if (S.LookupQualifiedName(R, RT->getDecl()))
3930 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3931 NamedDecl *decl = (*I)->getUnderlyingDecl();
3932 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3933 Results.insert(FK);
3934 }
3935 return Results;
3936}
3937
Richard Smith2868a732014-02-28 01:36:39 +00003938/// Check if we could call '.c_str()' on an object.
3939///
3940/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3941/// allow the call, or if it would be ambiguous).
3942bool Sema::hasCStrMethod(const Expr *E) {
3943 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3944 MethodSet Results =
3945 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3946 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3947 MI != ME; ++MI)
3948 if ((*MI)->getMinRequiredArguments() == 0)
3949 return true;
3950 return false;
3951}
3952
Richard Smith55ce3522012-06-25 20:30:08 +00003953// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003954// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003955// Returns true when a c_str() conversion method is found.
3956bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003957 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003958 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3959
3960 MethodSet Results =
3961 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3962
3963 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3964 MI != ME; ++MI) {
3965 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003966 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003967 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003968 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003969 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003970 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3971 << "c_str()"
3972 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3973 return true;
3974 }
3975 }
3976
3977 return false;
3978}
3979
Ted Kremenekab278de2010-01-28 23:39:18 +00003980bool
Ted Kremenek02087932010-07-16 02:11:22 +00003981CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003982 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003983 const char *startSpecifier,
3984 unsigned specifierLen) {
3985
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003986 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003987 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003988 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003989
Ted Kremenek6cd69422010-07-19 22:01:06 +00003990 if (FS.consumesDataArgument()) {
3991 if (atFirstArg) {
3992 atFirstArg = false;
3993 usesPositionalArgs = FS.usesPositionalArg();
3994 }
3995 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003996 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3997 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003998 return false;
3999 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004000 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004001
Ted Kremenekd1668192010-02-27 01:41:03 +00004002 // First check if the field width, precision, and conversion specifier
4003 // have matching data arguments.
4004 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4005 startSpecifier, specifierLen)) {
4006 return false;
4007 }
4008
4009 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4010 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004011 return false;
4012 }
4013
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004014 if (!CS.consumesDataArgument()) {
4015 // FIXME: Technically specifying a precision or field width here
4016 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004017 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004018 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004019
Ted Kremenek4a49d982010-02-26 19:18:41 +00004020 // Consume the argument.
4021 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004022 if (argIndex < NumDataArgs) {
4023 // The check to see if the argIndex is valid will come later.
4024 // We set the bit here because we may exit early from this
4025 // function if we encounter some other error.
4026 CoveredArgs.set(argIndex);
4027 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004028
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004029 // FreeBSD kernel extensions.
4030 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4031 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4032 // We need at least two arguments.
4033 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4034 return false;
4035
4036 // Claim the second argument.
4037 CoveredArgs.set(argIndex + 1);
4038
4039 // Type check the first argument (int for %b, pointer for %D)
4040 const Expr *Ex = getDataArg(argIndex);
4041 const analyze_printf::ArgType &AT =
4042 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4043 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4044 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4045 EmitFormatDiagnostic(
4046 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4047 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4048 << false << Ex->getSourceRange(),
4049 Ex->getLocStart(), /*IsStringLocation*/false,
4050 getSpecifierRange(startSpecifier, specifierLen));
4051
4052 // Type check the second argument (char * for both %b and %D)
4053 Ex = getDataArg(argIndex + 1);
4054 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4055 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4056 EmitFormatDiagnostic(
4057 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4058 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4059 << false << Ex->getSourceRange(),
4060 Ex->getLocStart(), /*IsStringLocation*/false,
4061 getSpecifierRange(startSpecifier, specifierLen));
4062
4063 return true;
4064 }
4065
Ted Kremenek4a49d982010-02-26 19:18:41 +00004066 // Check for using an Objective-C specific conversion specifier
4067 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004068 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004069 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4070 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004071 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004072
Tom Careb49ec692010-06-17 19:00:27 +00004073 // Check for invalid use of field width
4074 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004075 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004076 startSpecifier, specifierLen);
4077 }
4078
4079 // Check for invalid use of precision
4080 if (!FS.hasValidPrecision()) {
4081 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4082 startSpecifier, specifierLen);
4083 }
4084
4085 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004086 if (!FS.hasValidThousandsGroupingPrefix())
4087 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004088 if (!FS.hasValidLeadingZeros())
4089 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4090 if (!FS.hasValidPlusPrefix())
4091 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004092 if (!FS.hasValidSpacePrefix())
4093 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004094 if (!FS.hasValidAlternativeForm())
4095 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4096 if (!FS.hasValidLeftJustified())
4097 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4098
4099 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004100 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4101 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4102 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004103 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4104 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4105 startSpecifier, specifierLen);
4106
4107 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004108 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004109 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4110 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004111 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004112 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004113 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004114 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4115 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004116
Jordan Rose92303592012-09-08 04:00:03 +00004117 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4118 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4119
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004120 // The remaining checks depend on the data arguments.
4121 if (HasVAListArg)
4122 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004123
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004124 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004125 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004126
Jordan Rose58bbe422012-07-19 18:10:08 +00004127 const Expr *Arg = getDataArg(argIndex);
4128 if (!Arg)
4129 return true;
4130
4131 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004132}
4133
Jordan Roseaee34382012-09-05 22:56:26 +00004134static bool requiresParensToAddCast(const Expr *E) {
4135 // FIXME: We should have a general way to reason about operator
4136 // precedence and whether parens are actually needed here.
4137 // Take care of a few common cases where they aren't.
4138 const Expr *Inside = E->IgnoreImpCasts();
4139 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4140 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4141
4142 switch (Inside->getStmtClass()) {
4143 case Stmt::ArraySubscriptExprClass:
4144 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004145 case Stmt::CharacterLiteralClass:
4146 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004147 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004148 case Stmt::FloatingLiteralClass:
4149 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004150 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004151 case Stmt::ObjCArrayLiteralClass:
4152 case Stmt::ObjCBoolLiteralExprClass:
4153 case Stmt::ObjCBoxedExprClass:
4154 case Stmt::ObjCDictionaryLiteralClass:
4155 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004156 case Stmt::ObjCIvarRefExprClass:
4157 case Stmt::ObjCMessageExprClass:
4158 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004159 case Stmt::ObjCStringLiteralClass:
4160 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004161 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004162 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004163 case Stmt::UnaryOperatorClass:
4164 return false;
4165 default:
4166 return true;
4167 }
4168}
4169
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004170static std::pair<QualType, StringRef>
4171shouldNotPrintDirectly(const ASTContext &Context,
4172 QualType IntendedTy,
4173 const Expr *E) {
4174 // Use a 'while' to peel off layers of typedefs.
4175 QualType TyTy = IntendedTy;
4176 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4177 StringRef Name = UserTy->getDecl()->getName();
4178 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4179 .Case("NSInteger", Context.LongTy)
4180 .Case("NSUInteger", Context.UnsignedLongTy)
4181 .Case("SInt32", Context.IntTy)
4182 .Case("UInt32", Context.UnsignedIntTy)
4183 .Default(QualType());
4184
4185 if (!CastTy.isNull())
4186 return std::make_pair(CastTy, Name);
4187
4188 TyTy = UserTy->desugar();
4189 }
4190
4191 // Strip parens if necessary.
4192 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4193 return shouldNotPrintDirectly(Context,
4194 PE->getSubExpr()->getType(),
4195 PE->getSubExpr());
4196
4197 // If this is a conditional expression, then its result type is constructed
4198 // via usual arithmetic conversions and thus there might be no necessary
4199 // typedef sugar there. Recurse to operands to check for NSInteger &
4200 // Co. usage condition.
4201 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4202 QualType TrueTy, FalseTy;
4203 StringRef TrueName, FalseName;
4204
4205 std::tie(TrueTy, TrueName) =
4206 shouldNotPrintDirectly(Context,
4207 CO->getTrueExpr()->getType(),
4208 CO->getTrueExpr());
4209 std::tie(FalseTy, FalseName) =
4210 shouldNotPrintDirectly(Context,
4211 CO->getFalseExpr()->getType(),
4212 CO->getFalseExpr());
4213
4214 if (TrueTy == FalseTy)
4215 return std::make_pair(TrueTy, TrueName);
4216 else if (TrueTy.isNull())
4217 return std::make_pair(FalseTy, FalseName);
4218 else if (FalseTy.isNull())
4219 return std::make_pair(TrueTy, TrueName);
4220 }
4221
4222 return std::make_pair(QualType(), StringRef());
4223}
4224
Richard Smith55ce3522012-06-25 20:30:08 +00004225bool
4226CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4227 const char *StartSpecifier,
4228 unsigned SpecifierLen,
4229 const Expr *E) {
4230 using namespace analyze_format_string;
4231 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004232 // Now type check the data expression that matches the
4233 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004234 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4235 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004236 if (!AT.isValid())
4237 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004238
Jordan Rose598ec092012-12-05 18:44:40 +00004239 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004240 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4241 ExprTy = TET->getUnderlyingExpr()->getType();
4242 }
4243
Seth Cantrellb4802962015-03-04 03:12:10 +00004244 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4245
4246 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004247 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004248 }
Jordan Rose98709982012-06-04 22:48:57 +00004249
Jordan Rose22b74712012-09-05 22:56:19 +00004250 // Look through argument promotions for our error message's reported type.
4251 // This includes the integral and floating promotions, but excludes array
4252 // and function pointer decay; seeing that an argument intended to be a
4253 // string has type 'char [6]' is probably more confusing than 'char *'.
4254 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4255 if (ICE->getCastKind() == CK_IntegralCast ||
4256 ICE->getCastKind() == CK_FloatingCast) {
4257 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004258 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004259
4260 // Check if we didn't match because of an implicit cast from a 'char'
4261 // or 'short' to an 'int'. This is done because printf is a varargs
4262 // function.
4263 if (ICE->getType() == S.Context.IntTy ||
4264 ICE->getType() == S.Context.UnsignedIntTy) {
4265 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004266 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004267 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004268 }
Jordan Rose98709982012-06-04 22:48:57 +00004269 }
Jordan Rose598ec092012-12-05 18:44:40 +00004270 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4271 // Special case for 'a', which has type 'int' in C.
4272 // Note, however, that we do /not/ want to treat multibyte constants like
4273 // 'MooV' as characters! This form is deprecated but still exists.
4274 if (ExprTy == S.Context.IntTy)
4275 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4276 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004277 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004278
Jordan Rosebc53ed12014-05-31 04:12:14 +00004279 // Look through enums to their underlying type.
4280 bool IsEnum = false;
4281 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4282 ExprTy = EnumTy->getDecl()->getIntegerType();
4283 IsEnum = true;
4284 }
4285
Jordan Rose0e5badd2012-12-05 18:44:49 +00004286 // %C in an Objective-C context prints a unichar, not a wchar_t.
4287 // If the argument is an integer of some kind, believe the %C and suggest
4288 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004289 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004290 if (ObjCContext &&
4291 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4292 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4293 !ExprTy->isCharType()) {
4294 // 'unichar' is defined as a typedef of unsigned short, but we should
4295 // prefer using the typedef if it is visible.
4296 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004297
4298 // While we are here, check if the value is an IntegerLiteral that happens
4299 // to be within the valid range.
4300 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4301 const llvm::APInt &V = IL->getValue();
4302 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4303 return true;
4304 }
4305
Jordan Rose0e5badd2012-12-05 18:44:49 +00004306 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4307 Sema::LookupOrdinaryName);
4308 if (S.LookupName(Result, S.getCurScope())) {
4309 NamedDecl *ND = Result.getFoundDecl();
4310 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4311 if (TD->getUnderlyingType() == IntendedTy)
4312 IntendedTy = S.Context.getTypedefType(TD);
4313 }
4314 }
4315 }
4316
4317 // Special-case some of Darwin's platform-independence types by suggesting
4318 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004319 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004320 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004321 QualType CastTy;
4322 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4323 if (!CastTy.isNull()) {
4324 IntendedTy = CastTy;
4325 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004326 }
4327 }
4328
Jordan Rose22b74712012-09-05 22:56:19 +00004329 // We may be able to offer a FixItHint if it is a supported type.
4330 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004331 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004332 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004333
Jordan Rose22b74712012-09-05 22:56:19 +00004334 if (success) {
4335 // Get the fix string from the fixed format specifier
4336 SmallString<16> buf;
4337 llvm::raw_svector_ostream os(buf);
4338 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004339
Jordan Roseaee34382012-09-05 22:56:26 +00004340 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4341
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004342 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004343 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4344 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4345 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4346 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004347 // In this case, the specifier is wrong and should be changed to match
4348 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004349 EmitFormatDiagnostic(S.PDiag(diag)
4350 << AT.getRepresentativeTypeName(S.Context)
4351 << IntendedTy << IsEnum << E->getSourceRange(),
4352 E->getLocStart(),
4353 /*IsStringLocation*/ false, SpecRange,
4354 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004355
4356 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004357 // The canonical type for formatting this value is different from the
4358 // actual type of the expression. (This occurs, for example, with Darwin's
4359 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4360 // should be printed as 'long' for 64-bit compatibility.)
4361 // Rather than emitting a normal format/argument mismatch, we want to
4362 // add a cast to the recommended type (and correct the format string
4363 // if necessary).
4364 SmallString<16> CastBuf;
4365 llvm::raw_svector_ostream CastFix(CastBuf);
4366 CastFix << "(";
4367 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4368 CastFix << ")";
4369
4370 SmallVector<FixItHint,4> Hints;
4371 if (!AT.matchesType(S.Context, IntendedTy))
4372 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4373
4374 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4375 // If there's already a cast present, just replace it.
4376 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4377 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4378
4379 } else if (!requiresParensToAddCast(E)) {
4380 // If the expression has high enough precedence,
4381 // just write the C-style cast.
4382 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4383 CastFix.str()));
4384 } else {
4385 // Otherwise, add parens around the expression as well as the cast.
4386 CastFix << "(";
4387 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4388 CastFix.str()));
4389
Alp Tokerb6cc5922014-05-03 03:45:55 +00004390 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004391 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4392 }
4393
Jordan Rose0e5badd2012-12-05 18:44:49 +00004394 if (ShouldNotPrintDirectly) {
4395 // The expression has a type that should not be printed directly.
4396 // We extract the name from the typedef because we don't want to show
4397 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004398 StringRef Name;
4399 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4400 Name = TypedefTy->getDecl()->getName();
4401 else
4402 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004403 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004404 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004405 << E->getSourceRange(),
4406 E->getLocStart(), /*IsStringLocation=*/false,
4407 SpecRange, Hints);
4408 } else {
4409 // In this case, the expression could be printed using a different
4410 // specifier, but we've decided that the specifier is probably correct
4411 // and we should cast instead. Just use the normal warning message.
4412 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004413 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4414 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004415 << E->getSourceRange(),
4416 E->getLocStart(), /*IsStringLocation*/false,
4417 SpecRange, Hints);
4418 }
Jordan Roseaee34382012-09-05 22:56:26 +00004419 }
Jordan Rose22b74712012-09-05 22:56:19 +00004420 } else {
4421 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4422 SpecifierLen);
4423 // Since the warning for passing non-POD types to variadic functions
4424 // was deferred until now, we emit a warning for non-POD
4425 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004426 switch (S.isValidVarArgType(ExprTy)) {
4427 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004428 case Sema::VAK_ValidInCXX11: {
4429 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4430 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4431 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4432 }
Richard Smithd7293d72013-08-05 18:49:43 +00004433
Seth Cantrellb4802962015-03-04 03:12:10 +00004434 EmitFormatDiagnostic(
4435 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4436 << IsEnum << CSR << E->getSourceRange(),
4437 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4438 break;
4439 }
Richard Smithd7293d72013-08-05 18:49:43 +00004440 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004441 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004442 EmitFormatDiagnostic(
4443 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004444 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004445 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004446 << CallType
4447 << AT.getRepresentativeTypeName(S.Context)
4448 << CSR
4449 << E->getSourceRange(),
4450 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004451 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004452 break;
4453
4454 case Sema::VAK_Invalid:
4455 if (ExprTy->isObjCObjectType())
4456 EmitFormatDiagnostic(
4457 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4458 << S.getLangOpts().CPlusPlus11
4459 << ExprTy
4460 << CallType
4461 << AT.getRepresentativeTypeName(S.Context)
4462 << CSR
4463 << E->getSourceRange(),
4464 E->getLocStart(), /*IsStringLocation*/false, CSR);
4465 else
4466 // FIXME: If this is an initializer list, suggest removing the braces
4467 // or inserting a cast to the target type.
4468 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4469 << isa<InitListExpr>(E) << ExprTy << CallType
4470 << AT.getRepresentativeTypeName(S.Context)
4471 << E->getSourceRange();
4472 break;
4473 }
4474
4475 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4476 "format string specifier index out of range");
4477 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004478 }
4479
Ted Kremenekab278de2010-01-28 23:39:18 +00004480 return true;
4481}
4482
Ted Kremenek02087932010-07-16 02:11:22 +00004483//===--- CHECK: Scanf format string checking ------------------------------===//
4484
4485namespace {
4486class CheckScanfHandler : public CheckFormatHandler {
4487public:
4488 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4489 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004490 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004491 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004492 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004493 Sema::VariadicCallType CallType,
4494 llvm::SmallBitVector &CheckedVarArgs)
4495 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4496 numDataArgs, beg, hasVAListArg,
4497 Args, formatIdx, inFunctionCall, CallType,
4498 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004499 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004500
4501 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4502 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004503 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004504
4505 bool HandleInvalidScanfConversionSpecifier(
4506 const analyze_scanf::ScanfSpecifier &FS,
4507 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004508 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004509
Craig Toppere14c0f82014-03-12 04:55:44 +00004510 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004511};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004512}
Ted Kremenekab278de2010-01-28 23:39:18 +00004513
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004514void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4515 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004516 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4517 getLocationOfByte(end), /*IsStringLocation*/true,
4518 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004519}
4520
Ted Kremenekce815422010-07-19 21:25:57 +00004521bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4522 const analyze_scanf::ScanfSpecifier &FS,
4523 const char *startSpecifier,
4524 unsigned specifierLen) {
4525
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004526 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004527 FS.getConversionSpecifier();
4528
4529 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4530 getLocationOfByte(CS.getStart()),
4531 startSpecifier, specifierLen,
4532 CS.getStart(), CS.getLength());
4533}
4534
Ted Kremenek02087932010-07-16 02:11:22 +00004535bool CheckScanfHandler::HandleScanfSpecifier(
4536 const analyze_scanf::ScanfSpecifier &FS,
4537 const char *startSpecifier,
4538 unsigned specifierLen) {
4539
4540 using namespace analyze_scanf;
4541 using namespace analyze_format_string;
4542
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004543 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004544
Ted Kremenek6cd69422010-07-19 22:01:06 +00004545 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4546 // be used to decide if we are using positional arguments consistently.
4547 if (FS.consumesDataArgument()) {
4548 if (atFirstArg) {
4549 atFirstArg = false;
4550 usesPositionalArgs = FS.usesPositionalArg();
4551 }
4552 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004553 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4554 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004555 return false;
4556 }
Ted Kremenek02087932010-07-16 02:11:22 +00004557 }
4558
4559 // Check if the field with is non-zero.
4560 const OptionalAmount &Amt = FS.getFieldWidth();
4561 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4562 if (Amt.getConstantAmount() == 0) {
4563 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4564 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004565 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4566 getLocationOfByte(Amt.getStart()),
4567 /*IsStringLocation*/true, R,
4568 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004569 }
4570 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004571
Ted Kremenek02087932010-07-16 02:11:22 +00004572 if (!FS.consumesDataArgument()) {
4573 // FIXME: Technically specifying a precision or field width here
4574 // makes no sense. Worth issuing a warning at some point.
4575 return true;
4576 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004577
Ted Kremenek02087932010-07-16 02:11:22 +00004578 // Consume the argument.
4579 unsigned argIndex = FS.getArgIndex();
4580 if (argIndex < NumDataArgs) {
4581 // The check to see if the argIndex is valid will come later.
4582 // We set the bit here because we may exit early from this
4583 // function if we encounter some other error.
4584 CoveredArgs.set(argIndex);
4585 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004586
Ted Kremenek4407ea42010-07-20 20:04:47 +00004587 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004588 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004589 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4590 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004591 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004592 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004593 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004594 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4595 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004596
Jordan Rose92303592012-09-08 04:00:03 +00004597 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4598 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4599
Ted Kremenek02087932010-07-16 02:11:22 +00004600 // The remaining checks depend on the data arguments.
4601 if (HasVAListArg)
4602 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004603
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004604 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004605 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004606
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004607 // Check that the argument type matches the format specifier.
4608 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004609 if (!Ex)
4610 return true;
4611
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004612 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004613
4614 if (!AT.isValid()) {
4615 return true;
4616 }
4617
Seth Cantrellb4802962015-03-04 03:12:10 +00004618 analyze_format_string::ArgType::MatchKind match =
4619 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004620 if (match == analyze_format_string::ArgType::Match) {
4621 return true;
4622 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004623
Seth Cantrell79340072015-03-04 05:58:08 +00004624 ScanfSpecifier fixedFS = FS;
4625 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4626 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004627
Seth Cantrell79340072015-03-04 05:58:08 +00004628 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4629 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4630 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4631 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004632
Seth Cantrell79340072015-03-04 05:58:08 +00004633 if (success) {
4634 // Get the fix string from the fixed format specifier.
4635 SmallString<128> buf;
4636 llvm::raw_svector_ostream os(buf);
4637 fixedFS.toString(os);
4638
4639 EmitFormatDiagnostic(
4640 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4641 << Ex->getType() << false << Ex->getSourceRange(),
4642 Ex->getLocStart(),
4643 /*IsStringLocation*/ false,
4644 getSpecifierRange(startSpecifier, specifierLen),
4645 FixItHint::CreateReplacement(
4646 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4647 } else {
4648 EmitFormatDiagnostic(S.PDiag(diag)
4649 << AT.getRepresentativeTypeName(S.Context)
4650 << Ex->getType() << false << Ex->getSourceRange(),
4651 Ex->getLocStart(),
4652 /*IsStringLocation*/ false,
4653 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004654 }
4655
Ted Kremenek02087932010-07-16 02:11:22 +00004656 return true;
4657}
4658
4659void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004660 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004661 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004662 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004663 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004664 bool inFunctionCall, VariadicCallType CallType,
4665 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004666
Ted Kremenekab278de2010-01-28 23:39:18 +00004667 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004668 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004669 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004670 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004671 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4672 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004673 return;
4674 }
Ted Kremenek02087932010-07-16 02:11:22 +00004675
Ted Kremenekab278de2010-01-28 23:39:18 +00004676 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004677 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004678 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004679 // Account for cases where the string literal is truncated in a declaration.
4680 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4681 assert(T && "String literal not of constant array type!");
4682 size_t TypeSize = T->getSize().getZExtValue();
4683 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004684 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004685
4686 // Emit a warning if the string literal is truncated and does not contain an
4687 // embedded null character.
4688 if (TypeSize <= StrRef.size() &&
4689 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4690 CheckFormatHandler::EmitFormatDiagnostic(
4691 *this, inFunctionCall, Args[format_idx],
4692 PDiag(diag::warn_printf_format_string_not_null_terminated),
4693 FExpr->getLocStart(),
4694 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4695 return;
4696 }
4697
Ted Kremenekab278de2010-01-28 23:39:18 +00004698 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004699 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004700 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004701 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004702 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4703 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004704 return;
4705 }
Ted Kremenek02087932010-07-16 02:11:22 +00004706
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004707 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004708 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004709 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004710 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004711 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004712 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004713
Hans Wennborg23926bd2011-12-15 10:25:47 +00004714 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004715 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004716 Context.getTargetInfo(),
4717 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004718 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004719 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004720 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004721 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004722 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004723
Hans Wennborg23926bd2011-12-15 10:25:47 +00004724 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004725 getLangOpts(),
4726 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004727 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004728 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004729}
4730
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004731bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4732 // Str - The format string. NOTE: this is NOT null-terminated!
4733 StringRef StrRef = FExpr->getString();
4734 const char *Str = StrRef.data();
4735 // Account for cases where the string literal is truncated in a declaration.
4736 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4737 assert(T && "String literal not of constant array type!");
4738 size_t TypeSize = T->getSize().getZExtValue();
4739 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4740 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4741 getLangOpts(),
4742 Context.getTargetInfo());
4743}
4744
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004745//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4746
4747// Returns the related absolute value function that is larger, of 0 if one
4748// does not exist.
4749static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4750 switch (AbsFunction) {
4751 default:
4752 return 0;
4753
4754 case Builtin::BI__builtin_abs:
4755 return Builtin::BI__builtin_labs;
4756 case Builtin::BI__builtin_labs:
4757 return Builtin::BI__builtin_llabs;
4758 case Builtin::BI__builtin_llabs:
4759 return 0;
4760
4761 case Builtin::BI__builtin_fabsf:
4762 return Builtin::BI__builtin_fabs;
4763 case Builtin::BI__builtin_fabs:
4764 return Builtin::BI__builtin_fabsl;
4765 case Builtin::BI__builtin_fabsl:
4766 return 0;
4767
4768 case Builtin::BI__builtin_cabsf:
4769 return Builtin::BI__builtin_cabs;
4770 case Builtin::BI__builtin_cabs:
4771 return Builtin::BI__builtin_cabsl;
4772 case Builtin::BI__builtin_cabsl:
4773 return 0;
4774
4775 case Builtin::BIabs:
4776 return Builtin::BIlabs;
4777 case Builtin::BIlabs:
4778 return Builtin::BIllabs;
4779 case Builtin::BIllabs:
4780 return 0;
4781
4782 case Builtin::BIfabsf:
4783 return Builtin::BIfabs;
4784 case Builtin::BIfabs:
4785 return Builtin::BIfabsl;
4786 case Builtin::BIfabsl:
4787 return 0;
4788
4789 case Builtin::BIcabsf:
4790 return Builtin::BIcabs;
4791 case Builtin::BIcabs:
4792 return Builtin::BIcabsl;
4793 case Builtin::BIcabsl:
4794 return 0;
4795 }
4796}
4797
4798// Returns the argument type of the absolute value function.
4799static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4800 unsigned AbsType) {
4801 if (AbsType == 0)
4802 return QualType();
4803
4804 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4805 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4806 if (Error != ASTContext::GE_None)
4807 return QualType();
4808
4809 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4810 if (!FT)
4811 return QualType();
4812
4813 if (FT->getNumParams() != 1)
4814 return QualType();
4815
4816 return FT->getParamType(0);
4817}
4818
4819// Returns the best absolute value function, or zero, based on type and
4820// current absolute value function.
4821static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4822 unsigned AbsFunctionKind) {
4823 unsigned BestKind = 0;
4824 uint64_t ArgSize = Context.getTypeSize(ArgType);
4825 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4826 Kind = getLargerAbsoluteValueFunction(Kind)) {
4827 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4828 if (Context.getTypeSize(ParamType) >= ArgSize) {
4829 if (BestKind == 0)
4830 BestKind = Kind;
4831 else if (Context.hasSameType(ParamType, ArgType)) {
4832 BestKind = Kind;
4833 break;
4834 }
4835 }
4836 }
4837 return BestKind;
4838}
4839
4840enum AbsoluteValueKind {
4841 AVK_Integer,
4842 AVK_Floating,
4843 AVK_Complex
4844};
4845
4846static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4847 if (T->isIntegralOrEnumerationType())
4848 return AVK_Integer;
4849 if (T->isRealFloatingType())
4850 return AVK_Floating;
4851 if (T->isAnyComplexType())
4852 return AVK_Complex;
4853
4854 llvm_unreachable("Type not integer, floating, or complex");
4855}
4856
4857// Changes the absolute value function to a different type. Preserves whether
4858// the function is a builtin.
4859static unsigned changeAbsFunction(unsigned AbsKind,
4860 AbsoluteValueKind ValueKind) {
4861 switch (ValueKind) {
4862 case AVK_Integer:
4863 switch (AbsKind) {
4864 default:
4865 return 0;
4866 case Builtin::BI__builtin_fabsf:
4867 case Builtin::BI__builtin_fabs:
4868 case Builtin::BI__builtin_fabsl:
4869 case Builtin::BI__builtin_cabsf:
4870 case Builtin::BI__builtin_cabs:
4871 case Builtin::BI__builtin_cabsl:
4872 return Builtin::BI__builtin_abs;
4873 case Builtin::BIfabsf:
4874 case Builtin::BIfabs:
4875 case Builtin::BIfabsl:
4876 case Builtin::BIcabsf:
4877 case Builtin::BIcabs:
4878 case Builtin::BIcabsl:
4879 return Builtin::BIabs;
4880 }
4881 case AVK_Floating:
4882 switch (AbsKind) {
4883 default:
4884 return 0;
4885 case Builtin::BI__builtin_abs:
4886 case Builtin::BI__builtin_labs:
4887 case Builtin::BI__builtin_llabs:
4888 case Builtin::BI__builtin_cabsf:
4889 case Builtin::BI__builtin_cabs:
4890 case Builtin::BI__builtin_cabsl:
4891 return Builtin::BI__builtin_fabsf;
4892 case Builtin::BIabs:
4893 case Builtin::BIlabs:
4894 case Builtin::BIllabs:
4895 case Builtin::BIcabsf:
4896 case Builtin::BIcabs:
4897 case Builtin::BIcabsl:
4898 return Builtin::BIfabsf;
4899 }
4900 case AVK_Complex:
4901 switch (AbsKind) {
4902 default:
4903 return 0;
4904 case Builtin::BI__builtin_abs:
4905 case Builtin::BI__builtin_labs:
4906 case Builtin::BI__builtin_llabs:
4907 case Builtin::BI__builtin_fabsf:
4908 case Builtin::BI__builtin_fabs:
4909 case Builtin::BI__builtin_fabsl:
4910 return Builtin::BI__builtin_cabsf;
4911 case Builtin::BIabs:
4912 case Builtin::BIlabs:
4913 case Builtin::BIllabs:
4914 case Builtin::BIfabsf:
4915 case Builtin::BIfabs:
4916 case Builtin::BIfabsl:
4917 return Builtin::BIcabsf;
4918 }
4919 }
4920 llvm_unreachable("Unable to convert function");
4921}
4922
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004923static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004924 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4925 if (!FnInfo)
4926 return 0;
4927
4928 switch (FDecl->getBuiltinID()) {
4929 default:
4930 return 0;
4931 case Builtin::BI__builtin_abs:
4932 case Builtin::BI__builtin_fabs:
4933 case Builtin::BI__builtin_fabsf:
4934 case Builtin::BI__builtin_fabsl:
4935 case Builtin::BI__builtin_labs:
4936 case Builtin::BI__builtin_llabs:
4937 case Builtin::BI__builtin_cabs:
4938 case Builtin::BI__builtin_cabsf:
4939 case Builtin::BI__builtin_cabsl:
4940 case Builtin::BIabs:
4941 case Builtin::BIlabs:
4942 case Builtin::BIllabs:
4943 case Builtin::BIfabs:
4944 case Builtin::BIfabsf:
4945 case Builtin::BIfabsl:
4946 case Builtin::BIcabs:
4947 case Builtin::BIcabsf:
4948 case Builtin::BIcabsl:
4949 return FDecl->getBuiltinID();
4950 }
4951 llvm_unreachable("Unknown Builtin type");
4952}
4953
4954// If the replacement is valid, emit a note with replacement function.
4955// Additionally, suggest including the proper header if not already included.
4956static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004957 unsigned AbsKind, QualType ArgType) {
4958 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004959 const char *HeaderName = nullptr;
4960 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004961 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4962 FunctionName = "std::abs";
4963 if (ArgType->isIntegralOrEnumerationType()) {
4964 HeaderName = "cstdlib";
4965 } else if (ArgType->isRealFloatingType()) {
4966 HeaderName = "cmath";
4967 } else {
4968 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004969 }
Richard Trieubeffb832014-04-15 23:47:53 +00004970
4971 // Lookup all std::abs
4972 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004973 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004974 R.suppressDiagnostics();
4975 S.LookupQualifiedName(R, Std);
4976
4977 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004978 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004979 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4980 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4981 } else {
4982 FDecl = dyn_cast<FunctionDecl>(I);
4983 }
4984 if (!FDecl)
4985 continue;
4986
4987 // Found std::abs(), check that they are the right ones.
4988 if (FDecl->getNumParams() != 1)
4989 continue;
4990
4991 // Check that the parameter type can handle the argument.
4992 QualType ParamType = FDecl->getParamDecl(0)->getType();
4993 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4994 S.Context.getTypeSize(ArgType) <=
4995 S.Context.getTypeSize(ParamType)) {
4996 // Found a function, don't need the header hint.
4997 EmitHeaderHint = false;
4998 break;
4999 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005000 }
Richard Trieubeffb832014-04-15 23:47:53 +00005001 }
5002 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005003 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005004 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5005
5006 if (HeaderName) {
5007 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5008 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5009 R.suppressDiagnostics();
5010 S.LookupName(R, S.getCurScope());
5011
5012 if (R.isSingleResult()) {
5013 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5014 if (FD && FD->getBuiltinID() == AbsKind) {
5015 EmitHeaderHint = false;
5016 } else {
5017 return;
5018 }
5019 } else if (!R.empty()) {
5020 return;
5021 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005022 }
5023 }
5024
5025 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005026 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005027
Richard Trieubeffb832014-04-15 23:47:53 +00005028 if (!HeaderName)
5029 return;
5030
5031 if (!EmitHeaderHint)
5032 return;
5033
Alp Toker5d96e0a2014-07-11 20:53:51 +00005034 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5035 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005036}
5037
5038static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5039 if (!FDecl)
5040 return false;
5041
5042 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5043 return false;
5044
5045 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5046
5047 while (ND && ND->isInlineNamespace()) {
5048 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005049 }
Richard Trieubeffb832014-04-15 23:47:53 +00005050
5051 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5052 return false;
5053
5054 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5055 return false;
5056
5057 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005058}
5059
5060// Warn when using the wrong abs() function.
5061void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5062 const FunctionDecl *FDecl,
5063 IdentifierInfo *FnInfo) {
5064 if (Call->getNumArgs() != 1)
5065 return;
5066
5067 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005068 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5069 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005070 return;
5071
5072 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5073 QualType ParamType = Call->getArg(0)->getType();
5074
Alp Toker5d96e0a2014-07-11 20:53:51 +00005075 // Unsigned types cannot be negative. Suggest removing the absolute value
5076 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005077 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005078 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005079 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005080 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5081 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005082 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005083 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5084 return;
5085 }
5086
David Majnemer7f77eb92015-11-15 03:04:34 +00005087 // Taking the absolute value of a pointer is very suspicious, they probably
5088 // wanted to index into an array, dereference a pointer, call a function, etc.
5089 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5090 unsigned DiagType = 0;
5091 if (ArgType->isFunctionType())
5092 DiagType = 1;
5093 else if (ArgType->isArrayType())
5094 DiagType = 2;
5095
5096 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5097 return;
5098 }
5099
Richard Trieubeffb832014-04-15 23:47:53 +00005100 // std::abs has overloads which prevent most of the absolute value problems
5101 // from occurring.
5102 if (IsStdAbs)
5103 return;
5104
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005105 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5106 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5107
5108 // The argument and parameter are the same kind. Check if they are the right
5109 // size.
5110 if (ArgValueKind == ParamValueKind) {
5111 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5112 return;
5113
5114 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5115 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5116 << FDecl << ArgType << ParamType;
5117
5118 if (NewAbsKind == 0)
5119 return;
5120
5121 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005122 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005123 return;
5124 }
5125
5126 // ArgValueKind != ParamValueKind
5127 // The wrong type of absolute value function was used. Attempt to find the
5128 // proper one.
5129 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5130 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5131 if (NewAbsKind == 0)
5132 return;
5133
5134 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5135 << FDecl << ParamValueKind << ArgValueKind;
5136
5137 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005138 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005139 return;
5140}
5141
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005142//===--- CHECK: Standard memory functions ---------------------------------===//
5143
Nico Weber0e6daef2013-12-26 23:38:39 +00005144/// \brief Takes the expression passed to the size_t parameter of functions
5145/// such as memcmp, strncat, etc and warns if it's a comparison.
5146///
5147/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5148static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5149 IdentifierInfo *FnName,
5150 SourceLocation FnLoc,
5151 SourceLocation RParenLoc) {
5152 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5153 if (!Size)
5154 return false;
5155
5156 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5157 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5158 return false;
5159
Nico Weber0e6daef2013-12-26 23:38:39 +00005160 SourceRange SizeRange = Size->getSourceRange();
5161 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5162 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005163 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005164 << FnName << FixItHint::CreateInsertion(
5165 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005166 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005167 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005168 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005169 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5170 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005171
5172 return true;
5173}
5174
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005175/// \brief Determine whether the given type is or contains a dynamic class type
5176/// (e.g., whether it has a vtable).
5177static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5178 bool &IsContained) {
5179 // Look through array types while ignoring qualifiers.
5180 const Type *Ty = T->getBaseElementTypeUnsafe();
5181 IsContained = false;
5182
5183 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5184 RD = RD ? RD->getDefinition() : nullptr;
5185 if (!RD)
5186 return nullptr;
5187
5188 if (RD->isDynamicClass())
5189 return RD;
5190
5191 // Check all the fields. If any bases were dynamic, the class is dynamic.
5192 // It's impossible for a class to transitively contain itself by value, so
5193 // infinite recursion is impossible.
5194 for (auto *FD : RD->fields()) {
5195 bool SubContained;
5196 if (const CXXRecordDecl *ContainedRD =
5197 getContainedDynamicClass(FD->getType(), SubContained)) {
5198 IsContained = true;
5199 return ContainedRD;
5200 }
5201 }
5202
5203 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005204}
5205
Chandler Carruth889ed862011-06-21 23:04:20 +00005206/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005207/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005208static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005209 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005210 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5211 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5212 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005213
Craig Topperc3ec1492014-05-26 06:22:03 +00005214 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005215}
5216
Chandler Carruth889ed862011-06-21 23:04:20 +00005217/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005218static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005219 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5220 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5221 if (SizeOf->getKind() == clang::UETT_SizeOf)
5222 return SizeOf->getTypeOfArgument();
5223
5224 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005225}
5226
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005227/// \brief Check for dangerous or invalid arguments to memset().
5228///
Chandler Carruthac687262011-06-03 06:23:57 +00005229/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005230/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5231/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005232///
5233/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005234void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005235 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005236 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005237 assert(BId != 0);
5238
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005239 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005240 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005241 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005242 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005243 return;
5244
Anna Zaks22122702012-01-17 00:37:07 +00005245 unsigned LastArg = (BId == Builtin::BImemset ||
5246 BId == Builtin::BIstrndup ? 1 : 2);
5247 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005248 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005249
Nico Weber0e6daef2013-12-26 23:38:39 +00005250 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5251 Call->getLocStart(), Call->getRParenLoc()))
5252 return;
5253
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005254 // We have special checking when the length is a sizeof expression.
5255 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5256 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5257 llvm::FoldingSetNodeID SizeOfArgID;
5258
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005259 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5260 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005261 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005262
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005263 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005264 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005265 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005266 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005267
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005268 // Never warn about void type pointers. This can be used to suppress
5269 // false positives.
5270 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005271 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005272
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005273 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5274 // actually comparing the expressions for equality. Because computing the
5275 // expression IDs can be expensive, we only do this if the diagnostic is
5276 // enabled.
5277 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005278 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5279 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005280 // We only compute IDs for expressions if the warning is enabled, and
5281 // cache the sizeof arg's ID.
5282 if (SizeOfArgID == llvm::FoldingSetNodeID())
5283 SizeOfArg->Profile(SizeOfArgID, Context, true);
5284 llvm::FoldingSetNodeID DestID;
5285 Dest->Profile(DestID, Context, true);
5286 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005287 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5288 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005289 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005290 StringRef ReadableName = FnName->getName();
5291
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005292 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005293 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005294 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005295 if (!PointeeTy->isIncompleteType() &&
5296 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005297 ActionIdx = 2; // If the pointee's size is sizeof(char),
5298 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005299
5300 // If the function is defined as a builtin macro, do not show macro
5301 // expansion.
5302 SourceLocation SL = SizeOfArg->getExprLoc();
5303 SourceRange DSR = Dest->getSourceRange();
5304 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005305 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005306
5307 if (SM.isMacroArgExpansion(SL)) {
5308 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5309 SL = SM.getSpellingLoc(SL);
5310 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5311 SM.getSpellingLoc(DSR.getEnd()));
5312 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5313 SM.getSpellingLoc(SSR.getEnd()));
5314 }
5315
Anna Zaksd08d9152012-05-30 23:14:52 +00005316 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005317 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005318 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005319 << PointeeTy
5320 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005321 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005322 << SSR);
5323 DiagRuntimeBehavior(SL, SizeOfArg,
5324 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5325 << ActionIdx
5326 << SSR);
5327
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005328 break;
5329 }
5330 }
5331
5332 // Also check for cases where the sizeof argument is the exact same
5333 // type as the memory argument, and where it points to a user-defined
5334 // record type.
5335 if (SizeOfArgTy != QualType()) {
5336 if (PointeeTy->isRecordType() &&
5337 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5338 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5339 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5340 << FnName << SizeOfArgTy << ArgIdx
5341 << PointeeTy << Dest->getSourceRange()
5342 << LenExpr->getSourceRange());
5343 break;
5344 }
Nico Weberc5e73862011-06-14 16:14:58 +00005345 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005346 } else if (DestTy->isArrayType()) {
5347 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005348 }
Nico Weberc5e73862011-06-14 16:14:58 +00005349
Nico Weberc44b35e2015-03-21 17:37:46 +00005350 if (PointeeTy == QualType())
5351 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005352
Nico Weberc44b35e2015-03-21 17:37:46 +00005353 // Always complain about dynamic classes.
5354 bool IsContained;
5355 if (const CXXRecordDecl *ContainedRD =
5356 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005357
Nico Weberc44b35e2015-03-21 17:37:46 +00005358 unsigned OperationType = 0;
5359 // "overwritten" if we're warning about the destination for any call
5360 // but memcmp; otherwise a verb appropriate to the call.
5361 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5362 if (BId == Builtin::BImemcpy)
5363 OperationType = 1;
5364 else if(BId == Builtin::BImemmove)
5365 OperationType = 2;
5366 else if (BId == Builtin::BImemcmp)
5367 OperationType = 3;
5368 }
5369
John McCall31168b02011-06-15 23:02:42 +00005370 DiagRuntimeBehavior(
5371 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005372 PDiag(diag::warn_dyn_class_memaccess)
5373 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5374 << FnName << IsContained << ContainedRD << OperationType
5375 << Call->getCallee()->getSourceRange());
5376 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5377 BId != Builtin::BImemset)
5378 DiagRuntimeBehavior(
5379 Dest->getExprLoc(), Dest,
5380 PDiag(diag::warn_arc_object_memaccess)
5381 << ArgIdx << FnName << PointeeTy
5382 << Call->getCallee()->getSourceRange());
5383 else
5384 continue;
5385
5386 DiagRuntimeBehavior(
5387 Dest->getExprLoc(), Dest,
5388 PDiag(diag::note_bad_memaccess_silence)
5389 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5390 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005391 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005392
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005393}
5394
Ted Kremenek6865f772011-08-18 20:55:45 +00005395// A little helper routine: ignore addition and subtraction of integer literals.
5396// This intentionally does not ignore all integer constant expressions because
5397// we don't want to remove sizeof().
5398static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5399 Ex = Ex->IgnoreParenCasts();
5400
5401 for (;;) {
5402 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5403 if (!BO || !BO->isAdditiveOp())
5404 break;
5405
5406 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5407 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5408
5409 if (isa<IntegerLiteral>(RHS))
5410 Ex = LHS;
5411 else if (isa<IntegerLiteral>(LHS))
5412 Ex = RHS;
5413 else
5414 break;
5415 }
5416
5417 return Ex;
5418}
5419
Anna Zaks13b08572012-08-08 21:42:23 +00005420static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5421 ASTContext &Context) {
5422 // Only handle constant-sized or VLAs, but not flexible members.
5423 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5424 // Only issue the FIXIT for arrays of size > 1.
5425 if (CAT->getSize().getSExtValue() <= 1)
5426 return false;
5427 } else if (!Ty->isVariableArrayType()) {
5428 return false;
5429 }
5430 return true;
5431}
5432
Ted Kremenek6865f772011-08-18 20:55:45 +00005433// Warn if the user has made the 'size' argument to strlcpy or strlcat
5434// be the size of the source, instead of the destination.
5435void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5436 IdentifierInfo *FnName) {
5437
5438 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005439 unsigned NumArgs = Call->getNumArgs();
5440 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005441 return;
5442
5443 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5444 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005445 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005446
5447 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5448 Call->getLocStart(), Call->getRParenLoc()))
5449 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005450
5451 // Look for 'strlcpy(dst, x, sizeof(x))'
5452 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5453 CompareWithSrc = Ex;
5454 else {
5455 // Look for 'strlcpy(dst, x, strlen(x))'
5456 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005457 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5458 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005459 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5460 }
5461 }
5462
5463 if (!CompareWithSrc)
5464 return;
5465
5466 // Determine if the argument to sizeof/strlen is equal to the source
5467 // argument. In principle there's all kinds of things you could do
5468 // here, for instance creating an == expression and evaluating it with
5469 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5470 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5471 if (!SrcArgDRE)
5472 return;
5473
5474 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5475 if (!CompareWithSrcDRE ||
5476 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5477 return;
5478
5479 const Expr *OriginalSizeArg = Call->getArg(2);
5480 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5481 << OriginalSizeArg->getSourceRange() << FnName;
5482
5483 // Output a FIXIT hint if the destination is an array (rather than a
5484 // pointer to an array). This could be enhanced to handle some
5485 // pointers if we know the actual size, like if DstArg is 'array+2'
5486 // we could say 'sizeof(array)-2'.
5487 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005488 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005489 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005490
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005491 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005492 llvm::raw_svector_ostream OS(sizeString);
5493 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005494 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005495 OS << ")";
5496
5497 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5498 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5499 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005500}
5501
Anna Zaks314cd092012-02-01 19:08:57 +00005502/// Check if two expressions refer to the same declaration.
5503static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5504 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5505 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5506 return D1->getDecl() == D2->getDecl();
5507 return false;
5508}
5509
5510static const Expr *getStrlenExprArg(const Expr *E) {
5511 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5512 const FunctionDecl *FD = CE->getDirectCallee();
5513 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005514 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005515 return CE->getArg(0)->IgnoreParenCasts();
5516 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005517 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005518}
5519
5520// Warn on anti-patterns as the 'size' argument to strncat.
5521// The correct size argument should look like following:
5522// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5523void Sema::CheckStrncatArguments(const CallExpr *CE,
5524 IdentifierInfo *FnName) {
5525 // Don't crash if the user has the wrong number of arguments.
5526 if (CE->getNumArgs() < 3)
5527 return;
5528 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5529 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5530 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5531
Nico Weber0e6daef2013-12-26 23:38:39 +00005532 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5533 CE->getRParenLoc()))
5534 return;
5535
Anna Zaks314cd092012-02-01 19:08:57 +00005536 // Identify common expressions, which are wrongly used as the size argument
5537 // to strncat and may lead to buffer overflows.
5538 unsigned PatternType = 0;
5539 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5540 // - sizeof(dst)
5541 if (referToTheSameDecl(SizeOfArg, DstArg))
5542 PatternType = 1;
5543 // - sizeof(src)
5544 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5545 PatternType = 2;
5546 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5547 if (BE->getOpcode() == BO_Sub) {
5548 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5549 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5550 // - sizeof(dst) - strlen(dst)
5551 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5552 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5553 PatternType = 1;
5554 // - sizeof(src) - (anything)
5555 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5556 PatternType = 2;
5557 }
5558 }
5559
5560 if (PatternType == 0)
5561 return;
5562
Anna Zaks5069aa32012-02-03 01:27:37 +00005563 // Generate the diagnostic.
5564 SourceLocation SL = LenArg->getLocStart();
5565 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005566 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005567
5568 // If the function is defined as a builtin macro, do not show macro expansion.
5569 if (SM.isMacroArgExpansion(SL)) {
5570 SL = SM.getSpellingLoc(SL);
5571 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5572 SM.getSpellingLoc(SR.getEnd()));
5573 }
5574
Anna Zaks13b08572012-08-08 21:42:23 +00005575 // Check if the destination is an array (rather than a pointer to an array).
5576 QualType DstTy = DstArg->getType();
5577 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5578 Context);
5579 if (!isKnownSizeArray) {
5580 if (PatternType == 1)
5581 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5582 else
5583 Diag(SL, diag::warn_strncat_src_size) << SR;
5584 return;
5585 }
5586
Anna Zaks314cd092012-02-01 19:08:57 +00005587 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005588 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005589 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005590 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005591
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005592 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005593 llvm::raw_svector_ostream OS(sizeString);
5594 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005595 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005596 OS << ") - ";
5597 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005598 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005599 OS << ") - 1";
5600
Anna Zaks5069aa32012-02-03 01:27:37 +00005601 Diag(SL, diag::note_strncat_wrong_size)
5602 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005603}
5604
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005605//===--- CHECK: Return Address of Stack Variable --------------------------===//
5606
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005607static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5608 Decl *ParentDecl);
5609static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5610 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005611
5612/// CheckReturnStackAddr - Check if a return statement returns the address
5613/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005614static void
5615CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5616 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005617
Craig Topperc3ec1492014-05-26 06:22:03 +00005618 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005619 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005620
5621 // Perform checking for returned stack addresses, local blocks,
5622 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005623 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005624 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005625 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005626 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005627 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005628 }
5629
Craig Topperc3ec1492014-05-26 06:22:03 +00005630 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005631 return; // Nothing suspicious was found.
5632
5633 SourceLocation diagLoc;
5634 SourceRange diagRange;
5635 if (refVars.empty()) {
5636 diagLoc = stackE->getLocStart();
5637 diagRange = stackE->getSourceRange();
5638 } else {
5639 // We followed through a reference variable. 'stackE' contains the
5640 // problematic expression but we will warn at the return statement pointing
5641 // at the reference variable. We will later display the "trail" of
5642 // reference variables using notes.
5643 diagLoc = refVars[0]->getLocStart();
5644 diagRange = refVars[0]->getSourceRange();
5645 }
5646
5647 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Craig Topperda7b27f2015-11-17 05:40:09 +00005648 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005649 << DR->getDecl()->getDeclName() << diagRange;
5650 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005651 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005652 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005653 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005654 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005655 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5656 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005657 }
5658
5659 // Display the "trail" of reference variables that we followed until we
5660 // found the problematic expression using notes.
5661 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5662 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5663 // If this var binds to another reference var, show the range of the next
5664 // var, otherwise the var binds to the problematic expression, in which case
5665 // show the range of the expression.
5666 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5667 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005668 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5669 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005670 }
5671}
5672
5673/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5674/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005675/// to a location on the stack, a local block, an address of a label, or a
5676/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005677/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005678/// encounter a subexpression that (1) clearly does not lead to one of the
5679/// above problematic expressions (2) is something we cannot determine leads to
5680/// a problematic expression based on such local checking.
5681///
5682/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5683/// the expression that they point to. Such variables are added to the
5684/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005685///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005686/// EvalAddr processes expressions that are pointers that are used as
5687/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005688/// At the base case of the recursion is a check for the above problematic
5689/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005690///
5691/// This implementation handles:
5692///
5693/// * pointer-to-pointer casts
5694/// * implicit conversions from array references to pointers
5695/// * taking the address of fields
5696/// * arbitrary interplay between "&" and "*" operators
5697/// * pointer arithmetic from an address of a stack variable
5698/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005699static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5700 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005701 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005702 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005703
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005704 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005705 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005706 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005707 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005708 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005709
Peter Collingbourne91147592011-04-15 00:35:48 +00005710 E = E->IgnoreParens();
5711
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005712 // Our "symbolic interpreter" is just a dispatch off the currently
5713 // viewed AST node. We then recursively traverse the AST by calling
5714 // EvalAddr and EvalVal appropriately.
5715 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005716 case Stmt::DeclRefExprClass: {
5717 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5718
Richard Smith40f08eb2014-01-30 22:05:38 +00005719 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005720 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005721 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005722
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005723 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5724 // If this is a reference variable, follow through to the expression that
5725 // it points to.
5726 if (V->hasLocalStorage() &&
5727 V->getType()->isReferenceType() && V->hasInit()) {
5728 // Add the reference variable to the "trail".
5729 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005730 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005731 }
5732
Craig Topperc3ec1492014-05-26 06:22:03 +00005733 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005734 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005735
Chris Lattner934edb22007-12-28 05:31:15 +00005736 case Stmt::UnaryOperatorClass: {
5737 // The only unary operator that make sense to handle here
5738 // is AddrOf. All others don't make sense as pointers.
5739 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005740
John McCalle3027922010-08-25 11:45:40 +00005741 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005742 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005743 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005744 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005745 }
Mike Stump11289f42009-09-09 15:08:12 +00005746
Chris Lattner934edb22007-12-28 05:31:15 +00005747 case Stmt::BinaryOperatorClass: {
5748 // Handle pointer arithmetic. All other binary operators are not valid
5749 // in this context.
5750 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005751 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005752
John McCalle3027922010-08-25 11:45:40 +00005753 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005754 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005755
Chris Lattner934edb22007-12-28 05:31:15 +00005756 Expr *Base = B->getLHS();
5757
5758 // Determine which argument is the real pointer base. It could be
5759 // the RHS argument instead of the LHS.
5760 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005761
Chris Lattner934edb22007-12-28 05:31:15 +00005762 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005763 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005764 }
Steve Naroff2752a172008-09-10 19:17:48 +00005765
Chris Lattner934edb22007-12-28 05:31:15 +00005766 // For conditional operators we need to see if either the LHS or RHS are
5767 // valid DeclRefExpr*s. If one of them is valid, we return it.
5768 case Stmt::ConditionalOperatorClass: {
5769 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005770
Chris Lattner934edb22007-12-28 05:31:15 +00005771 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005772 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5773 if (Expr *LHSExpr = C->getLHS()) {
5774 // In C++, we can have a throw-expression, which has 'void' type.
5775 if (!LHSExpr->getType()->isVoidType())
5776 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005777 return LHS;
5778 }
Chris Lattner934edb22007-12-28 05:31:15 +00005779
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005780 // In C++, we can have a throw-expression, which has 'void' type.
5781 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005782 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005783
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005784 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005785 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005786
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005787 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005788 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005789 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005790 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005791
5792 case Stmt::AddrLabelExprClass:
5793 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005794
John McCall28fc7092011-11-10 05:35:25 +00005795 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005796 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5797 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005798
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005799 // For casts, we need to handle conversions from arrays to
5800 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005801 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005802 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005803 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005804 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005805 case Stmt::CXXStaticCastExprClass:
5806 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005807 case Stmt::CXXConstCastExprClass:
5808 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005809 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5810 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005811 case CK_LValueToRValue:
5812 case CK_NoOp:
5813 case CK_BaseToDerived:
5814 case CK_DerivedToBase:
5815 case CK_UncheckedDerivedToBase:
5816 case CK_Dynamic:
5817 case CK_CPointerToObjCPointerCast:
5818 case CK_BlockPointerToObjCPointerCast:
5819 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005820 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005821
5822 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005823 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005824
Richard Trieudadefde2014-07-02 04:39:38 +00005825 case CK_BitCast:
5826 if (SubExpr->getType()->isAnyPointerType() ||
5827 SubExpr->getType()->isBlockPointerType() ||
5828 SubExpr->getType()->isObjCQualifiedIdType())
5829 return EvalAddr(SubExpr, refVars, ParentDecl);
5830 else
5831 return nullptr;
5832
Eli Friedman8195ad72012-02-23 23:04:32 +00005833 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005834 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005835 }
Chris Lattner934edb22007-12-28 05:31:15 +00005836 }
Mike Stump11289f42009-09-09 15:08:12 +00005837
Douglas Gregorfe314812011-06-21 17:03:29 +00005838 case Stmt::MaterializeTemporaryExprClass:
5839 if (Expr *Result = EvalAddr(
5840 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005841 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005842 return Result;
5843
5844 return E;
5845
Chris Lattner934edb22007-12-28 05:31:15 +00005846 // Everything else: we simply don't reason about them.
5847 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005848 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005849 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005850}
Mike Stump11289f42009-09-09 15:08:12 +00005851
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005852
5853/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5854/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005855static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5856 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005857do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005858 // We should only be called for evaluating non-pointer expressions, or
5859 // expressions with a pointer type that are not used as references but instead
5860 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005861
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005862 // Our "symbolic interpreter" is just a dispatch off the currently
5863 // viewed AST node. We then recursively traverse the AST by calling
5864 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005865
5866 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005867 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005868 case Stmt::ImplicitCastExprClass: {
5869 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005870 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005871 E = IE->getSubExpr();
5872 continue;
5873 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005874 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005875 }
5876
John McCall28fc7092011-11-10 05:35:25 +00005877 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005878 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005879
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005880 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005881 // When we hit a DeclRefExpr we are looking at code that refers to a
5882 // variable's name. If it's not a reference variable we check if it has
5883 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005884 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005885
Richard Smith40f08eb2014-01-30 22:05:38 +00005886 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005887 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005888 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005889
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005890 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5891 // Check if it refers to itself, e.g. "int& i = i;".
5892 if (V == ParentDecl)
5893 return DR;
5894
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005895 if (V->hasLocalStorage()) {
5896 if (!V->getType()->isReferenceType())
5897 return DR;
5898
5899 // Reference variable, follow through to the expression that
5900 // it points to.
5901 if (V->hasInit()) {
5902 // Add the reference variable to the "trail".
5903 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005904 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005905 }
5906 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005907 }
Mike Stump11289f42009-09-09 15:08:12 +00005908
Craig Topperc3ec1492014-05-26 06:22:03 +00005909 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005910 }
Mike Stump11289f42009-09-09 15:08:12 +00005911
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005912 case Stmt::UnaryOperatorClass: {
5913 // The only unary operator that make sense to handle here
5914 // is Deref. All others don't resolve to a "name." This includes
5915 // handling all sorts of rvalues passed to a unary operator.
5916 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005917
John McCalle3027922010-08-25 11:45:40 +00005918 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005919 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005920
Craig Topperc3ec1492014-05-26 06:22:03 +00005921 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005922 }
Mike Stump11289f42009-09-09 15:08:12 +00005923
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005924 case Stmt::ArraySubscriptExprClass: {
5925 // Array subscripts are potential references to data on the stack. We
5926 // retrieve the DeclRefExpr* for the array variable if it indeed
5927 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005928 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005929 }
Mike Stump11289f42009-09-09 15:08:12 +00005930
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005931 case Stmt::OMPArraySectionExprClass: {
5932 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5933 ParentDecl);
5934 }
5935
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005936 case Stmt::ConditionalOperatorClass: {
5937 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005938 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005939 ConditionalOperator *C = cast<ConditionalOperator>(E);
5940
Anders Carlsson801c5c72007-11-30 19:04:31 +00005941 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005942 if (Expr *LHSExpr = C->getLHS()) {
5943 // In C++, we can have a throw-expression, which has 'void' type.
5944 if (!LHSExpr->getType()->isVoidType())
5945 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5946 return LHS;
5947 }
5948
5949 // In C++, we can have a throw-expression, which has 'void' type.
5950 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005951 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005952
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005953 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005954 }
Mike Stump11289f42009-09-09 15:08:12 +00005955
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005956 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005957 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005958 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005959
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005960 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005961 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005962 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005963
5964 // Check whether the member type is itself a reference, in which case
5965 // we're not going to refer to the member, but to what the member refers to.
5966 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005967 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005968
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005969 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005970 }
Mike Stump11289f42009-09-09 15:08:12 +00005971
Douglas Gregorfe314812011-06-21 17:03:29 +00005972 case Stmt::MaterializeTemporaryExprClass:
5973 if (Expr *Result = EvalVal(
5974 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005975 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005976 return Result;
5977
5978 return E;
5979
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005980 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005981 // Check that we don't return or take the address of a reference to a
5982 // temporary. This is only useful in C++.
5983 if (!E->isTypeDependent() && E->isRValue())
5984 return E;
5985
5986 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005987 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005988 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005989} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005990}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005991
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005992void
5993Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5994 SourceLocation ReturnLoc,
5995 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005996 const AttrVec *Attrs,
5997 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005998 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5999
6000 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006001 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6002 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006003 CheckNonNullExpr(*this, RetValExp))
6004 Diag(ReturnLoc, diag::warn_null_ret)
6005 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006006
6007 // C++11 [basic.stc.dynamic.allocation]p4:
6008 // If an allocation function declared with a non-throwing
6009 // exception-specification fails to allocate storage, it shall return
6010 // a null pointer. Any other allocation function that fails to allocate
6011 // storage shall indicate failure only by throwing an exception [...]
6012 if (FD) {
6013 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6014 if (Op == OO_New || Op == OO_Array_New) {
6015 const FunctionProtoType *Proto
6016 = FD->getType()->castAs<FunctionProtoType>();
6017 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6018 CheckNonNullExpr(*this, RetValExp))
6019 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6020 << FD << getLangOpts().CPlusPlus11;
6021 }
6022 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006023}
6024
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006025//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6026
6027/// Check for comparisons of floating point operands using != and ==.
6028/// Issue a warning if these are no self-comparisons, as they are not likely
6029/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006030void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006031 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6032 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006033
6034 // Special case: check for x == x (which is OK).
6035 // Do not emit warnings for such cases.
6036 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6037 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6038 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006039 return;
Mike Stump11289f42009-09-09 15:08:12 +00006040
6041
Ted Kremenekeda40e22007-11-29 00:59:04 +00006042 // Special case: check for comparisons against literals that can be exactly
6043 // represented by APFloat. In such cases, do not emit a warning. This
6044 // is a heuristic: often comparison against such literals are used to
6045 // detect if a value in a variable has not changed. This clearly can
6046 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006047 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6048 if (FLL->isExact())
6049 return;
6050 } else
6051 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6052 if (FLR->isExact())
6053 return;
Mike Stump11289f42009-09-09 15:08:12 +00006054
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006055 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006056 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006057 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006058 return;
Mike Stump11289f42009-09-09 15:08:12 +00006059
David Blaikie1f4ff152012-07-16 20:47:22 +00006060 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006061 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006062 return;
Mike Stump11289f42009-09-09 15:08:12 +00006063
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006064 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006065 Diag(Loc, diag::warn_floatingpoint_eq)
6066 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006067}
John McCallca01b222010-01-04 23:21:16 +00006068
John McCall70aa5392010-01-06 05:24:50 +00006069//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6070//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006071
John McCall70aa5392010-01-06 05:24:50 +00006072namespace {
John McCallca01b222010-01-04 23:21:16 +00006073
John McCall70aa5392010-01-06 05:24:50 +00006074/// Structure recording the 'active' range of an integer-valued
6075/// expression.
6076struct IntRange {
6077 /// The number of bits active in the int.
6078 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006079
John McCall70aa5392010-01-06 05:24:50 +00006080 /// True if the int is known not to have negative values.
6081 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006082
John McCall70aa5392010-01-06 05:24:50 +00006083 IntRange(unsigned Width, bool NonNegative)
6084 : Width(Width), NonNegative(NonNegative)
6085 {}
John McCallca01b222010-01-04 23:21:16 +00006086
John McCall817d4af2010-11-10 23:38:19 +00006087 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006088 static IntRange forBoolType() {
6089 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006090 }
6091
John McCall817d4af2010-11-10 23:38:19 +00006092 /// Returns the range of an opaque value of the given integral type.
6093 static IntRange forValueOfType(ASTContext &C, QualType T) {
6094 return forValueOfCanonicalType(C,
6095 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006096 }
6097
John McCall817d4af2010-11-10 23:38:19 +00006098 /// Returns the range of an opaque value of a canonical integral type.
6099 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006100 assert(T->isCanonicalUnqualified());
6101
6102 if (const VectorType *VT = dyn_cast<VectorType>(T))
6103 T = VT->getElementType().getTypePtr();
6104 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6105 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006106 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6107 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006108
David Majnemer6a426652013-06-07 22:07:20 +00006109 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006110 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006111 EnumDecl *Enum = ET->getDecl();
6112 if (!Enum->isCompleteDefinition())
6113 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006114
David Majnemer6a426652013-06-07 22:07:20 +00006115 unsigned NumPositive = Enum->getNumPositiveBits();
6116 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006117
David Majnemer6a426652013-06-07 22:07:20 +00006118 if (NumNegative == 0)
6119 return IntRange(NumPositive, true/*NonNegative*/);
6120 else
6121 return IntRange(std::max(NumPositive + 1, NumNegative),
6122 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006123 }
John McCall70aa5392010-01-06 05:24:50 +00006124
6125 const BuiltinType *BT = cast<BuiltinType>(T);
6126 assert(BT->isInteger());
6127
6128 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6129 }
6130
John McCall817d4af2010-11-10 23:38:19 +00006131 /// Returns the "target" range of a canonical integral type, i.e.
6132 /// the range of values expressible in the type.
6133 ///
6134 /// This matches forValueOfCanonicalType except that enums have the
6135 /// full range of their type, not the range of their enumerators.
6136 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6137 assert(T->isCanonicalUnqualified());
6138
6139 if (const VectorType *VT = dyn_cast<VectorType>(T))
6140 T = VT->getElementType().getTypePtr();
6141 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6142 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006143 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6144 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006145 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006146 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006147
6148 const BuiltinType *BT = cast<BuiltinType>(T);
6149 assert(BT->isInteger());
6150
6151 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6152 }
6153
6154 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006155 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006156 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006157 L.NonNegative && R.NonNegative);
6158 }
6159
John McCall817d4af2010-11-10 23:38:19 +00006160 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006161 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006162 return IntRange(std::min(L.Width, R.Width),
6163 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006164 }
6165};
6166
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006167static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6168 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006169 if (value.isSigned() && value.isNegative())
6170 return IntRange(value.getMinSignedBits(), false);
6171
6172 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006173 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006174
6175 // isNonNegative() just checks the sign bit without considering
6176 // signedness.
6177 return IntRange(value.getActiveBits(), true);
6178}
6179
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006180static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6181 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006182 if (result.isInt())
6183 return GetValueRange(C, result.getInt(), MaxWidth);
6184
6185 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006186 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6187 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6188 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6189 R = IntRange::join(R, El);
6190 }
John McCall70aa5392010-01-06 05:24:50 +00006191 return R;
6192 }
6193
6194 if (result.isComplexInt()) {
6195 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6196 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6197 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006198 }
6199
6200 // This can happen with lossless casts to intptr_t of "based" lvalues.
6201 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006202 // FIXME: The only reason we need to pass the type in here is to get
6203 // the sign right on this one case. It would be nice if APValue
6204 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006205 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006206 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006207}
John McCall70aa5392010-01-06 05:24:50 +00006208
Eli Friedmane6d33952013-07-08 20:20:06 +00006209static QualType GetExprType(Expr *E) {
6210 QualType Ty = E->getType();
6211 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6212 Ty = AtomicRHS->getValueType();
6213 return Ty;
6214}
6215
John McCall70aa5392010-01-06 05:24:50 +00006216/// Pseudo-evaluate the given integer expression, estimating the
6217/// range of values it might take.
6218///
6219/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006220static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006221 E = E->IgnoreParens();
6222
6223 // Try a full evaluation first.
6224 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006225 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006226 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006227
6228 // I think we only want to look through implicit casts here; if the
6229 // user has an explicit widening cast, we should treat the value as
6230 // being of the new, wider type.
6231 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006232 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006233 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6234
Eli Friedmane6d33952013-07-08 20:20:06 +00006235 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006236
John McCalle3027922010-08-25 11:45:40 +00006237 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006238
John McCall70aa5392010-01-06 05:24:50 +00006239 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006240 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006241 return OutputTypeRange;
6242
6243 IntRange SubRange
6244 = GetExprRange(C, CE->getSubExpr(),
6245 std::min(MaxWidth, OutputTypeRange.Width));
6246
6247 // Bail out if the subexpr's range is as wide as the cast type.
6248 if (SubRange.Width >= OutputTypeRange.Width)
6249 return OutputTypeRange;
6250
6251 // Otherwise, we take the smaller width, and we're non-negative if
6252 // either the output type or the subexpr is.
6253 return IntRange(SubRange.Width,
6254 SubRange.NonNegative || OutputTypeRange.NonNegative);
6255 }
6256
6257 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6258 // If we can fold the condition, just take that operand.
6259 bool CondResult;
6260 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6261 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6262 : CO->getFalseExpr(),
6263 MaxWidth);
6264
6265 // Otherwise, conservatively merge.
6266 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6267 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6268 return IntRange::join(L, R);
6269 }
6270
6271 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6272 switch (BO->getOpcode()) {
6273
6274 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006275 case BO_LAnd:
6276 case BO_LOr:
6277 case BO_LT:
6278 case BO_GT:
6279 case BO_LE:
6280 case BO_GE:
6281 case BO_EQ:
6282 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006283 return IntRange::forBoolType();
6284
John McCallc3688382011-07-13 06:35:24 +00006285 // The type of the assignments is the type of the LHS, so the RHS
6286 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006287 case BO_MulAssign:
6288 case BO_DivAssign:
6289 case BO_RemAssign:
6290 case BO_AddAssign:
6291 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006292 case BO_XorAssign:
6293 case BO_OrAssign:
6294 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006295 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006296
John McCallc3688382011-07-13 06:35:24 +00006297 // Simple assignments just pass through the RHS, which will have
6298 // been coerced to the LHS type.
6299 case BO_Assign:
6300 // TODO: bitfields?
6301 return GetExprRange(C, BO->getRHS(), MaxWidth);
6302
John McCall70aa5392010-01-06 05:24:50 +00006303 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006304 case BO_PtrMemD:
6305 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006306 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006307
John McCall2ce81ad2010-01-06 22:07:33 +00006308 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006309 case BO_And:
6310 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006311 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6312 GetExprRange(C, BO->getRHS(), MaxWidth));
6313
John McCall70aa5392010-01-06 05:24:50 +00006314 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006315 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006316 // ...except that we want to treat '1 << (blah)' as logically
6317 // positive. It's an important idiom.
6318 if (IntegerLiteral *I
6319 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6320 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006321 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006322 return IntRange(R.Width, /*NonNegative*/ true);
6323 }
6324 }
6325 // fallthrough
6326
John McCalle3027922010-08-25 11:45:40 +00006327 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006328 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006329
John McCall2ce81ad2010-01-06 22:07:33 +00006330 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006331 case BO_Shr:
6332 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006333 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6334
6335 // If the shift amount is a positive constant, drop the width by
6336 // that much.
6337 llvm::APSInt shift;
6338 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6339 shift.isNonNegative()) {
6340 unsigned zext = shift.getZExtValue();
6341 if (zext >= L.Width)
6342 L.Width = (L.NonNegative ? 0 : 1);
6343 else
6344 L.Width -= zext;
6345 }
6346
6347 return L;
6348 }
6349
6350 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006351 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006352 return GetExprRange(C, BO->getRHS(), MaxWidth);
6353
John McCall2ce81ad2010-01-06 22:07:33 +00006354 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006355 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006356 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006357 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006358 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006359
John McCall51431812011-07-14 22:39:48 +00006360 // The width of a division result is mostly determined by the size
6361 // of the LHS.
6362 case BO_Div: {
6363 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006364 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006365 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6366
6367 // If the divisor is constant, use that.
6368 llvm::APSInt divisor;
6369 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6370 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6371 if (log2 >= L.Width)
6372 L.Width = (L.NonNegative ? 0 : 1);
6373 else
6374 L.Width = std::min(L.Width - log2, MaxWidth);
6375 return L;
6376 }
6377
6378 // Otherwise, just use the LHS's width.
6379 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6380 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6381 }
6382
6383 // The result of a remainder can't be larger than the result of
6384 // either side.
6385 case BO_Rem: {
6386 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006387 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006388 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6389 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6390
6391 IntRange meet = IntRange::meet(L, R);
6392 meet.Width = std::min(meet.Width, MaxWidth);
6393 return meet;
6394 }
6395
6396 // The default behavior is okay for these.
6397 case BO_Mul:
6398 case BO_Add:
6399 case BO_Xor:
6400 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006401 break;
6402 }
6403
John McCall51431812011-07-14 22:39:48 +00006404 // The default case is to treat the operation as if it were closed
6405 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006406 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6407 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6408 return IntRange::join(L, R);
6409 }
6410
6411 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6412 switch (UO->getOpcode()) {
6413 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006414 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006415 return IntRange::forBoolType();
6416
6417 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006418 case UO_Deref:
6419 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006420 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006421
6422 default:
6423 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6424 }
6425 }
6426
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006427 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6428 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6429
John McCalld25db7e2013-05-06 21:39:12 +00006430 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006431 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006432 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006433
Eli Friedmane6d33952013-07-08 20:20:06 +00006434 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006435}
John McCall263a48b2010-01-04 23:31:57 +00006436
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006437static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006438 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006439}
6440
John McCall263a48b2010-01-04 23:31:57 +00006441/// Checks whether the given value, which currently has the given
6442/// source semantics, has the same value when coerced through the
6443/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006444static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6445 const llvm::fltSemantics &Src,
6446 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006447 llvm::APFloat truncated = value;
6448
6449 bool ignored;
6450 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6451 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6452
6453 return truncated.bitwiseIsEqual(value);
6454}
6455
6456/// Checks whether the given value, which currently has the given
6457/// source semantics, has the same value when coerced through the
6458/// target semantics.
6459///
6460/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006461static bool IsSameFloatAfterCast(const APValue &value,
6462 const llvm::fltSemantics &Src,
6463 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006464 if (value.isFloat())
6465 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6466
6467 if (value.isVector()) {
6468 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6469 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6470 return false;
6471 return true;
6472 }
6473
6474 assert(value.isComplexFloat());
6475 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6476 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6477}
6478
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006479static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006480
Ted Kremenek6274be42010-09-23 21:43:44 +00006481static bool IsZero(Sema &S, Expr *E) {
6482 // Suppress cases where we are comparing against an enum constant.
6483 if (const DeclRefExpr *DR =
6484 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6485 if (isa<EnumConstantDecl>(DR->getDecl()))
6486 return false;
6487
6488 // Suppress cases where the '0' value is expanded from a macro.
6489 if (E->getLocStart().isMacroID())
6490 return false;
6491
John McCallcc7e5bf2010-05-06 08:58:33 +00006492 llvm::APSInt Value;
6493 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6494}
6495
John McCall2551c1b2010-10-06 00:25:24 +00006496static bool HasEnumType(Expr *E) {
6497 // Strip off implicit integral promotions.
6498 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006499 if (ICE->getCastKind() != CK_IntegralCast &&
6500 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006501 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006502 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006503 }
6504
6505 return E->getType()->isEnumeralType();
6506}
6507
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006508static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006509 // Disable warning in template instantiations.
6510 if (!S.ActiveTemplateInstantiations.empty())
6511 return;
6512
John McCalle3027922010-08-25 11:45:40 +00006513 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006514 if (E->isValueDependent())
6515 return;
6516
John McCalle3027922010-08-25 11:45:40 +00006517 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006518 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006519 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006520 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006521 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006522 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006523 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006524 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006525 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006526 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006527 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006528 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006529 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006530 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006531 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006532 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6533 }
6534}
6535
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006536static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006537 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006538 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006539 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006540 // Disable warning in template instantiations.
6541 if (!S.ActiveTemplateInstantiations.empty())
6542 return;
6543
Richard Trieu0f097742014-04-04 04:13:47 +00006544 // TODO: Investigate using GetExprRange() to get tighter bounds
6545 // on the bit ranges.
6546 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006547 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006548 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006549 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6550 unsigned OtherWidth = OtherRange.Width;
6551
6552 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6553
Richard Trieu560910c2012-11-14 22:50:24 +00006554 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006555 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006556 return;
6557
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006558 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006559 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006560
Richard Trieu0f097742014-04-04 04:13:47 +00006561 // Used for diagnostic printout.
6562 enum {
6563 LiteralConstant = 0,
6564 CXXBoolLiteralTrue,
6565 CXXBoolLiteralFalse
6566 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006567
Richard Trieu0f097742014-04-04 04:13:47 +00006568 if (!OtherIsBooleanType) {
6569 QualType ConstantT = Constant->getType();
6570 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006571
Richard Trieu0f097742014-04-04 04:13:47 +00006572 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6573 return;
6574 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6575 "comparison with non-integer type");
6576
6577 bool ConstantSigned = ConstantT->isSignedIntegerType();
6578 bool CommonSigned = CommonT->isSignedIntegerType();
6579
6580 bool EqualityOnly = false;
6581
6582 if (CommonSigned) {
6583 // The common type is signed, therefore no signed to unsigned conversion.
6584 if (!OtherRange.NonNegative) {
6585 // Check that the constant is representable in type OtherT.
6586 if (ConstantSigned) {
6587 if (OtherWidth >= Value.getMinSignedBits())
6588 return;
6589 } else { // !ConstantSigned
6590 if (OtherWidth >= Value.getActiveBits() + 1)
6591 return;
6592 }
6593 } else { // !OtherSigned
6594 // Check that the constant is representable in type OtherT.
6595 // Negative values are out of range.
6596 if (ConstantSigned) {
6597 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6598 return;
6599 } else { // !ConstantSigned
6600 if (OtherWidth >= Value.getActiveBits())
6601 return;
6602 }
Richard Trieu560910c2012-11-14 22:50:24 +00006603 }
Richard Trieu0f097742014-04-04 04:13:47 +00006604 } else { // !CommonSigned
6605 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006606 if (OtherWidth >= Value.getActiveBits())
6607 return;
Craig Toppercf360162014-06-18 05:13:11 +00006608 } else { // OtherSigned
6609 assert(!ConstantSigned &&
6610 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006611 // Check to see if the constant is representable in OtherT.
6612 if (OtherWidth > Value.getActiveBits())
6613 return;
6614 // Check to see if the constant is equivalent to a negative value
6615 // cast to CommonT.
6616 if (S.Context.getIntWidth(ConstantT) ==
6617 S.Context.getIntWidth(CommonT) &&
6618 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6619 return;
6620 // The constant value rests between values that OtherT can represent
6621 // after conversion. Relational comparison still works, but equality
6622 // comparisons will be tautological.
6623 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006624 }
6625 }
Richard Trieu0f097742014-04-04 04:13:47 +00006626
6627 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6628
6629 if (op == BO_EQ || op == BO_NE) {
6630 IsTrue = op == BO_NE;
6631 } else if (EqualityOnly) {
6632 return;
6633 } else if (RhsConstant) {
6634 if (op == BO_GT || op == BO_GE)
6635 IsTrue = !PositiveConstant;
6636 else // op == BO_LT || op == BO_LE
6637 IsTrue = PositiveConstant;
6638 } else {
6639 if (op == BO_LT || op == BO_LE)
6640 IsTrue = !PositiveConstant;
6641 else // op == BO_GT || op == BO_GE
6642 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006643 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006644 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006645 // Other isKnownToHaveBooleanValue
6646 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6647 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6648 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6649
6650 static const struct LinkedConditions {
6651 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6652 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6653 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6654 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6655 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6656 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6657
6658 } TruthTable = {
6659 // Constant on LHS. | Constant on RHS. |
6660 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6661 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6662 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6663 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6664 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6665 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6666 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6667 };
6668
6669 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6670
6671 enum ConstantValue ConstVal = Zero;
6672 if (Value.isUnsigned() || Value.isNonNegative()) {
6673 if (Value == 0) {
6674 LiteralOrBoolConstant =
6675 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6676 ConstVal = Zero;
6677 } else if (Value == 1) {
6678 LiteralOrBoolConstant =
6679 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6680 ConstVal = One;
6681 } else {
6682 LiteralOrBoolConstant = LiteralConstant;
6683 ConstVal = GT_One;
6684 }
6685 } else {
6686 ConstVal = LT_Zero;
6687 }
6688
6689 CompareBoolWithConstantResult CmpRes;
6690
6691 switch (op) {
6692 case BO_LT:
6693 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6694 break;
6695 case BO_GT:
6696 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6697 break;
6698 case BO_LE:
6699 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6700 break;
6701 case BO_GE:
6702 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6703 break;
6704 case BO_EQ:
6705 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6706 break;
6707 case BO_NE:
6708 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6709 break;
6710 default:
6711 CmpRes = Unkwn;
6712 break;
6713 }
6714
6715 if (CmpRes == AFals) {
6716 IsTrue = false;
6717 } else if (CmpRes == ATrue) {
6718 IsTrue = true;
6719 } else {
6720 return;
6721 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006722 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006723
6724 // If this is a comparison to an enum constant, include that
6725 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006726 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006727 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6728 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6729
6730 SmallString<64> PrettySourceValue;
6731 llvm::raw_svector_ostream OS(PrettySourceValue);
6732 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006733 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006734 else
6735 OS << Value;
6736
Richard Trieu0f097742014-04-04 04:13:47 +00006737 S.DiagRuntimeBehavior(
6738 E->getOperatorLoc(), E,
6739 S.PDiag(diag::warn_out_of_range_compare)
6740 << OS.str() << LiteralOrBoolConstant
6741 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6742 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006743}
6744
John McCallcc7e5bf2010-05-06 08:58:33 +00006745/// Analyze the operands of the given comparison. Implements the
6746/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006747static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006748 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6749 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006750}
John McCall263a48b2010-01-04 23:31:57 +00006751
John McCallca01b222010-01-04 23:21:16 +00006752/// \brief Implements -Wsign-compare.
6753///
Richard Trieu82402a02011-09-15 21:56:47 +00006754/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006755static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006756 // The type the comparison is being performed in.
6757 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006758
6759 // Only analyze comparison operators where both sides have been converted to
6760 // the same type.
6761 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6762 return AnalyzeImpConvsInComparison(S, E);
6763
6764 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006765 if (E->isValueDependent())
6766 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006767
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006768 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6769 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006770
6771 bool IsComparisonConstant = false;
6772
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006773 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006774 // of 'true' or 'false'.
6775 if (T->isIntegralType(S.Context)) {
6776 llvm::APSInt RHSValue;
6777 bool IsRHSIntegralLiteral =
6778 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6779 llvm::APSInt LHSValue;
6780 bool IsLHSIntegralLiteral =
6781 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6782 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6783 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6784 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6785 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6786 else
6787 IsComparisonConstant =
6788 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006789 } else if (!T->hasUnsignedIntegerRepresentation())
6790 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006791
John McCallcc7e5bf2010-05-06 08:58:33 +00006792 // We don't do anything special if this isn't an unsigned integral
6793 // comparison: we're only interested in integral comparisons, and
6794 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006795 //
6796 // We also don't care about value-dependent expressions or expressions
6797 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006798 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006799 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006800
John McCallcc7e5bf2010-05-06 08:58:33 +00006801 // Check to see if one of the (unmodified) operands is of different
6802 // signedness.
6803 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006804 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6805 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006806 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006807 signedOperand = LHS;
6808 unsignedOperand = RHS;
6809 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6810 signedOperand = RHS;
6811 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006812 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006813 CheckTrivialUnsignedComparison(S, E);
6814 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006815 }
6816
John McCallcc7e5bf2010-05-06 08:58:33 +00006817 // Otherwise, calculate the effective range of the signed operand.
6818 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006819
John McCallcc7e5bf2010-05-06 08:58:33 +00006820 // Go ahead and analyze implicit conversions in the operands. Note
6821 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006822 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6823 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006824
John McCallcc7e5bf2010-05-06 08:58:33 +00006825 // If the signed range is non-negative, -Wsign-compare won't fire,
6826 // but we should still check for comparisons which are always true
6827 // or false.
6828 if (signedRange.NonNegative)
6829 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006830
6831 // For (in)equality comparisons, if the unsigned operand is a
6832 // constant which cannot collide with a overflowed signed operand,
6833 // then reinterpreting the signed operand as unsigned will not
6834 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006835 if (E->isEqualityOp()) {
6836 unsigned comparisonWidth = S.Context.getIntWidth(T);
6837 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006838
John McCallcc7e5bf2010-05-06 08:58:33 +00006839 // We should never be unable to prove that the unsigned operand is
6840 // non-negative.
6841 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6842
6843 if (unsignedRange.Width < comparisonWidth)
6844 return;
6845 }
6846
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006847 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6848 S.PDiag(diag::warn_mixed_sign_comparison)
6849 << LHS->getType() << RHS->getType()
6850 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006851}
6852
John McCall1f425642010-11-11 03:21:53 +00006853/// Analyzes an attempt to assign the given value to a bitfield.
6854///
6855/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006856static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6857 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006858 assert(Bitfield->isBitField());
6859 if (Bitfield->isInvalidDecl())
6860 return false;
6861
John McCalldeebbcf2010-11-11 05:33:51 +00006862 // White-list bool bitfields.
6863 if (Bitfield->getType()->isBooleanType())
6864 return false;
6865
Douglas Gregor789adec2011-02-04 13:09:01 +00006866 // Ignore value- or type-dependent expressions.
6867 if (Bitfield->getBitWidth()->isValueDependent() ||
6868 Bitfield->getBitWidth()->isTypeDependent() ||
6869 Init->isValueDependent() ||
6870 Init->isTypeDependent())
6871 return false;
6872
John McCall1f425642010-11-11 03:21:53 +00006873 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6874
Richard Smith5fab0c92011-12-28 19:48:30 +00006875 llvm::APSInt Value;
6876 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006877 return false;
6878
John McCall1f425642010-11-11 03:21:53 +00006879 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006880 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006881
6882 if (OriginalWidth <= FieldWidth)
6883 return false;
6884
Eli Friedmanc267a322012-01-26 23:11:39 +00006885 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006886 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006887 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006888
Eli Friedmanc267a322012-01-26 23:11:39 +00006889 // Check whether the stored value is equal to the original value.
6890 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006891 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006892 return false;
6893
Eli Friedmanc267a322012-01-26 23:11:39 +00006894 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006895 // therefore don't strictly fit into a signed bitfield of width 1.
6896 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006897 return false;
6898
John McCall1f425642010-11-11 03:21:53 +00006899 std::string PrettyValue = Value.toString(10);
6900 std::string PrettyTrunc = TruncatedValue.toString(10);
6901
6902 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6903 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6904 << Init->getSourceRange();
6905
6906 return true;
6907}
6908
John McCalld2a53122010-11-09 23:24:47 +00006909/// Analyze the given simple or compound assignment for warning-worthy
6910/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006911static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006912 // Just recurse on the LHS.
6913 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6914
6915 // We want to recurse on the RHS as normal unless we're assigning to
6916 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006917 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006918 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006919 E->getOperatorLoc())) {
6920 // Recurse, ignoring any implicit conversions on the RHS.
6921 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6922 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006923 }
6924 }
6925
6926 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6927}
6928
John McCall263a48b2010-01-04 23:31:57 +00006929/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006930static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006931 SourceLocation CContext, unsigned diag,
6932 bool pruneControlFlow = false) {
6933 if (pruneControlFlow) {
6934 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6935 S.PDiag(diag)
6936 << SourceType << T << E->getSourceRange()
6937 << SourceRange(CContext));
6938 return;
6939 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006940 S.Diag(E->getExprLoc(), diag)
6941 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6942}
6943
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006944/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006945static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006946 SourceLocation CContext, unsigned diag,
6947 bool pruneControlFlow = false) {
6948 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006949}
6950
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006951/// Diagnose an implicit cast from a literal expression. Does not warn when the
6952/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006953void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6954 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006955 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006956 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006957 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006958 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6959 T->hasUnsignedIntegerRepresentation());
6960 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006961 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006962 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006963 return;
6964
Eli Friedman07185912013-08-29 23:44:43 +00006965 // FIXME: Force the precision of the source value down so we don't print
6966 // digits which are usually useless (we don't really care here if we
6967 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6968 // would automatically print the shortest representation, but it's a bit
6969 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006970 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006971 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6972 precision = (precision * 59 + 195) / 196;
6973 Value.toString(PrettySourceValue, precision);
6974
David Blaikie9b88cc02012-05-15 17:18:27 +00006975 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006976 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6977 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6978 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006979 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006980
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006981 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006982 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6983 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006984}
6985
John McCall18a2c2c2010-11-09 22:22:12 +00006986std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6987 if (!Range.Width) return "0";
6988
6989 llvm::APSInt ValueInRange = Value;
6990 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006991 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006992 return ValueInRange.toString(10);
6993}
6994
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006995static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6996 if (!isa<ImplicitCastExpr>(Ex))
6997 return false;
6998
6999 Expr *InnerE = Ex->IgnoreParenImpCasts();
7000 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7001 const Type *Source =
7002 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7003 if (Target->isDependentType())
7004 return false;
7005
7006 const BuiltinType *FloatCandidateBT =
7007 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7008 const Type *BoolCandidateType = ToBool ? Target : Source;
7009
7010 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7011 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7012}
7013
7014void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7015 SourceLocation CC) {
7016 unsigned NumArgs = TheCall->getNumArgs();
7017 for (unsigned i = 0; i < NumArgs; ++i) {
7018 Expr *CurrA = TheCall->getArg(i);
7019 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7020 continue;
7021
7022 bool IsSwapped = ((i > 0) &&
7023 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7024 IsSwapped |= ((i < (NumArgs - 1)) &&
7025 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7026 if (IsSwapped) {
7027 // Warn on this floating-point to bool conversion.
7028 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7029 CurrA->getType(), CC,
7030 diag::warn_impcast_floating_point_to_bool);
7031 }
7032 }
7033}
7034
Richard Trieu5b993502014-10-15 03:42:06 +00007035static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7036 SourceLocation CC) {
7037 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7038 E->getExprLoc()))
7039 return;
7040
7041 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7042 const Expr::NullPointerConstantKind NullKind =
7043 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7044 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7045 return;
7046
7047 // Return if target type is a safe conversion.
7048 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7049 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7050 return;
7051
7052 SourceLocation Loc = E->getSourceRange().getBegin();
7053
7054 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7055 if (NullKind == Expr::NPCK_GNUNull) {
7056 if (Loc.isMacroID())
7057 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7058 }
7059
7060 // Only warn if the null and context location are in the same macro expansion.
7061 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7062 return;
7063
7064 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7065 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7066 << FixItHint::CreateReplacement(Loc,
7067 S.getFixItZeroLiteralForType(T, Loc));
7068}
7069
Douglas Gregor5054cb02015-07-07 03:58:22 +00007070static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7071 ObjCArrayLiteral *ArrayLiteral);
7072static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7073 ObjCDictionaryLiteral *DictionaryLiteral);
7074
7075/// Check a single element within a collection literal against the
7076/// target element type.
7077static void checkObjCCollectionLiteralElement(Sema &S,
7078 QualType TargetElementType,
7079 Expr *Element,
7080 unsigned ElementKind) {
7081 // Skip a bitcast to 'id' or qualified 'id'.
7082 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7083 if (ICE->getCastKind() == CK_BitCast &&
7084 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7085 Element = ICE->getSubExpr();
7086 }
7087
7088 QualType ElementType = Element->getType();
7089 ExprResult ElementResult(Element);
7090 if (ElementType->getAs<ObjCObjectPointerType>() &&
7091 S.CheckSingleAssignmentConstraints(TargetElementType,
7092 ElementResult,
7093 false, false)
7094 != Sema::Compatible) {
7095 S.Diag(Element->getLocStart(),
7096 diag::warn_objc_collection_literal_element)
7097 << ElementType << ElementKind << TargetElementType
7098 << Element->getSourceRange();
7099 }
7100
7101 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7102 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7103 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7104 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7105}
7106
7107/// Check an Objective-C array literal being converted to the given
7108/// target type.
7109static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7110 ObjCArrayLiteral *ArrayLiteral) {
7111 if (!S.NSArrayDecl)
7112 return;
7113
7114 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7115 if (!TargetObjCPtr)
7116 return;
7117
7118 if (TargetObjCPtr->isUnspecialized() ||
7119 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7120 != S.NSArrayDecl->getCanonicalDecl())
7121 return;
7122
7123 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7124 if (TypeArgs.size() != 1)
7125 return;
7126
7127 QualType TargetElementType = TypeArgs[0];
7128 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7129 checkObjCCollectionLiteralElement(S, TargetElementType,
7130 ArrayLiteral->getElement(I),
7131 0);
7132 }
7133}
7134
7135/// Check an Objective-C dictionary literal being converted to the given
7136/// target type.
7137static void checkObjCDictionaryLiteral(
7138 Sema &S, QualType TargetType,
7139 ObjCDictionaryLiteral *DictionaryLiteral) {
7140 if (!S.NSDictionaryDecl)
7141 return;
7142
7143 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7144 if (!TargetObjCPtr)
7145 return;
7146
7147 if (TargetObjCPtr->isUnspecialized() ||
7148 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7149 != S.NSDictionaryDecl->getCanonicalDecl())
7150 return;
7151
7152 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7153 if (TypeArgs.size() != 2)
7154 return;
7155
7156 QualType TargetKeyType = TypeArgs[0];
7157 QualType TargetObjectType = TypeArgs[1];
7158 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7159 auto Element = DictionaryLiteral->getKeyValueElement(I);
7160 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7161 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7162 }
7163}
7164
John McCallcc7e5bf2010-05-06 08:58:33 +00007165void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007166 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007167 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007168
John McCallcc7e5bf2010-05-06 08:58:33 +00007169 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7170 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7171 if (Source == Target) return;
7172 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007173
Chandler Carruthc22845a2011-07-26 05:40:03 +00007174 // If the conversion context location is invalid don't complain. We also
7175 // don't want to emit a warning if the issue occurs from the expansion of
7176 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7177 // delay this check as long as possible. Once we detect we are in that
7178 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007179 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007180 return;
7181
Richard Trieu021baa32011-09-23 20:10:00 +00007182 // Diagnose implicit casts to bool.
7183 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7184 if (isa<StringLiteral>(E))
7185 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007186 // and expressions, for instance, assert(0 && "error here"), are
7187 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007188 return DiagnoseImpCast(S, E, T, CC,
7189 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007190 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7191 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7192 // This covers the literal expressions that evaluate to Objective-C
7193 // objects.
7194 return DiagnoseImpCast(S, E, T, CC,
7195 diag::warn_impcast_objective_c_literal_to_bool);
7196 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007197 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7198 // Warn on pointer to bool conversion that is always true.
7199 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7200 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007201 }
Richard Trieu021baa32011-09-23 20:10:00 +00007202 }
John McCall263a48b2010-01-04 23:31:57 +00007203
Douglas Gregor5054cb02015-07-07 03:58:22 +00007204 // Check implicit casts from Objective-C collection literals to specialized
7205 // collection types, e.g., NSArray<NSString *> *.
7206 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7207 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7208 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7209 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7210
John McCall263a48b2010-01-04 23:31:57 +00007211 // Strip vector types.
7212 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007213 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007214 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007215 return;
John McCallacf0ee52010-10-08 02:01:28 +00007216 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007217 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007218
7219 // If the vector cast is cast between two vectors of the same size, it is
7220 // a bitcast, not a conversion.
7221 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7222 return;
John McCall263a48b2010-01-04 23:31:57 +00007223
7224 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7225 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7226 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007227 if (auto VecTy = dyn_cast<VectorType>(Target))
7228 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007229
7230 // Strip complex types.
7231 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007232 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007233 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007234 return;
7235
John McCallacf0ee52010-10-08 02:01:28 +00007236 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007237 }
John McCall263a48b2010-01-04 23:31:57 +00007238
7239 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7240 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7241 }
7242
7243 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7244 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7245
7246 // If the source is floating point...
7247 if (SourceBT && SourceBT->isFloatingPoint()) {
7248 // ...and the target is floating point...
7249 if (TargetBT && TargetBT->isFloatingPoint()) {
7250 // ...then warn if we're dropping FP rank.
7251
7252 // Builtin FP kinds are ordered by increasing FP rank.
7253 if (SourceBT->getKind() > TargetBT->getKind()) {
7254 // Don't warn about float constants that are precisely
7255 // representable in the target type.
7256 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007257 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007258 // Value might be a float, a float vector, or a float complex.
7259 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007260 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7261 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007262 return;
7263 }
7264
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007265 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007266 return;
7267
John McCallacf0ee52010-10-08 02:01:28 +00007268 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007269
7270 }
7271 // ... or possibly if we're increasing rank, too
7272 else if (TargetBT->getKind() > SourceBT->getKind()) {
7273 if (S.SourceMgr.isInSystemMacro(CC))
7274 return;
7275
7276 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007277 }
7278 return;
7279 }
7280
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007281 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007282 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007283 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007284 return;
7285
Chandler Carruth22c7a792011-02-17 11:05:49 +00007286 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007287 // We also want to warn on, e.g., "int i = -1.234"
7288 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7289 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7290 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7291
Chandler Carruth016ef402011-04-10 08:36:24 +00007292 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7293 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007294 } else {
7295 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7296 }
7297 }
John McCall263a48b2010-01-04 23:31:57 +00007298
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007299 // If the target is bool, warn if expr is a function or method call.
7300 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7301 isa<CallExpr>(E)) {
7302 // Check last argument of function call to see if it is an
7303 // implicit cast from a type matching the type the result
7304 // is being cast to.
7305 CallExpr *CEx = cast<CallExpr>(E);
7306 unsigned NumArgs = CEx->getNumArgs();
7307 if (NumArgs > 0) {
7308 Expr *LastA = CEx->getArg(NumArgs - 1);
7309 Expr *InnerE = LastA->IgnoreParenImpCasts();
7310 const Type *InnerType =
7311 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7312 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7313 // Warn on this floating-point to bool conversion
7314 DiagnoseImpCast(S, E, T, CC,
7315 diag::warn_impcast_floating_point_to_bool);
7316 }
7317 }
7318 }
John McCall263a48b2010-01-04 23:31:57 +00007319 return;
7320 }
7321
Richard Trieu5b993502014-10-15 03:42:06 +00007322 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007323
David Blaikie9366d2b2012-06-19 21:19:06 +00007324 if (!Source->isIntegerType() || !Target->isIntegerType())
7325 return;
7326
David Blaikie7555b6a2012-05-15 16:56:36 +00007327 // TODO: remove this early return once the false positives for constant->bool
7328 // in templates, macros, etc, are reduced or removed.
7329 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7330 return;
7331
John McCallcc7e5bf2010-05-06 08:58:33 +00007332 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007333 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007334
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007335 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007336 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007337 // TODO: this should happen for bitfield stores, too.
7338 llvm::APSInt Value(32);
7339 if (E->isIntegerConstantExpr(Value, S.Context)) {
7340 if (S.SourceMgr.isInSystemMacro(CC))
7341 return;
7342
John McCall18a2c2c2010-11-09 22:22:12 +00007343 std::string PrettySourceValue = Value.toString(10);
7344 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007345
Ted Kremenek33ba9952011-10-22 02:37:33 +00007346 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7347 S.PDiag(diag::warn_impcast_integer_precision_constant)
7348 << PrettySourceValue << PrettyTargetValue
7349 << E->getType() << T << E->getSourceRange()
7350 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007351 return;
7352 }
7353
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007354 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7355 if (S.SourceMgr.isInSystemMacro(CC))
7356 return;
7357
David Blaikie9455da02012-04-12 22:40:54 +00007358 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007359 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7360 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007361 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007362 }
7363
7364 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7365 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7366 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007367
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007368 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007369 return;
7370
John McCallcc7e5bf2010-05-06 08:58:33 +00007371 unsigned DiagID = diag::warn_impcast_integer_sign;
7372
7373 // Traditionally, gcc has warned about this under -Wsign-compare.
7374 // We also want to warn about it in -Wconversion.
7375 // So if -Wconversion is off, use a completely identical diagnostic
7376 // in the sign-compare group.
7377 // The conditional-checking code will
7378 if (ICContext) {
7379 DiagID = diag::warn_impcast_integer_sign_conditional;
7380 *ICContext = true;
7381 }
7382
John McCallacf0ee52010-10-08 02:01:28 +00007383 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007384 }
7385
Douglas Gregora78f1932011-02-22 02:45:07 +00007386 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007387 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7388 // type, to give us better diagnostics.
7389 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007390 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007391 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7392 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7393 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7394 SourceType = S.Context.getTypeDeclType(Enum);
7395 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7396 }
7397 }
7398
Douglas Gregora78f1932011-02-22 02:45:07 +00007399 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7400 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007401 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7402 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007403 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007404 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007405 return;
7406
Douglas Gregor364f7db2011-03-12 00:14:31 +00007407 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007408 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007409 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007410
John McCall263a48b2010-01-04 23:31:57 +00007411 return;
7412}
7413
David Blaikie18e9ac72012-05-15 21:57:38 +00007414void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7415 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007416
7417void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007418 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007419 E = E->IgnoreParenImpCasts();
7420
7421 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007422 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007423
John McCallacf0ee52010-10-08 02:01:28 +00007424 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007425 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007426 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007427 return;
7428}
7429
David Blaikie18e9ac72012-05-15 21:57:38 +00007430void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7431 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007432 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007433
7434 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007435 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7436 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007437
7438 // If -Wconversion would have warned about either of the candidates
7439 // for a signedness conversion to the context type...
7440 if (!Suspicious) return;
7441
7442 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007443 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007444 return;
7445
John McCallcc7e5bf2010-05-06 08:58:33 +00007446 // ...then check whether it would have warned about either of the
7447 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007448 if (E->getType() == T) return;
7449
7450 Suspicious = false;
7451 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7452 E->getType(), CC, &Suspicious);
7453 if (!Suspicious)
7454 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007455 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007456}
7457
Richard Trieu65724892014-11-15 06:37:39 +00007458/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7459/// Input argument E is a logical expression.
7460static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7461 if (S.getLangOpts().Bool)
7462 return;
7463 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7464}
7465
John McCallcc7e5bf2010-05-06 08:58:33 +00007466/// AnalyzeImplicitConversions - Find and report any interesting
7467/// implicit conversions in the given expression. There are a couple
7468/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007469void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007470 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007471 Expr *E = OrigE->IgnoreParenImpCasts();
7472
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007473 if (E->isTypeDependent() || E->isValueDependent())
7474 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007475
John McCallcc7e5bf2010-05-06 08:58:33 +00007476 // For conditional operators, we analyze the arguments as if they
7477 // were being fed directly into the output.
7478 if (isa<ConditionalOperator>(E)) {
7479 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007480 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007481 return;
7482 }
7483
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007484 // Check implicit argument conversions for function calls.
7485 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7486 CheckImplicitArgumentConversions(S, Call, CC);
7487
John McCallcc7e5bf2010-05-06 08:58:33 +00007488 // Go ahead and check any implicit conversions we might have skipped.
7489 // The non-canonical typecheck is just an optimization;
7490 // CheckImplicitConversion will filter out dead implicit conversions.
7491 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007492 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007493
7494 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007495
7496 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7497 // The bound subexpressions in a PseudoObjectExpr are not reachable
7498 // as transitive children.
7499 // FIXME: Use a more uniform representation for this.
7500 for (auto *SE : POE->semantics())
7501 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7502 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007503 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007504
John McCallcc7e5bf2010-05-06 08:58:33 +00007505 // Skip past explicit casts.
7506 if (isa<ExplicitCastExpr>(E)) {
7507 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007508 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007509 }
7510
John McCalld2a53122010-11-09 23:24:47 +00007511 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7512 // Do a somewhat different check with comparison operators.
7513 if (BO->isComparisonOp())
7514 return AnalyzeComparison(S, BO);
7515
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007516 // And with simple assignments.
7517 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007518 return AnalyzeAssignment(S, BO);
7519 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007520
7521 // These break the otherwise-useful invariant below. Fortunately,
7522 // we don't really need to recurse into them, because any internal
7523 // expressions should have been analyzed already when they were
7524 // built into statements.
7525 if (isa<StmtExpr>(E)) return;
7526
7527 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007528 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007529
7530 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007531 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007532 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007533 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007534 for (Stmt *SubStmt : E->children()) {
7535 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007536 if (!ChildExpr)
7537 continue;
7538
Richard Trieu955231d2014-01-25 01:10:35 +00007539 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007540 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007541 // Ignore checking string literals that are in logical and operators.
7542 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007543 continue;
7544 AnalyzeImplicitConversions(S, ChildExpr, CC);
7545 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007546
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007547 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007548 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7549 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007550 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007551
7552 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7553 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007554 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007555 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007556
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007557 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7558 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007559 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007560}
7561
7562} // end anonymous namespace
7563
Richard Trieu3bb8b562014-02-26 02:36:06 +00007564enum {
7565 AddressOf,
7566 FunctionPointer,
7567 ArrayPointer
7568};
7569
Richard Trieuc1888e02014-06-28 23:25:37 +00007570// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7571// Returns true when emitting a warning about taking the address of a reference.
7572static bool CheckForReference(Sema &SemaRef, const Expr *E,
7573 PartialDiagnostic PD) {
7574 E = E->IgnoreParenImpCasts();
7575
7576 const FunctionDecl *FD = nullptr;
7577
7578 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7579 if (!DRE->getDecl()->getType()->isReferenceType())
7580 return false;
7581 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7582 if (!M->getMemberDecl()->getType()->isReferenceType())
7583 return false;
7584 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007585 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007586 return false;
7587 FD = Call->getDirectCallee();
7588 } else {
7589 return false;
7590 }
7591
7592 SemaRef.Diag(E->getExprLoc(), PD);
7593
7594 // If possible, point to location of function.
7595 if (FD) {
7596 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7597 }
7598
7599 return true;
7600}
7601
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007602// Returns true if the SourceLocation is expanded from any macro body.
7603// Returns false if the SourceLocation is invalid, is from not in a macro
7604// expansion, or is from expanded from a top-level macro argument.
7605static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7606 if (Loc.isInvalid())
7607 return false;
7608
7609 while (Loc.isMacroID()) {
7610 if (SM.isMacroBodyExpansion(Loc))
7611 return true;
7612 Loc = SM.getImmediateMacroCallerLoc(Loc);
7613 }
7614
7615 return false;
7616}
7617
Richard Trieu3bb8b562014-02-26 02:36:06 +00007618/// \brief Diagnose pointers that are always non-null.
7619/// \param E the expression containing the pointer
7620/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7621/// compared to a null pointer
7622/// \param IsEqual True when the comparison is equal to a null pointer
7623/// \param Range Extra SourceRange to highlight in the diagnostic
7624void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7625 Expr::NullPointerConstantKind NullKind,
7626 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007627 if (!E)
7628 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007629
7630 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007631 if (E->getExprLoc().isMacroID()) {
7632 const SourceManager &SM = getSourceManager();
7633 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7634 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007635 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007636 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007637 E = E->IgnoreImpCasts();
7638
7639 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7640
Richard Trieuf7432752014-06-06 21:39:26 +00007641 if (isa<CXXThisExpr>(E)) {
7642 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7643 : diag::warn_this_bool_conversion;
7644 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7645 return;
7646 }
7647
Richard Trieu3bb8b562014-02-26 02:36:06 +00007648 bool IsAddressOf = false;
7649
7650 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7651 if (UO->getOpcode() != UO_AddrOf)
7652 return;
7653 IsAddressOf = true;
7654 E = UO->getSubExpr();
7655 }
7656
Richard Trieuc1888e02014-06-28 23:25:37 +00007657 if (IsAddressOf) {
7658 unsigned DiagID = IsCompare
7659 ? diag::warn_address_of_reference_null_compare
7660 : diag::warn_address_of_reference_bool_conversion;
7661 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7662 << IsEqual;
7663 if (CheckForReference(*this, E, PD)) {
7664 return;
7665 }
7666 }
7667
George Burgess IV850269a2015-12-08 22:02:00 +00007668 auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
7669 std::string Str;
7670 llvm::raw_string_ostream S(Str);
7671 E->printPretty(S, nullptr, getPrintingPolicy());
7672 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7673 : diag::warn_cast_nonnull_to_bool;
7674 Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
7675 << E->getSourceRange() << Range << IsEqual;
7676 };
7677
7678 // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
7679 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
7680 if (auto *Callee = Call->getDirectCallee()) {
7681 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7682 ComplainAboutNonnullParamOrCall(false);
7683 return;
7684 }
7685 }
7686 }
7687
Richard Trieu3bb8b562014-02-26 02:36:06 +00007688 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007689 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007690 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7691 D = R->getDecl();
7692 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7693 D = M->getMemberDecl();
7694 }
7695
7696 // Weak Decls can be null.
7697 if (!D || D->isWeak())
7698 return;
George Burgess IV850269a2015-12-08 22:02:00 +00007699
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007700 // Check for parameter decl with nonnull attribute
George Burgess IV850269a2015-12-08 22:02:00 +00007701 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7702 if (getCurFunction() &&
7703 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7704 if (PV->hasAttr<NonNullAttr>()) {
7705 ComplainAboutNonnullParamOrCall(true);
7706 return;
7707 }
7708
7709 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7710 auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
7711 assert(ParamIter != FD->param_end());
7712 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
7713
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007714 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7715 if (!NonNull->args_size()) {
George Burgess IV850269a2015-12-08 22:02:00 +00007716 ComplainAboutNonnullParamOrCall(true);
7717 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007718 }
George Burgess IV850269a2015-12-08 22:02:00 +00007719
7720 for (unsigned ArgNo : NonNull->args()) {
7721 if (ArgNo == ParamNo) {
7722 ComplainAboutNonnullParamOrCall(true);
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007723 return;
7724 }
George Burgess IV850269a2015-12-08 22:02:00 +00007725 }
7726 }
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007727 }
7728 }
George Burgess IV850269a2015-12-08 22:02:00 +00007729 }
7730
Richard Trieu3bb8b562014-02-26 02:36:06 +00007731 QualType T = D->getType();
7732 const bool IsArray = T->isArrayType();
7733 const bool IsFunction = T->isFunctionType();
7734
Richard Trieuc1888e02014-06-28 23:25:37 +00007735 // Address of function is used to silence the function warning.
7736 if (IsAddressOf && IsFunction) {
7737 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007738 }
7739
7740 // Found nothing.
7741 if (!IsAddressOf && !IsFunction && !IsArray)
7742 return;
7743
7744 // Pretty print the expression for the diagnostic.
7745 std::string Str;
7746 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007747 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007748
7749 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7750 : diag::warn_impcast_pointer_to_bool;
7751 unsigned DiagType;
7752 if (IsAddressOf)
7753 DiagType = AddressOf;
7754 else if (IsFunction)
7755 DiagType = FunctionPointer;
7756 else if (IsArray)
7757 DiagType = ArrayPointer;
7758 else
7759 llvm_unreachable("Could not determine diagnostic.");
7760 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7761 << Range << IsEqual;
7762
7763 if (!IsFunction)
7764 return;
7765
7766 // Suggest '&' to silence the function warning.
7767 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7768 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7769
7770 // Check to see if '()' fixit should be emitted.
7771 QualType ReturnType;
7772 UnresolvedSet<4> NonTemplateOverloads;
7773 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7774 if (ReturnType.isNull())
7775 return;
7776
7777 if (IsCompare) {
7778 // There are two cases here. If there is null constant, the only suggest
7779 // for a pointer return type. If the null is 0, then suggest if the return
7780 // type is a pointer or an integer type.
7781 if (!ReturnType->isPointerType()) {
7782 if (NullKind == Expr::NPCK_ZeroExpression ||
7783 NullKind == Expr::NPCK_ZeroLiteral) {
7784 if (!ReturnType->isIntegerType())
7785 return;
7786 } else {
7787 return;
7788 }
7789 }
7790 } else { // !IsCompare
7791 // For function to bool, only suggest if the function pointer has bool
7792 // return type.
7793 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7794 return;
7795 }
7796 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007797 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007798}
7799
7800
John McCallcc7e5bf2010-05-06 08:58:33 +00007801/// Diagnoses "dangerous" implicit conversions within the given
7802/// expression (which is a full expression). Implements -Wconversion
7803/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007804///
7805/// \param CC the "context" location of the implicit conversion, i.e.
7806/// the most location of the syntactic entity requiring the implicit
7807/// conversion
7808void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007809 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007810 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007811 return;
7812
7813 // Don't diagnose for value- or type-dependent expressions.
7814 if (E->isTypeDependent() || E->isValueDependent())
7815 return;
7816
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007817 // Check for array bounds violations in cases where the check isn't triggered
7818 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7819 // ArraySubscriptExpr is on the RHS of a variable initialization.
7820 CheckArrayAccess(E);
7821
John McCallacf0ee52010-10-08 02:01:28 +00007822 // This is not the right CC for (e.g.) a variable initialization.
7823 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007824}
7825
Richard Trieu65724892014-11-15 06:37:39 +00007826/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7827/// Input argument E is a logical expression.
7828void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7829 ::CheckBoolLikeConversion(*this, E, CC);
7830}
7831
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007832/// Diagnose when expression is an integer constant expression and its evaluation
7833/// results in integer overflow
7834void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007835 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7836 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007837}
7838
Richard Smithc406cb72013-01-17 01:17:56 +00007839namespace {
7840/// \brief Visitor for expressions which looks for unsequenced operations on the
7841/// same object.
7842class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007843 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7844
Richard Smithc406cb72013-01-17 01:17:56 +00007845 /// \brief A tree of sequenced regions within an expression. Two regions are
7846 /// unsequenced if one is an ancestor or a descendent of the other. When we
7847 /// finish processing an expression with sequencing, such as a comma
7848 /// expression, we fold its tree nodes into its parent, since they are
7849 /// unsequenced with respect to nodes we will visit later.
7850 class SequenceTree {
7851 struct Value {
7852 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7853 unsigned Parent : 31;
7854 bool Merged : 1;
7855 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007856 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007857
7858 public:
7859 /// \brief A region within an expression which may be sequenced with respect
7860 /// to some other region.
7861 class Seq {
7862 explicit Seq(unsigned N) : Index(N) {}
7863 unsigned Index;
7864 friend class SequenceTree;
7865 public:
7866 Seq() : Index(0) {}
7867 };
7868
7869 SequenceTree() { Values.push_back(Value(0)); }
7870 Seq root() const { return Seq(0); }
7871
7872 /// \brief Create a new sequence of operations, which is an unsequenced
7873 /// subset of \p Parent. This sequence of operations is sequenced with
7874 /// respect to other children of \p Parent.
7875 Seq allocate(Seq Parent) {
7876 Values.push_back(Value(Parent.Index));
7877 return Seq(Values.size() - 1);
7878 }
7879
7880 /// \brief Merge a sequence of operations into its parent.
7881 void merge(Seq S) {
7882 Values[S.Index].Merged = true;
7883 }
7884
7885 /// \brief Determine whether two operations are unsequenced. This operation
7886 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7887 /// should have been merged into its parent as appropriate.
7888 bool isUnsequenced(Seq Cur, Seq Old) {
7889 unsigned C = representative(Cur.Index);
7890 unsigned Target = representative(Old.Index);
7891 while (C >= Target) {
7892 if (C == Target)
7893 return true;
7894 C = Values[C].Parent;
7895 }
7896 return false;
7897 }
7898
7899 private:
7900 /// \brief Pick a representative for a sequence.
7901 unsigned representative(unsigned K) {
7902 if (Values[K].Merged)
7903 // Perform path compression as we go.
7904 return Values[K].Parent = representative(Values[K].Parent);
7905 return K;
7906 }
7907 };
7908
7909 /// An object for which we can track unsequenced uses.
7910 typedef NamedDecl *Object;
7911
7912 /// Different flavors of object usage which we track. We only track the
7913 /// least-sequenced usage of each kind.
7914 enum UsageKind {
7915 /// A read of an object. Multiple unsequenced reads are OK.
7916 UK_Use,
7917 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007918 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007919 UK_ModAsValue,
7920 /// A modification of an object which is not sequenced before the value
7921 /// computation of the expression, such as n++.
7922 UK_ModAsSideEffect,
7923
7924 UK_Count = UK_ModAsSideEffect + 1
7925 };
7926
7927 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007928 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007929 Expr *Use;
7930 SequenceTree::Seq Seq;
7931 };
7932
7933 struct UsageInfo {
7934 UsageInfo() : Diagnosed(false) {}
7935 Usage Uses[UK_Count];
7936 /// Have we issued a diagnostic for this variable already?
7937 bool Diagnosed;
7938 };
7939 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7940
7941 Sema &SemaRef;
7942 /// Sequenced regions within the expression.
7943 SequenceTree Tree;
7944 /// Declaration modifications and references which we have seen.
7945 UsageInfoMap UsageMap;
7946 /// The region we are currently within.
7947 SequenceTree::Seq Region;
7948 /// Filled in with declarations which were modified as a side-effect
7949 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007950 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007951 /// Expressions to check later. We defer checking these to reduce
7952 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007953 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007954
7955 /// RAII object wrapping the visitation of a sequenced subexpression of an
7956 /// expression. At the end of this process, the side-effects of the evaluation
7957 /// become sequenced with respect to the value computation of the result, so
7958 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7959 /// UK_ModAsValue.
7960 struct SequencedSubexpression {
7961 SequencedSubexpression(SequenceChecker &Self)
7962 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7963 Self.ModAsSideEffect = &ModAsSideEffect;
7964 }
7965 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007966 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7967 MI != ME; ++MI) {
7968 UsageInfo &U = Self.UsageMap[MI->first];
7969 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7970 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7971 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007972 }
7973 Self.ModAsSideEffect = OldModAsSideEffect;
7974 }
7975
7976 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007977 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7978 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007979 };
7980
Richard Smith40238f02013-06-20 22:21:56 +00007981 /// RAII object wrapping the visitation of a subexpression which we might
7982 /// choose to evaluate as a constant. If any subexpression is evaluated and
7983 /// found to be non-constant, this allows us to suppress the evaluation of
7984 /// the outer expression.
7985 class EvaluationTracker {
7986 public:
7987 EvaluationTracker(SequenceChecker &Self)
7988 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7989 Self.EvalTracker = this;
7990 }
7991 ~EvaluationTracker() {
7992 Self.EvalTracker = Prev;
7993 if (Prev)
7994 Prev->EvalOK &= EvalOK;
7995 }
7996
7997 bool evaluate(const Expr *E, bool &Result) {
7998 if (!EvalOK || E->isValueDependent())
7999 return false;
8000 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8001 return EvalOK;
8002 }
8003
8004 private:
8005 SequenceChecker &Self;
8006 EvaluationTracker *Prev;
8007 bool EvalOK;
8008 } *EvalTracker;
8009
Richard Smithc406cb72013-01-17 01:17:56 +00008010 /// \brief Find the object which is produced by the specified expression,
8011 /// if any.
8012 Object getObject(Expr *E, bool Mod) const {
8013 E = E->IgnoreParenCasts();
8014 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8015 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8016 return getObject(UO->getSubExpr(), Mod);
8017 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8018 if (BO->getOpcode() == BO_Comma)
8019 return getObject(BO->getRHS(), Mod);
8020 if (Mod && BO->isAssignmentOp())
8021 return getObject(BO->getLHS(), Mod);
8022 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8023 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8024 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8025 return ME->getMemberDecl();
8026 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8027 // FIXME: If this is a reference, map through to its value.
8028 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008029 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008030 }
8031
8032 /// \brief Note that an object was modified or used by an expression.
8033 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8034 Usage &U = UI.Uses[UK];
8035 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8036 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8037 ModAsSideEffect->push_back(std::make_pair(O, U));
8038 U.Use = Ref;
8039 U.Seq = Region;
8040 }
8041 }
8042 /// \brief Check whether a modification or use conflicts with a prior usage.
8043 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8044 bool IsModMod) {
8045 if (UI.Diagnosed)
8046 return;
8047
8048 const Usage &U = UI.Uses[OtherKind];
8049 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8050 return;
8051
8052 Expr *Mod = U.Use;
8053 Expr *ModOrUse = Ref;
8054 if (OtherKind == UK_Use)
8055 std::swap(Mod, ModOrUse);
8056
8057 SemaRef.Diag(Mod->getExprLoc(),
8058 IsModMod ? diag::warn_unsequenced_mod_mod
8059 : diag::warn_unsequenced_mod_use)
8060 << O << SourceRange(ModOrUse->getExprLoc());
8061 UI.Diagnosed = true;
8062 }
8063
8064 void notePreUse(Object O, Expr *Use) {
8065 UsageInfo &U = UsageMap[O];
8066 // Uses conflict with other modifications.
8067 checkUsage(O, U, Use, UK_ModAsValue, false);
8068 }
8069 void notePostUse(Object O, Expr *Use) {
8070 UsageInfo &U = UsageMap[O];
8071 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8072 addUsage(U, O, Use, UK_Use);
8073 }
8074
8075 void notePreMod(Object O, Expr *Mod) {
8076 UsageInfo &U = UsageMap[O];
8077 // Modifications conflict with other modifications and with uses.
8078 checkUsage(O, U, Mod, UK_ModAsValue, true);
8079 checkUsage(O, U, Mod, UK_Use, false);
8080 }
8081 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8082 UsageInfo &U = UsageMap[O];
8083 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8084 addUsage(U, O, Use, UK);
8085 }
8086
8087public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008088 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008089 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8090 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008091 Visit(E);
8092 }
8093
8094 void VisitStmt(Stmt *S) {
8095 // Skip all statements which aren't expressions for now.
8096 }
8097
8098 void VisitExpr(Expr *E) {
8099 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008100 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008101 }
8102
8103 void VisitCastExpr(CastExpr *E) {
8104 Object O = Object();
8105 if (E->getCastKind() == CK_LValueToRValue)
8106 O = getObject(E->getSubExpr(), false);
8107
8108 if (O)
8109 notePreUse(O, E);
8110 VisitExpr(E);
8111 if (O)
8112 notePostUse(O, E);
8113 }
8114
8115 void VisitBinComma(BinaryOperator *BO) {
8116 // C++11 [expr.comma]p1:
8117 // Every value computation and side effect associated with the left
8118 // expression is sequenced before every value computation and side
8119 // effect associated with the right expression.
8120 SequenceTree::Seq LHS = Tree.allocate(Region);
8121 SequenceTree::Seq RHS = Tree.allocate(Region);
8122 SequenceTree::Seq OldRegion = Region;
8123
8124 {
8125 SequencedSubexpression SeqLHS(*this);
8126 Region = LHS;
8127 Visit(BO->getLHS());
8128 }
8129
8130 Region = RHS;
8131 Visit(BO->getRHS());
8132
8133 Region = OldRegion;
8134
8135 // Forget that LHS and RHS are sequenced. They are both unsequenced
8136 // with respect to other stuff.
8137 Tree.merge(LHS);
8138 Tree.merge(RHS);
8139 }
8140
8141 void VisitBinAssign(BinaryOperator *BO) {
8142 // The modification is sequenced after the value computation of the LHS
8143 // and RHS, so check it before inspecting the operands and update the
8144 // map afterwards.
8145 Object O = getObject(BO->getLHS(), true);
8146 if (!O)
8147 return VisitExpr(BO);
8148
8149 notePreMod(O, BO);
8150
8151 // C++11 [expr.ass]p7:
8152 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8153 // only once.
8154 //
8155 // Therefore, for a compound assignment operator, O is considered used
8156 // everywhere except within the evaluation of E1 itself.
8157 if (isa<CompoundAssignOperator>(BO))
8158 notePreUse(O, BO);
8159
8160 Visit(BO->getLHS());
8161
8162 if (isa<CompoundAssignOperator>(BO))
8163 notePostUse(O, BO);
8164
8165 Visit(BO->getRHS());
8166
Richard Smith83e37bee2013-06-26 23:16:51 +00008167 // C++11 [expr.ass]p1:
8168 // the assignment is sequenced [...] before the value computation of the
8169 // assignment expression.
8170 // C11 6.5.16/3 has no such rule.
8171 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8172 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008173 }
8174 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8175 VisitBinAssign(CAO);
8176 }
8177
8178 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8179 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8180 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8181 Object O = getObject(UO->getSubExpr(), true);
8182 if (!O)
8183 return VisitExpr(UO);
8184
8185 notePreMod(O, UO);
8186 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008187 // C++11 [expr.pre.incr]p1:
8188 // the expression ++x is equivalent to x+=1
8189 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8190 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008191 }
8192
8193 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8194 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8195 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8196 Object O = getObject(UO->getSubExpr(), true);
8197 if (!O)
8198 return VisitExpr(UO);
8199
8200 notePreMod(O, UO);
8201 Visit(UO->getSubExpr());
8202 notePostMod(O, UO, UK_ModAsSideEffect);
8203 }
8204
8205 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8206 void VisitBinLOr(BinaryOperator *BO) {
8207 // The side-effects of the LHS of an '&&' are sequenced before the
8208 // value computation of the RHS, and hence before the value computation
8209 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8210 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008211 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008212 {
8213 SequencedSubexpression Sequenced(*this);
8214 Visit(BO->getLHS());
8215 }
8216
8217 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008218 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008219 if (!Result)
8220 Visit(BO->getRHS());
8221 } else {
8222 // Check for unsequenced operations in the RHS, treating it as an
8223 // entirely separate evaluation.
8224 //
8225 // FIXME: If there are operations in the RHS which are unsequenced
8226 // with respect to operations outside the RHS, and those operations
8227 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008228 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008229 }
Richard Smithc406cb72013-01-17 01:17:56 +00008230 }
8231 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008232 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008233 {
8234 SequencedSubexpression Sequenced(*this);
8235 Visit(BO->getLHS());
8236 }
8237
8238 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008239 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008240 if (Result)
8241 Visit(BO->getRHS());
8242 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008243 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008244 }
Richard Smithc406cb72013-01-17 01:17:56 +00008245 }
8246
8247 // Only visit the condition, unless we can be sure which subexpression will
8248 // be chosen.
8249 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008250 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008251 {
8252 SequencedSubexpression Sequenced(*this);
8253 Visit(CO->getCond());
8254 }
Richard Smithc406cb72013-01-17 01:17:56 +00008255
8256 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008257 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008258 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008259 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008260 WorkList.push_back(CO->getTrueExpr());
8261 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008262 }
Richard Smithc406cb72013-01-17 01:17:56 +00008263 }
8264
Richard Smithe3dbfe02013-06-30 10:40:20 +00008265 void VisitCallExpr(CallExpr *CE) {
8266 // C++11 [intro.execution]p15:
8267 // When calling a function [...], every value computation and side effect
8268 // associated with any argument expression, or with the postfix expression
8269 // designating the called function, is sequenced before execution of every
8270 // expression or statement in the body of the function [and thus before
8271 // the value computation of its result].
8272 SequencedSubexpression Sequenced(*this);
8273 Base::VisitCallExpr(CE);
8274
8275 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8276 }
8277
Richard Smithc406cb72013-01-17 01:17:56 +00008278 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008279 // This is a call, so all subexpressions are sequenced before the result.
8280 SequencedSubexpression Sequenced(*this);
8281
Richard Smithc406cb72013-01-17 01:17:56 +00008282 if (!CCE->isListInitialization())
8283 return VisitExpr(CCE);
8284
8285 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008286 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008287 SequenceTree::Seq Parent = Region;
8288 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8289 E = CCE->arg_end();
8290 I != E; ++I) {
8291 Region = Tree.allocate(Parent);
8292 Elts.push_back(Region);
8293 Visit(*I);
8294 }
8295
8296 // Forget that the initializers are sequenced.
8297 Region = Parent;
8298 for (unsigned I = 0; I < Elts.size(); ++I)
8299 Tree.merge(Elts[I]);
8300 }
8301
8302 void VisitInitListExpr(InitListExpr *ILE) {
8303 if (!SemaRef.getLangOpts().CPlusPlus11)
8304 return VisitExpr(ILE);
8305
8306 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008307 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008308 SequenceTree::Seq Parent = Region;
8309 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8310 Expr *E = ILE->getInit(I);
8311 if (!E) continue;
8312 Region = Tree.allocate(Parent);
8313 Elts.push_back(Region);
8314 Visit(E);
8315 }
8316
8317 // Forget that the initializers are sequenced.
8318 Region = Parent;
8319 for (unsigned I = 0; I < Elts.size(); ++I)
8320 Tree.merge(Elts[I]);
8321 }
8322};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008323}
Richard Smithc406cb72013-01-17 01:17:56 +00008324
8325void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008326 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008327 WorkList.push_back(E);
8328 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008329 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008330 SequenceChecker(*this, Item, WorkList);
8331 }
Richard Smithc406cb72013-01-17 01:17:56 +00008332}
8333
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008334void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8335 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008336 CheckImplicitConversions(E, CheckLoc);
8337 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008338 if (!IsConstexpr && !E->isValueDependent())
8339 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008340}
8341
John McCall1f425642010-11-11 03:21:53 +00008342void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8343 FieldDecl *BitField,
8344 Expr *Init) {
8345 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8346}
8347
David Majnemer61a5bbf2015-04-07 22:08:51 +00008348static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8349 SourceLocation Loc) {
8350 if (!PType->isVariablyModifiedType())
8351 return;
8352 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8353 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8354 return;
8355 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008356 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8357 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8358 return;
8359 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008360 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8361 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8362 return;
8363 }
8364
8365 const ArrayType *AT = S.Context.getAsArrayType(PType);
8366 if (!AT)
8367 return;
8368
8369 if (AT->getSizeModifier() != ArrayType::Star) {
8370 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8371 return;
8372 }
8373
8374 S.Diag(Loc, diag::err_array_star_in_function_definition);
8375}
8376
Mike Stump0c2ec772010-01-21 03:59:47 +00008377/// CheckParmsForFunctionDef - Check that the parameters of the given
8378/// function are appropriate for the definition of a function. This
8379/// takes care of any checks that cannot be performed on the
8380/// declaration itself, e.g., that the types of each of the function
8381/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008382bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8383 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008384 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008385 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008386 for (; P != PEnd; ++P) {
8387 ParmVarDecl *Param = *P;
8388
Mike Stump0c2ec772010-01-21 03:59:47 +00008389 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8390 // function declarator that is part of a function definition of
8391 // that function shall not have incomplete type.
8392 //
8393 // This is also C++ [dcl.fct]p6.
8394 if (!Param->isInvalidDecl() &&
8395 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008396 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008397 Param->setInvalidDecl();
8398 HasInvalidParm = true;
8399 }
8400
8401 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8402 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008403 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008404 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008405 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008406 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008407 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008408
8409 // C99 6.7.5.3p12:
8410 // If the function declarator is not part of a definition of that
8411 // function, parameters may have incomplete type and may use the [*]
8412 // notation in their sequences of declarator specifiers to specify
8413 // variable length array types.
8414 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008415 // FIXME: This diagnostic should point the '[*]' if source-location
8416 // information is added for it.
8417 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008418
8419 // MSVC destroys objects passed by value in the callee. Therefore a
8420 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008421 // object's destructor. However, we don't perform any direct access check
8422 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008423 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8424 .getCXXABI()
8425 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008426 if (!Param->isInvalidDecl()) {
8427 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8428 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8429 if (!ClassDecl->isInvalidDecl() &&
8430 !ClassDecl->hasIrrelevantDestructor() &&
8431 !ClassDecl->isDependentContext()) {
8432 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8433 MarkFunctionReferenced(Param->getLocation(), Destructor);
8434 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8435 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008436 }
8437 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008438 }
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00008439
8440 // Parameters with the pass_object_size attribute only need to be marked
8441 // constant at function definitions. Because we lack information about
8442 // whether we're on a declaration or definition when we're instantiating the
8443 // attribute, we need to check for constness here.
8444 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
8445 if (!Param->getType().isConstQualified())
8446 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
8447 << Attr->getSpelling() << 1;
Mike Stump0c2ec772010-01-21 03:59:47 +00008448 }
8449
8450 return HasInvalidParm;
8451}
John McCall2b5c1b22010-08-12 21:44:57 +00008452
8453/// CheckCastAlign - Implements -Wcast-align, which warns when a
8454/// pointer cast increases the alignment requirements.
8455void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8456 // This is actually a lot of work to potentially be doing on every
8457 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008458 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008459 return;
8460
8461 // Ignore dependent types.
8462 if (T->isDependentType() || Op->getType()->isDependentType())
8463 return;
8464
8465 // Require that the destination be a pointer type.
8466 const PointerType *DestPtr = T->getAs<PointerType>();
8467 if (!DestPtr) return;
8468
8469 // If the destination has alignment 1, we're done.
8470 QualType DestPointee = DestPtr->getPointeeType();
8471 if (DestPointee->isIncompleteType()) return;
8472 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8473 if (DestAlign.isOne()) return;
8474
8475 // Require that the source be a pointer type.
8476 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8477 if (!SrcPtr) return;
8478 QualType SrcPointee = SrcPtr->getPointeeType();
8479
8480 // Whitelist casts from cv void*. We already implicitly
8481 // whitelisted casts to cv void*, since they have alignment 1.
8482 // Also whitelist casts involving incomplete types, which implicitly
8483 // includes 'void'.
8484 if (SrcPointee->isIncompleteType()) return;
8485
8486 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8487 if (SrcAlign >= DestAlign) return;
8488
8489 Diag(TRange.getBegin(), diag::warn_cast_align)
8490 << Op->getType() << T
8491 << static_cast<unsigned>(SrcAlign.getQuantity())
8492 << static_cast<unsigned>(DestAlign.getQuantity())
8493 << TRange << Op->getSourceRange();
8494}
8495
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008496static const Type* getElementType(const Expr *BaseExpr) {
8497 const Type* EltType = BaseExpr->getType().getTypePtr();
8498 if (EltType->isAnyPointerType())
8499 return EltType->getPointeeType().getTypePtr();
8500 else if (EltType->isArrayType())
8501 return EltType->getBaseElementTypeUnsafe();
8502 return EltType;
8503}
8504
Chandler Carruth28389f02011-08-05 09:10:50 +00008505/// \brief Check whether this array fits the idiom of a size-one tail padded
8506/// array member of a struct.
8507///
8508/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8509/// commonly used to emulate flexible arrays in C89 code.
8510static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8511 const NamedDecl *ND) {
8512 if (Size != 1 || !ND) return false;
8513
8514 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8515 if (!FD) return false;
8516
8517 // Don't consider sizes resulting from macro expansions or template argument
8518 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008519
8520 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008521 while (TInfo) {
8522 TypeLoc TL = TInfo->getTypeLoc();
8523 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008524 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8525 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008526 TInfo = TDL->getTypeSourceInfo();
8527 continue;
8528 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008529 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8530 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008531 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8532 return false;
8533 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008534 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008535 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008536
8537 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008538 if (!RD) return false;
8539 if (RD->isUnion()) return false;
8540 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8541 if (!CRD->isStandardLayout()) return false;
8542 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008543
Benjamin Kramer8c543672011-08-06 03:04:42 +00008544 // See if this is the last field decl in the record.
8545 const Decl *D = FD;
8546 while ((D = D->getNextDeclInContext()))
8547 if (isa<FieldDecl>(D))
8548 return false;
8549 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008550}
8551
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008552void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008553 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008554 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008555 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008556 if (IndexExpr->isValueDependent())
8557 return;
8558
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008559 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008560 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008561 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008562 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008563 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008564 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008565
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008566 llvm::APSInt index;
Richard Smith0c6124b2015-12-03 01:36:22 +00008567 if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
Ted Kremenek64699be2011-02-16 01:57:07 +00008568 return;
Richard Smith13f67182011-12-16 19:31:14 +00008569 if (IndexNegated)
8570 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008571
Craig Topperc3ec1492014-05-26 06:22:03 +00008572 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008573 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8574 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008575 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008576 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008577
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008578 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008579 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008580 if (!size.isStrictlyPositive())
8581 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008582
8583 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008584 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008585 // Make sure we're comparing apples to apples when comparing index to size
8586 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8587 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008588 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008589 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008590 if (ptrarith_typesize != array_typesize) {
8591 // There's a cast to a different size type involved
8592 uint64_t ratio = array_typesize / ptrarith_typesize;
8593 // TODO: Be smarter about handling cases where array_typesize is not a
8594 // multiple of ptrarith_typesize
8595 if (ptrarith_typesize * ratio == array_typesize)
8596 size *= llvm::APInt(size.getBitWidth(), ratio);
8597 }
8598 }
8599
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008600 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008601 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008602 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008603 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008604
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008605 // For array subscripting the index must be less than size, but for pointer
8606 // arithmetic also allow the index (offset) to be equal to size since
8607 // computing the next address after the end of the array is legal and
8608 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008609 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008610 return;
8611
8612 // Also don't warn for arrays of size 1 which are members of some
8613 // structure. These are often used to approximate flexible arrays in C89
8614 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008615 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008616 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008617
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008618 // Suppress the warning if the subscript expression (as identified by the
8619 // ']' location) and the index expression are both from macro expansions
8620 // within a system header.
8621 if (ASE) {
8622 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8623 ASE->getRBracketLoc());
8624 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8625 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8626 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008627 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008628 return;
8629 }
8630 }
8631
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008632 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008633 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008634 DiagID = diag::warn_array_index_exceeds_bounds;
8635
8636 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8637 PDiag(DiagID) << index.toString(10, true)
8638 << size.toString(10, true)
8639 << (unsigned)size.getLimitedValue(~0U)
8640 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008641 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008642 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008643 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008644 DiagID = diag::warn_ptr_arith_precedes_bounds;
8645 if (index.isNegative()) index = -index;
8646 }
8647
8648 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8649 PDiag(DiagID) << index.toString(10, true)
8650 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008651 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008652
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008653 if (!ND) {
8654 // Try harder to find a NamedDecl to point at in the note.
8655 while (const ArraySubscriptExpr *ASE =
8656 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8657 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8658 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8659 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8660 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8661 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8662 }
8663
Chandler Carruth1af88f12011-02-17 21:10:52 +00008664 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008665 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8666 PDiag(diag::note_array_index_out_of_bounds)
8667 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008668}
8669
Ted Kremenekdf26df72011-03-01 18:41:00 +00008670void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008671 int AllowOnePastEnd = 0;
8672 while (expr) {
8673 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008674 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008675 case Stmt::ArraySubscriptExprClass: {
8676 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008677 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008678 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008679 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008680 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008681 case Stmt::OMPArraySectionExprClass: {
8682 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8683 if (ASE->getLowerBound())
8684 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8685 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8686 return;
8687 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008688 case Stmt::UnaryOperatorClass: {
8689 // Only unwrap the * and & unary operators
8690 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8691 expr = UO->getSubExpr();
8692 switch (UO->getOpcode()) {
8693 case UO_AddrOf:
8694 AllowOnePastEnd++;
8695 break;
8696 case UO_Deref:
8697 AllowOnePastEnd--;
8698 break;
8699 default:
8700 return;
8701 }
8702 break;
8703 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008704 case Stmt::ConditionalOperatorClass: {
8705 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8706 if (const Expr *lhs = cond->getLHS())
8707 CheckArrayAccess(lhs);
8708 if (const Expr *rhs = cond->getRHS())
8709 CheckArrayAccess(rhs);
8710 return;
8711 }
8712 default:
8713 return;
8714 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008715 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008716}
John McCall31168b02011-06-15 23:02:42 +00008717
8718//===--- CHECK: Objective-C retain cycles ----------------------------------//
8719
8720namespace {
8721 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008722 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008723 VarDecl *Variable;
8724 SourceRange Range;
8725 SourceLocation Loc;
8726 bool Indirect;
8727
8728 void setLocsFrom(Expr *e) {
8729 Loc = e->getExprLoc();
8730 Range = e->getSourceRange();
8731 }
8732 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008733}
John McCall31168b02011-06-15 23:02:42 +00008734
8735/// Consider whether capturing the given variable can possibly lead to
8736/// a retain cycle.
8737static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008738 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008739 // lifetime. In MRR, it's captured strongly if the variable is
8740 // __block and has an appropriate type.
8741 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8742 return false;
8743
8744 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008745 if (ref)
8746 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008747 return true;
8748}
8749
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008750static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008751 while (true) {
8752 e = e->IgnoreParens();
8753 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8754 switch (cast->getCastKind()) {
8755 case CK_BitCast:
8756 case CK_LValueBitCast:
8757 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008758 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008759 e = cast->getSubExpr();
8760 continue;
8761
John McCall31168b02011-06-15 23:02:42 +00008762 default:
8763 return false;
8764 }
8765 }
8766
8767 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8768 ObjCIvarDecl *ivar = ref->getDecl();
8769 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8770 return false;
8771
8772 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008773 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008774 return false;
8775
8776 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8777 owner.Indirect = true;
8778 return true;
8779 }
8780
8781 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8782 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8783 if (!var) return false;
8784 return considerVariable(var, ref, owner);
8785 }
8786
John McCall31168b02011-06-15 23:02:42 +00008787 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8788 if (member->isArrow()) return false;
8789
8790 // Don't count this as an indirect ownership.
8791 e = member->getBase();
8792 continue;
8793 }
8794
John McCallfe96e0b2011-11-06 09:01:30 +00008795 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8796 // Only pay attention to pseudo-objects on property references.
8797 ObjCPropertyRefExpr *pre
8798 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8799 ->IgnoreParens());
8800 if (!pre) return false;
8801 if (pre->isImplicitProperty()) return false;
8802 ObjCPropertyDecl *property = pre->getExplicitProperty();
8803 if (!property->isRetaining() &&
8804 !(property->getPropertyIvarDecl() &&
8805 property->getPropertyIvarDecl()->getType()
8806 .getObjCLifetime() == Qualifiers::OCL_Strong))
8807 return false;
8808
8809 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008810 if (pre->isSuperReceiver()) {
8811 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8812 if (!owner.Variable)
8813 return false;
8814 owner.Loc = pre->getLocation();
8815 owner.Range = pre->getSourceRange();
8816 return true;
8817 }
John McCallfe96e0b2011-11-06 09:01:30 +00008818 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8819 ->getSourceExpr());
8820 continue;
8821 }
8822
John McCall31168b02011-06-15 23:02:42 +00008823 // Array ivars?
8824
8825 return false;
8826 }
8827}
8828
8829namespace {
8830 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8831 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8832 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008833 Context(Context), Variable(variable), Capturer(nullptr),
8834 VarWillBeReased(false) {}
8835 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008836 VarDecl *Variable;
8837 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008838 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008839
8840 void VisitDeclRefExpr(DeclRefExpr *ref) {
8841 if (ref->getDecl() == Variable && !Capturer)
8842 Capturer = ref;
8843 }
8844
John McCall31168b02011-06-15 23:02:42 +00008845 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8846 if (Capturer) return;
8847 Visit(ref->getBase());
8848 if (Capturer && ref->isFreeIvar())
8849 Capturer = ref;
8850 }
8851
8852 void VisitBlockExpr(BlockExpr *block) {
8853 // Look inside nested blocks
8854 if (block->getBlockDecl()->capturesVariable(Variable))
8855 Visit(block->getBlockDecl()->getBody());
8856 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008857
8858 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8859 if (Capturer) return;
8860 if (OVE->getSourceExpr())
8861 Visit(OVE->getSourceExpr());
8862 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008863 void VisitBinaryOperator(BinaryOperator *BinOp) {
8864 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8865 return;
8866 Expr *LHS = BinOp->getLHS();
8867 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8868 if (DRE->getDecl() != Variable)
8869 return;
8870 if (Expr *RHS = BinOp->getRHS()) {
8871 RHS = RHS->IgnoreParenCasts();
8872 llvm::APSInt Value;
8873 VarWillBeReased =
8874 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8875 }
8876 }
8877 }
John McCall31168b02011-06-15 23:02:42 +00008878 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008879}
John McCall31168b02011-06-15 23:02:42 +00008880
8881/// Check whether the given argument is a block which captures a
8882/// variable.
8883static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8884 assert(owner.Variable && owner.Loc.isValid());
8885
8886 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008887
8888 // Look through [^{...} copy] and Block_copy(^{...}).
8889 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8890 Selector Cmd = ME->getSelector();
8891 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8892 e = ME->getInstanceReceiver();
8893 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008894 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008895 e = e->IgnoreParenCasts();
8896 }
8897 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8898 if (CE->getNumArgs() == 1) {
8899 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008900 if (Fn) {
8901 const IdentifierInfo *FnI = Fn->getIdentifier();
8902 if (FnI && FnI->isStr("_Block_copy")) {
8903 e = CE->getArg(0)->IgnoreParenCasts();
8904 }
8905 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008906 }
8907 }
8908
John McCall31168b02011-06-15 23:02:42 +00008909 BlockExpr *block = dyn_cast<BlockExpr>(e);
8910 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008911 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008912
8913 FindCaptureVisitor visitor(S.Context, owner.Variable);
8914 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008915 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008916}
8917
8918static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8919 RetainCycleOwner &owner) {
8920 assert(capturer);
8921 assert(owner.Variable && owner.Loc.isValid());
8922
8923 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8924 << owner.Variable << capturer->getSourceRange();
8925 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8926 << owner.Indirect << owner.Range;
8927}
8928
8929/// Check for a keyword selector that starts with the word 'add' or
8930/// 'set'.
8931static bool isSetterLikeSelector(Selector sel) {
8932 if (sel.isUnarySelector()) return false;
8933
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008934 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008935 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008936 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008937 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008938 else if (str.startswith("add")) {
8939 // Specially whitelist 'addOperationWithBlock:'.
8940 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8941 return false;
8942 str = str.substr(3);
8943 }
John McCall31168b02011-06-15 23:02:42 +00008944 else
8945 return false;
8946
8947 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008948 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008949}
8950
Benjamin Kramer3a743452015-03-09 15:03:32 +00008951static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8952 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008953 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8954 Message->getReceiverInterface(),
8955 NSAPI::ClassId_NSMutableArray);
8956 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008957 return None;
8958 }
8959
8960 Selector Sel = Message->getSelector();
8961
8962 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8963 S.NSAPIObj->getNSArrayMethodKind(Sel);
8964 if (!MKOpt) {
8965 return None;
8966 }
8967
8968 NSAPI::NSArrayMethodKind MK = *MKOpt;
8969
8970 switch (MK) {
8971 case NSAPI::NSMutableArr_addObject:
8972 case NSAPI::NSMutableArr_insertObjectAtIndex:
8973 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8974 return 0;
8975 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8976 return 1;
8977
8978 default:
8979 return None;
8980 }
8981
8982 return None;
8983}
8984
8985static
8986Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8987 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008988 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8989 Message->getReceiverInterface(),
8990 NSAPI::ClassId_NSMutableDictionary);
8991 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008992 return None;
8993 }
8994
8995 Selector Sel = Message->getSelector();
8996
8997 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8998 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8999 if (!MKOpt) {
9000 return None;
9001 }
9002
9003 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9004
9005 switch (MK) {
9006 case NSAPI::NSMutableDict_setObjectForKey:
9007 case NSAPI::NSMutableDict_setValueForKey:
9008 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9009 return 0;
9010
9011 default:
9012 return None;
9013 }
9014
9015 return None;
9016}
9017
9018static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009019 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9020 Message->getReceiverInterface(),
9021 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00009022
Alex Denisov5dfac812015-08-06 04:51:14 +00009023 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9024 Message->getReceiverInterface(),
9025 NSAPI::ClassId_NSMutableOrderedSet);
9026 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009027 return None;
9028 }
9029
9030 Selector Sel = Message->getSelector();
9031
9032 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9033 if (!MKOpt) {
9034 return None;
9035 }
9036
9037 NSAPI::NSSetMethodKind MK = *MKOpt;
9038
9039 switch (MK) {
9040 case NSAPI::NSMutableSet_addObject:
9041 case NSAPI::NSOrderedSet_setObjectAtIndex:
9042 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9043 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9044 return 0;
9045 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9046 return 1;
9047 }
9048
9049 return None;
9050}
9051
9052void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9053 if (!Message->isInstanceMessage()) {
9054 return;
9055 }
9056
9057 Optional<int> ArgOpt;
9058
9059 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9060 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9061 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9062 return;
9063 }
9064
9065 int ArgIndex = *ArgOpt;
9066
Alex Denisove1d882c2015-03-04 17:55:52 +00009067 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9068 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9069 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9070 }
9071
Alex Denisov5dfac812015-08-06 04:51:14 +00009072 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009073 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009074 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009075 Diag(Message->getSourceRange().getBegin(),
9076 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009077 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009078 }
9079 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009080 } else {
9081 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9082
9083 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9084 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9085 }
9086
9087 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9088 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9089 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9090 ValueDecl *Decl = ReceiverRE->getDecl();
9091 Diag(Message->getSourceRange().getBegin(),
9092 diag::warn_objc_circular_container)
9093 << Decl->getName() << Decl->getName();
9094 if (!ArgRE->isObjCSelfExpr()) {
9095 Diag(Decl->getLocation(),
9096 diag::note_objc_circular_container_declared_here)
9097 << Decl->getName();
9098 }
9099 }
9100 }
9101 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9102 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9103 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9104 ObjCIvarDecl *Decl = IvarRE->getDecl();
9105 Diag(Message->getSourceRange().getBegin(),
9106 diag::warn_objc_circular_container)
9107 << Decl->getName() << Decl->getName();
9108 Diag(Decl->getLocation(),
9109 diag::note_objc_circular_container_declared_here)
9110 << Decl->getName();
9111 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009112 }
9113 }
9114 }
9115
9116}
9117
John McCall31168b02011-06-15 23:02:42 +00009118/// Check a message send to see if it's likely to cause a retain cycle.
9119void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9120 // Only check instance methods whose selector looks like a setter.
9121 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9122 return;
9123
9124 // Try to find a variable that the receiver is strongly owned by.
9125 RetainCycleOwner owner;
9126 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009127 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009128 return;
9129 } else {
9130 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9131 owner.Variable = getCurMethodDecl()->getSelfDecl();
9132 owner.Loc = msg->getSuperLoc();
9133 owner.Range = msg->getSuperLoc();
9134 }
9135
9136 // Check whether the receiver is captured by any of the arguments.
9137 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9138 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9139 return diagnoseRetainCycle(*this, capturer, owner);
9140}
9141
9142/// Check a property assign to see if it's likely to cause a retain cycle.
9143void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9144 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009145 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009146 return;
9147
9148 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9149 diagnoseRetainCycle(*this, capturer, owner);
9150}
9151
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009152void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9153 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009154 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009155 return;
9156
9157 // Because we don't have an expression for the variable, we have to set the
9158 // location explicitly here.
9159 Owner.Loc = Var->getLocation();
9160 Owner.Range = Var->getSourceRange();
9161
9162 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9163 diagnoseRetainCycle(*this, Capturer, Owner);
9164}
9165
Ted Kremenek9304da92012-12-21 08:04:28 +00009166static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9167 Expr *RHS, bool isProperty) {
9168 // Check if RHS is an Objective-C object literal, which also can get
9169 // immediately zapped in a weak reference. Note that we explicitly
9170 // allow ObjCStringLiterals, since those are designed to never really die.
9171 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009172
Ted Kremenek64873352012-12-21 22:46:35 +00009173 // This enum needs to match with the 'select' in
9174 // warn_objc_arc_literal_assign (off-by-1).
9175 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9176 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9177 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009178
9179 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009180 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009181 << (isProperty ? 0 : 1)
9182 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009183
9184 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009185}
9186
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009187static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9188 Qualifiers::ObjCLifetime LT,
9189 Expr *RHS, bool isProperty) {
9190 // Strip off any implicit cast added to get to the one ARC-specific.
9191 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9192 if (cast->getCastKind() == CK_ARCConsumeObject) {
9193 S.Diag(Loc, diag::warn_arc_retained_assign)
9194 << (LT == Qualifiers::OCL_ExplicitNone)
9195 << (isProperty ? 0 : 1)
9196 << RHS->getSourceRange();
9197 return true;
9198 }
9199 RHS = cast->getSubExpr();
9200 }
9201
9202 if (LT == Qualifiers::OCL_Weak &&
9203 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9204 return true;
9205
9206 return false;
9207}
9208
Ted Kremenekb36234d2012-12-21 08:04:20 +00009209bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9210 QualType LHS, Expr *RHS) {
9211 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9212
9213 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9214 return false;
9215
9216 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9217 return true;
9218
9219 return false;
9220}
9221
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009222void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9223 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009224 QualType LHSType;
9225 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009226 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009227 ObjCPropertyRefExpr *PRE
9228 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9229 if (PRE && !PRE->isImplicitProperty()) {
9230 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9231 if (PD)
9232 LHSType = PD->getType();
9233 }
9234
9235 if (LHSType.isNull())
9236 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009237
9238 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9239
9240 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009241 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009242 getCurFunction()->markSafeWeakUse(LHS);
9243 }
9244
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009245 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9246 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009247
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009248 // FIXME. Check for other life times.
9249 if (LT != Qualifiers::OCL_None)
9250 return;
9251
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009252 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009253 if (PRE->isImplicitProperty())
9254 return;
9255 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9256 if (!PD)
9257 return;
9258
Bill Wendling44426052012-12-20 19:22:21 +00009259 unsigned Attributes = PD->getPropertyAttributes();
9260 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009261 // when 'assign' attribute was not explicitly specified
9262 // by user, ignore it and rely on property type itself
9263 // for lifetime info.
9264 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9265 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9266 LHSType->isObjCRetainableType())
9267 return;
9268
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009269 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009270 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009271 Diag(Loc, diag::warn_arc_retained_property_assign)
9272 << RHS->getSourceRange();
9273 return;
9274 }
9275 RHS = cast->getSubExpr();
9276 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009277 }
Bill Wendling44426052012-12-20 19:22:21 +00009278 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009279 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9280 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009281 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009282 }
9283}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009284
9285//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9286
9287namespace {
9288bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9289 SourceLocation StmtLoc,
9290 const NullStmt *Body) {
9291 // Do not warn if the body is a macro that expands to nothing, e.g:
9292 //
9293 // #define CALL(x)
9294 // if (condition)
9295 // CALL(0);
9296 //
9297 if (Body->hasLeadingEmptyMacro())
9298 return false;
9299
9300 // Get line numbers of statement and body.
9301 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009302 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009303 &StmtLineInvalid);
9304 if (StmtLineInvalid)
9305 return false;
9306
9307 bool BodyLineInvalid;
9308 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9309 &BodyLineInvalid);
9310 if (BodyLineInvalid)
9311 return false;
9312
9313 // Warn if null statement and body are on the same line.
9314 if (StmtLine != BodyLine)
9315 return false;
9316
9317 return true;
9318}
9319} // Unnamed namespace
9320
9321void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9322 const Stmt *Body,
9323 unsigned DiagID) {
9324 // Since this is a syntactic check, don't emit diagnostic for template
9325 // instantiations, this just adds noise.
9326 if (CurrentInstantiationScope)
9327 return;
9328
9329 // The body should be a null statement.
9330 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9331 if (!NBody)
9332 return;
9333
9334 // Do the usual checks.
9335 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9336 return;
9337
9338 Diag(NBody->getSemiLoc(), DiagID);
9339 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9340}
9341
9342void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9343 const Stmt *PossibleBody) {
9344 assert(!CurrentInstantiationScope); // Ensured by caller
9345
9346 SourceLocation StmtLoc;
9347 const Stmt *Body;
9348 unsigned DiagID;
9349 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9350 StmtLoc = FS->getRParenLoc();
9351 Body = FS->getBody();
9352 DiagID = diag::warn_empty_for_body;
9353 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9354 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9355 Body = WS->getBody();
9356 DiagID = diag::warn_empty_while_body;
9357 } else
9358 return; // Neither `for' nor `while'.
9359
9360 // The body should be a null statement.
9361 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9362 if (!NBody)
9363 return;
9364
9365 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009366 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009367 return;
9368
9369 // Do the usual checks.
9370 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9371 return;
9372
9373 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9374 // noise level low, emit diagnostics only if for/while is followed by a
9375 // CompoundStmt, e.g.:
9376 // for (int i = 0; i < n; i++);
9377 // {
9378 // a(i);
9379 // }
9380 // or if for/while is followed by a statement with more indentation
9381 // than for/while itself:
9382 // for (int i = 0; i < n; i++);
9383 // a(i);
9384 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9385 if (!ProbableTypo) {
9386 bool BodyColInvalid;
9387 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9388 PossibleBody->getLocStart(),
9389 &BodyColInvalid);
9390 if (BodyColInvalid)
9391 return;
9392
9393 bool StmtColInvalid;
9394 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9395 S->getLocStart(),
9396 &StmtColInvalid);
9397 if (StmtColInvalid)
9398 return;
9399
9400 if (BodyCol > StmtCol)
9401 ProbableTypo = true;
9402 }
9403
9404 if (ProbableTypo) {
9405 Diag(NBody->getSemiLoc(), DiagID);
9406 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9407 }
9408}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009409
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009410//===--- CHECK: Warn on self move with std::move. -------------------------===//
9411
9412/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9413void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9414 SourceLocation OpLoc) {
9415
9416 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9417 return;
9418
9419 if (!ActiveTemplateInstantiations.empty())
9420 return;
9421
9422 // Strip parens and casts away.
9423 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9424 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9425
9426 // Check for a call expression
9427 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9428 if (!CE || CE->getNumArgs() != 1)
9429 return;
9430
9431 // Check for a call to std::move
9432 const FunctionDecl *FD = CE->getDirectCallee();
9433 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9434 !FD->getIdentifier()->isStr("move"))
9435 return;
9436
9437 // Get argument from std::move
9438 RHSExpr = CE->getArg(0);
9439
9440 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9441 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9442
9443 // Two DeclRefExpr's, check that the decls are the same.
9444 if (LHSDeclRef && RHSDeclRef) {
9445 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9446 return;
9447 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9448 RHSDeclRef->getDecl()->getCanonicalDecl())
9449 return;
9450
9451 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9452 << LHSExpr->getSourceRange()
9453 << RHSExpr->getSourceRange();
9454 return;
9455 }
9456
9457 // Member variables require a different approach to check for self moves.
9458 // MemberExpr's are the same if every nested MemberExpr refers to the same
9459 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9460 // the base Expr's are CXXThisExpr's.
9461 const Expr *LHSBase = LHSExpr;
9462 const Expr *RHSBase = RHSExpr;
9463 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9464 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9465 if (!LHSME || !RHSME)
9466 return;
9467
9468 while (LHSME && RHSME) {
9469 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9470 RHSME->getMemberDecl()->getCanonicalDecl())
9471 return;
9472
9473 LHSBase = LHSME->getBase();
9474 RHSBase = RHSME->getBase();
9475 LHSME = dyn_cast<MemberExpr>(LHSBase);
9476 RHSME = dyn_cast<MemberExpr>(RHSBase);
9477 }
9478
9479 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9480 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9481 if (LHSDeclRef && RHSDeclRef) {
9482 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9483 return;
9484 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9485 RHSDeclRef->getDecl()->getCanonicalDecl())
9486 return;
9487
9488 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9489 << LHSExpr->getSourceRange()
9490 << RHSExpr->getSourceRange();
9491 return;
9492 }
9493
9494 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9495 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9496 << LHSExpr->getSourceRange()
9497 << RHSExpr->getSourceRange();
9498}
9499
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009500//===--- Layout compatibility ----------------------------------------------//
9501
9502namespace {
9503
9504bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9505
9506/// \brief Check if two enumeration types are layout-compatible.
9507bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9508 // C++11 [dcl.enum] p8:
9509 // Two enumeration types are layout-compatible if they have the same
9510 // underlying type.
9511 return ED1->isComplete() && ED2->isComplete() &&
9512 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9513}
9514
9515/// \brief Check if two fields are layout-compatible.
9516bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9517 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9518 return false;
9519
9520 if (Field1->isBitField() != Field2->isBitField())
9521 return false;
9522
9523 if (Field1->isBitField()) {
9524 // Make sure that the bit-fields are the same length.
9525 unsigned Bits1 = Field1->getBitWidthValue(C);
9526 unsigned Bits2 = Field2->getBitWidthValue(C);
9527
9528 if (Bits1 != Bits2)
9529 return false;
9530 }
9531
9532 return true;
9533}
9534
9535/// \brief Check if two standard-layout structs are layout-compatible.
9536/// (C++11 [class.mem] p17)
9537bool isLayoutCompatibleStruct(ASTContext &C,
9538 RecordDecl *RD1,
9539 RecordDecl *RD2) {
9540 // If both records are C++ classes, check that base classes match.
9541 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9542 // If one of records is a CXXRecordDecl we are in C++ mode,
9543 // thus the other one is a CXXRecordDecl, too.
9544 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9545 // Check number of base classes.
9546 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9547 return false;
9548
9549 // Check the base classes.
9550 for (CXXRecordDecl::base_class_const_iterator
9551 Base1 = D1CXX->bases_begin(),
9552 BaseEnd1 = D1CXX->bases_end(),
9553 Base2 = D2CXX->bases_begin();
9554 Base1 != BaseEnd1;
9555 ++Base1, ++Base2) {
9556 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9557 return false;
9558 }
9559 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9560 // If only RD2 is a C++ class, it should have zero base classes.
9561 if (D2CXX->getNumBases() > 0)
9562 return false;
9563 }
9564
9565 // Check the fields.
9566 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9567 Field2End = RD2->field_end(),
9568 Field1 = RD1->field_begin(),
9569 Field1End = RD1->field_end();
9570 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9571 if (!isLayoutCompatible(C, *Field1, *Field2))
9572 return false;
9573 }
9574 if (Field1 != Field1End || Field2 != Field2End)
9575 return false;
9576
9577 return true;
9578}
9579
9580/// \brief Check if two standard-layout unions are layout-compatible.
9581/// (C++11 [class.mem] p18)
9582bool isLayoutCompatibleUnion(ASTContext &C,
9583 RecordDecl *RD1,
9584 RecordDecl *RD2) {
9585 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009586 for (auto *Field2 : RD2->fields())
9587 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009588
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009589 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009590 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9591 I = UnmatchedFields.begin(),
9592 E = UnmatchedFields.end();
9593
9594 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009595 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009596 bool Result = UnmatchedFields.erase(*I);
9597 (void) Result;
9598 assert(Result);
9599 break;
9600 }
9601 }
9602 if (I == E)
9603 return false;
9604 }
9605
9606 return UnmatchedFields.empty();
9607}
9608
9609bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9610 if (RD1->isUnion() != RD2->isUnion())
9611 return false;
9612
9613 if (RD1->isUnion())
9614 return isLayoutCompatibleUnion(C, RD1, RD2);
9615 else
9616 return isLayoutCompatibleStruct(C, RD1, RD2);
9617}
9618
9619/// \brief Check if two types are layout-compatible in C++11 sense.
9620bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9621 if (T1.isNull() || T2.isNull())
9622 return false;
9623
9624 // C++11 [basic.types] p11:
9625 // If two types T1 and T2 are the same type, then T1 and T2 are
9626 // layout-compatible types.
9627 if (C.hasSameType(T1, T2))
9628 return true;
9629
9630 T1 = T1.getCanonicalType().getUnqualifiedType();
9631 T2 = T2.getCanonicalType().getUnqualifiedType();
9632
9633 const Type::TypeClass TC1 = T1->getTypeClass();
9634 const Type::TypeClass TC2 = T2->getTypeClass();
9635
9636 if (TC1 != TC2)
9637 return false;
9638
9639 if (TC1 == Type::Enum) {
9640 return isLayoutCompatible(C,
9641 cast<EnumType>(T1)->getDecl(),
9642 cast<EnumType>(T2)->getDecl());
9643 } else if (TC1 == Type::Record) {
9644 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9645 return false;
9646
9647 return isLayoutCompatible(C,
9648 cast<RecordType>(T1)->getDecl(),
9649 cast<RecordType>(T2)->getDecl());
9650 }
9651
9652 return false;
9653}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009654}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009655
9656//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9657
9658namespace {
9659/// \brief Given a type tag expression find the type tag itself.
9660///
9661/// \param TypeExpr Type tag expression, as it appears in user's code.
9662///
9663/// \param VD Declaration of an identifier that appears in a type tag.
9664///
9665/// \param MagicValue Type tag magic value.
9666bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9667 const ValueDecl **VD, uint64_t *MagicValue) {
9668 while(true) {
9669 if (!TypeExpr)
9670 return false;
9671
9672 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9673
9674 switch (TypeExpr->getStmtClass()) {
9675 case Stmt::UnaryOperatorClass: {
9676 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9677 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9678 TypeExpr = UO->getSubExpr();
9679 continue;
9680 }
9681 return false;
9682 }
9683
9684 case Stmt::DeclRefExprClass: {
9685 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9686 *VD = DRE->getDecl();
9687 return true;
9688 }
9689
9690 case Stmt::IntegerLiteralClass: {
9691 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9692 llvm::APInt MagicValueAPInt = IL->getValue();
9693 if (MagicValueAPInt.getActiveBits() <= 64) {
9694 *MagicValue = MagicValueAPInt.getZExtValue();
9695 return true;
9696 } else
9697 return false;
9698 }
9699
9700 case Stmt::BinaryConditionalOperatorClass:
9701 case Stmt::ConditionalOperatorClass: {
9702 const AbstractConditionalOperator *ACO =
9703 cast<AbstractConditionalOperator>(TypeExpr);
9704 bool Result;
9705 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9706 if (Result)
9707 TypeExpr = ACO->getTrueExpr();
9708 else
9709 TypeExpr = ACO->getFalseExpr();
9710 continue;
9711 }
9712 return false;
9713 }
9714
9715 case Stmt::BinaryOperatorClass: {
9716 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9717 if (BO->getOpcode() == BO_Comma) {
9718 TypeExpr = BO->getRHS();
9719 continue;
9720 }
9721 return false;
9722 }
9723
9724 default:
9725 return false;
9726 }
9727 }
9728}
9729
9730/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9731///
9732/// \param TypeExpr Expression that specifies a type tag.
9733///
9734/// \param MagicValues Registered magic values.
9735///
9736/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9737/// kind.
9738///
9739/// \param TypeInfo Information about the corresponding C type.
9740///
9741/// \returns true if the corresponding C type was found.
9742bool GetMatchingCType(
9743 const IdentifierInfo *ArgumentKind,
9744 const Expr *TypeExpr, const ASTContext &Ctx,
9745 const llvm::DenseMap<Sema::TypeTagMagicValue,
9746 Sema::TypeTagData> *MagicValues,
9747 bool &FoundWrongKind,
9748 Sema::TypeTagData &TypeInfo) {
9749 FoundWrongKind = false;
9750
9751 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009752 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009753
9754 uint64_t MagicValue;
9755
9756 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9757 return false;
9758
9759 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009760 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009761 if (I->getArgumentKind() != ArgumentKind) {
9762 FoundWrongKind = true;
9763 return false;
9764 }
9765 TypeInfo.Type = I->getMatchingCType();
9766 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9767 TypeInfo.MustBeNull = I->getMustBeNull();
9768 return true;
9769 }
9770 return false;
9771 }
9772
9773 if (!MagicValues)
9774 return false;
9775
9776 llvm::DenseMap<Sema::TypeTagMagicValue,
9777 Sema::TypeTagData>::const_iterator I =
9778 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9779 if (I == MagicValues->end())
9780 return false;
9781
9782 TypeInfo = I->second;
9783 return true;
9784}
9785} // unnamed namespace
9786
9787void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9788 uint64_t MagicValue, QualType Type,
9789 bool LayoutCompatible,
9790 bool MustBeNull) {
9791 if (!TypeTagForDatatypeMagicValues)
9792 TypeTagForDatatypeMagicValues.reset(
9793 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9794
9795 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9796 (*TypeTagForDatatypeMagicValues)[Magic] =
9797 TypeTagData(Type, LayoutCompatible, MustBeNull);
9798}
9799
9800namespace {
9801bool IsSameCharType(QualType T1, QualType T2) {
9802 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9803 if (!BT1)
9804 return false;
9805
9806 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9807 if (!BT2)
9808 return false;
9809
9810 BuiltinType::Kind T1Kind = BT1->getKind();
9811 BuiltinType::Kind T2Kind = BT2->getKind();
9812
9813 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9814 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9815 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9816 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9817}
9818} // unnamed namespace
9819
9820void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9821 const Expr * const *ExprArgs) {
9822 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9823 bool IsPointerAttr = Attr->getIsPointer();
9824
9825 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9826 bool FoundWrongKind;
9827 TypeTagData TypeInfo;
9828 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9829 TypeTagForDatatypeMagicValues.get(),
9830 FoundWrongKind, TypeInfo)) {
9831 if (FoundWrongKind)
9832 Diag(TypeTagExpr->getExprLoc(),
9833 diag::warn_type_tag_for_datatype_wrong_kind)
9834 << TypeTagExpr->getSourceRange();
9835 return;
9836 }
9837
9838 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9839 if (IsPointerAttr) {
9840 // Skip implicit cast of pointer to `void *' (as a function argument).
9841 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009842 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009843 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009844 ArgumentExpr = ICE->getSubExpr();
9845 }
9846 QualType ArgumentType = ArgumentExpr->getType();
9847
9848 // Passing a `void*' pointer shouldn't trigger a warning.
9849 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9850 return;
9851
9852 if (TypeInfo.MustBeNull) {
9853 // Type tag with matching void type requires a null pointer.
9854 if (!ArgumentExpr->isNullPointerConstant(Context,
9855 Expr::NPC_ValueDependentIsNotNull)) {
9856 Diag(ArgumentExpr->getExprLoc(),
9857 diag::warn_type_safety_null_pointer_required)
9858 << ArgumentKind->getName()
9859 << ArgumentExpr->getSourceRange()
9860 << TypeTagExpr->getSourceRange();
9861 }
9862 return;
9863 }
9864
9865 QualType RequiredType = TypeInfo.Type;
9866 if (IsPointerAttr)
9867 RequiredType = Context.getPointerType(RequiredType);
9868
9869 bool mismatch = false;
9870 if (!TypeInfo.LayoutCompatible) {
9871 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9872
9873 // C++11 [basic.fundamental] p1:
9874 // Plain char, signed char, and unsigned char are three distinct types.
9875 //
9876 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9877 // char' depending on the current char signedness mode.
9878 if (mismatch)
9879 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9880 RequiredType->getPointeeType())) ||
9881 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9882 mismatch = false;
9883 } else
9884 if (IsPointerAttr)
9885 mismatch = !isLayoutCompatible(Context,
9886 ArgumentType->getPointeeType(),
9887 RequiredType->getPointeeType());
9888 else
9889 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9890
9891 if (mismatch)
9892 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009893 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009894 << TypeInfo.LayoutCompatible << RequiredType
9895 << ArgumentExpr->getSourceRange()
9896 << TypeTagExpr->getSourceRange();
9897}