blob: e2d044c00e4bd1843adbe0cb8e3ca32523ddce7c [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.
1183static bool CheckNonNullExpr(Sema &S,
1184 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001185 // If the expression has non-null type, it doesn't evaluate to null.
1186 if (auto nullability
1187 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1188 if (*nullability == NullabilityKind::NonNull)
1189 return false;
1190 }
1191
Ted Kremeneka146db32014-01-17 06:24:47 +00001192 // As a special case, transparent unions initialized with zero are
1193 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001194 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001195 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1196 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001197 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001198 if (const InitListExpr *ILE =
1199 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001200 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001201 }
1202
1203 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001204 return (!Expr->isValueDependent() &&
1205 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1206 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001207}
1208
1209static void CheckNonNullArgument(Sema &S,
1210 const Expr *ArgExpr,
1211 SourceLocation CallSiteLoc) {
1212 if (CheckNonNullExpr(S, ArgExpr))
Eric Fiselier18677d52015-10-09 00:17:57 +00001213 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1214 S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
Ted Kremeneka146db32014-01-17 06:24:47 +00001215}
1216
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001217bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1218 FormatStringInfo FSI;
1219 if ((GetFormatStringType(Format) == FST_NSString) &&
1220 getFormatStringInfo(Format, false, &FSI)) {
1221 Idx = FSI.FormatIdx;
1222 return true;
1223 }
1224 return false;
1225}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001226/// \brief Diagnose use of %s directive in an NSString which is being passed
1227/// as formatting string to formatting method.
1228static void
1229DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1230 const NamedDecl *FDecl,
1231 Expr **Args,
1232 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001233 unsigned Idx = 0;
1234 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001235 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1236 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001237 Idx = 2;
1238 Format = true;
1239 }
1240 else
1241 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1242 if (S.GetFormatNSStringIdx(I, Idx)) {
1243 Format = true;
1244 break;
1245 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001246 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001247 if (!Format || NumArgs <= Idx)
1248 return;
1249 const Expr *FormatExpr = Args[Idx];
1250 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1251 FormatExpr = CSCE->getSubExpr();
1252 const StringLiteral *FormatString;
1253 if (const ObjCStringLiteral *OSL =
1254 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1255 FormatString = OSL->getString();
1256 else
1257 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1258 if (!FormatString)
1259 return;
1260 if (S.FormatStringHasSArg(FormatString)) {
1261 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1262 << "%s" << 1 << 1;
1263 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1264 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001265 }
1266}
1267
Douglas Gregorb4866e82015-06-19 18:13:19 +00001268/// Determine whether the given type has a non-null nullability annotation.
1269static bool isNonNullType(ASTContext &ctx, QualType type) {
1270 if (auto nullability = type->getNullability(ctx))
1271 return *nullability == NullabilityKind::NonNull;
1272
1273 return false;
1274}
1275
Ted Kremenek2bc73332014-01-17 06:24:43 +00001276static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001277 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001278 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001279 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001280 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001281 assert((FDecl || Proto) && "Need a function declaration or prototype");
1282
Ted Kremenek9aedc152014-01-17 06:24:56 +00001283 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001284 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001285 if (FDecl) {
1286 // Handle the nonnull attribute on the function/method declaration itself.
1287 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1288 if (!NonNull->args_size()) {
1289 // Easy case: all pointer arguments are nonnull.
1290 for (const auto *Arg : Args)
1291 if (S.isValidPointerAttrType(Arg->getType()))
1292 CheckNonNullArgument(S, Arg, CallSiteLoc);
1293 return;
1294 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001295
Douglas Gregorb4866e82015-06-19 18:13:19 +00001296 for (unsigned Val : NonNull->args()) {
1297 if (Val >= Args.size())
1298 continue;
1299 if (NonNullArgs.empty())
1300 NonNullArgs.resize(Args.size());
1301 NonNullArgs.set(Val);
1302 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001303 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001304 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001305
Douglas Gregorb4866e82015-06-19 18:13:19 +00001306 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1307 // Handle the nonnull attribute on the parameters of the
1308 // function/method.
1309 ArrayRef<ParmVarDecl*> parms;
1310 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1311 parms = FD->parameters();
1312 else
1313 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1314
1315 unsigned ParamIndex = 0;
1316 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1317 I != E; ++I, ++ParamIndex) {
1318 const ParmVarDecl *PVD = *I;
1319 if (PVD->hasAttr<NonNullAttr>() ||
1320 isNonNullType(S.Context, PVD->getType())) {
1321 if (NonNullArgs.empty())
1322 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001323
Douglas Gregorb4866e82015-06-19 18:13:19 +00001324 NonNullArgs.set(ParamIndex);
1325 }
1326 }
1327 } else {
1328 // If we have a non-function, non-method declaration but no
1329 // function prototype, try to dig out the function prototype.
1330 if (!Proto) {
1331 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1332 QualType type = VD->getType().getNonReferenceType();
1333 if (auto pointerType = type->getAs<PointerType>())
1334 type = pointerType->getPointeeType();
1335 else if (auto blockType = type->getAs<BlockPointerType>())
1336 type = blockType->getPointeeType();
1337 // FIXME: data member pointers?
1338
1339 // Dig out the function prototype, if there is one.
1340 Proto = type->getAs<FunctionProtoType>();
1341 }
1342 }
1343
1344 // Fill in non-null argument information from the nullability
1345 // information on the parameter types (if we have them).
1346 if (Proto) {
1347 unsigned Index = 0;
1348 for (auto paramType : Proto->getParamTypes()) {
1349 if (isNonNullType(S.Context, paramType)) {
1350 if (NonNullArgs.empty())
1351 NonNullArgs.resize(Args.size());
1352
1353 NonNullArgs.set(Index);
1354 }
1355
1356 ++Index;
1357 }
1358 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001359 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001360
Douglas Gregorb4866e82015-06-19 18:13:19 +00001361 // Check for non-null arguments.
1362 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1363 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001364 if (NonNullArgs[ArgIndex])
1365 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001366 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001367}
1368
Richard Smith55ce3522012-06-25 20:30:08 +00001369/// Handles the checks for format strings, non-POD arguments to vararg
1370/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001371void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1372 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001373 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001374 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001375 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001376 if (CurContext->isDependentContext())
1377 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001378
Ted Kremenekb8176da2010-09-09 04:33:05 +00001379 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001380 llvm::SmallBitVector CheckedVarArgs;
1381 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001382 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001383 // Only create vector if there are format attributes.
1384 CheckedVarArgs.resize(Args.size());
1385
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001386 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001387 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001388 }
Richard Smithd7293d72013-08-05 18:49:43 +00001389 }
Richard Smith55ce3522012-06-25 20:30:08 +00001390
1391 // Refuse POD arguments that weren't caught by the format string
1392 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001393 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001394 unsigned NumParams = Proto ? Proto->getNumParams()
1395 : FDecl && isa<FunctionDecl>(FDecl)
1396 ? cast<FunctionDecl>(FDecl)->getNumParams()
1397 : FDecl && isa<ObjCMethodDecl>(FDecl)
1398 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1399 : 0;
1400
Alp Toker9cacbab2014-01-20 20:26:09 +00001401 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001402 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001403 if (const Expr *Arg = Args[ArgIdx]) {
1404 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1405 checkVariadicArgument(Arg, CallType);
1406 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001407 }
Richard Smithd7293d72013-08-05 18:49:43 +00001408 }
Mike Stump11289f42009-09-09 15:08:12 +00001409
Douglas Gregorb4866e82015-06-19 18:13:19 +00001410 if (FDecl || Proto) {
1411 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001412
Richard Trieu41bc0992013-06-22 00:20:41 +00001413 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001414 if (FDecl) {
1415 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1416 CheckArgumentWithTypeTag(I, Args.data());
1417 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001418 }
Richard Smith55ce3522012-06-25 20:30:08 +00001419}
1420
1421/// CheckConstructorCall - Check a constructor call for correctness and safety
1422/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001423void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1424 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001425 const FunctionProtoType *Proto,
1426 SourceLocation Loc) {
1427 VariadicCallType CallType =
1428 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001429 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1430 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001431}
1432
1433/// CheckFunctionCall - Check a direct function call for various correctness
1434/// and safety properties not strictly enforced by the C type system.
1435bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1436 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001437 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1438 isa<CXXMethodDecl>(FDecl);
1439 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1440 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001441 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1442 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001443 Expr** Args = TheCall->getArgs();
1444 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001445 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001446 // If this is a call to a member operator, hide the first argument
1447 // from checkCall.
1448 // FIXME: Our choice of AST representation here is less than ideal.
1449 ++Args;
1450 --NumArgs;
1451 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001452 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001453 IsMemberFunction, TheCall->getRParenLoc(),
1454 TheCall->getCallee()->getSourceRange(), CallType);
1455
1456 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1457 // None of the checks below are needed for functions that don't have
1458 // simple names (e.g., C++ conversion functions).
1459 if (!FnInfo)
1460 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001461
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001462 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001463 if (getLangOpts().ObjC1)
1464 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001465
Anna Zaks22122702012-01-17 00:37:07 +00001466 unsigned CMId = FDecl->getMemoryFunctionKind();
1467 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001468 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001469
Anna Zaks201d4892012-01-13 21:52:01 +00001470 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001471 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001472 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001473 else if (CMId == Builtin::BIstrncat)
1474 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001475 else
Anna Zaks22122702012-01-17 00:37:07 +00001476 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001477
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001478 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001479}
1480
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001481bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001482 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001483 VariadicCallType CallType =
1484 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001485
Douglas Gregorb4866e82015-06-19 18:13:19 +00001486 checkCall(Method, nullptr, Args,
1487 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1488 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001489
1490 return false;
1491}
1492
Richard Trieu664c4c62013-06-20 21:03:13 +00001493bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1494 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001495 QualType Ty;
1496 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001497 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001498 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001499 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001500 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001501 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001502
Douglas Gregorb4866e82015-06-19 18:13:19 +00001503 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1504 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001505 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001506
Richard Trieu664c4c62013-06-20 21:03:13 +00001507 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001508 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001509 CallType = VariadicDoesNotApply;
1510 } else if (Ty->isBlockPointerType()) {
1511 CallType = VariadicBlock;
1512 } else { // Ty->isFunctionPointerType()
1513 CallType = VariadicFunction;
1514 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001515
Douglas Gregorb4866e82015-06-19 18:13:19 +00001516 checkCall(NDecl, Proto,
1517 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1518 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001519 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001520
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001521 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001522}
1523
Richard Trieu41bc0992013-06-22 00:20:41 +00001524/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1525/// such as function pointers returned from functions.
1526bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001527 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001528 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001529 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001530 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001531 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001532 TheCall->getCallee()->getSourceRange(), CallType);
1533
1534 return false;
1535}
1536
Tim Northovere94a34c2014-03-11 10:49:14 +00001537static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1538 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1539 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1540 return false;
1541
1542 switch (Op) {
1543 case AtomicExpr::AO__c11_atomic_init:
1544 llvm_unreachable("There is no ordering argument for an init");
1545
1546 case AtomicExpr::AO__c11_atomic_load:
1547 case AtomicExpr::AO__atomic_load_n:
1548 case AtomicExpr::AO__atomic_load:
1549 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1550 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1551
1552 case AtomicExpr::AO__c11_atomic_store:
1553 case AtomicExpr::AO__atomic_store:
1554 case AtomicExpr::AO__atomic_store_n:
1555 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1556 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1557 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1558
1559 default:
1560 return true;
1561 }
1562}
1563
Richard Smithfeea8832012-04-12 05:08:17 +00001564ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1565 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001566 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1567 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001568
Richard Smithfeea8832012-04-12 05:08:17 +00001569 // All these operations take one of the following forms:
1570 enum {
1571 // C __c11_atomic_init(A *, C)
1572 Init,
1573 // C __c11_atomic_load(A *, int)
1574 Load,
1575 // void __atomic_load(A *, CP, int)
1576 Copy,
1577 // C __c11_atomic_add(A *, M, int)
1578 Arithmetic,
1579 // C __atomic_exchange_n(A *, CP, int)
1580 Xchg,
1581 // void __atomic_exchange(A *, C *, CP, int)
1582 GNUXchg,
1583 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1584 C11CmpXchg,
1585 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1586 GNUCmpXchg
1587 } Form = Init;
1588 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1589 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1590 // where:
1591 // C is an appropriate type,
1592 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1593 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1594 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1595 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001596
Gabor Horvath98bd0982015-03-16 09:59:54 +00001597 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1598 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1599 AtomicExpr::AO__atomic_load,
1600 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001601 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1602 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1603 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1604 Op == AtomicExpr::AO__atomic_store_n ||
1605 Op == AtomicExpr::AO__atomic_exchange_n ||
1606 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1607 bool IsAddSub = false;
1608
1609 switch (Op) {
1610 case AtomicExpr::AO__c11_atomic_init:
1611 Form = Init;
1612 break;
1613
1614 case AtomicExpr::AO__c11_atomic_load:
1615 case AtomicExpr::AO__atomic_load_n:
1616 Form = Load;
1617 break;
1618
1619 case AtomicExpr::AO__c11_atomic_store:
1620 case AtomicExpr::AO__atomic_load:
1621 case AtomicExpr::AO__atomic_store:
1622 case AtomicExpr::AO__atomic_store_n:
1623 Form = Copy;
1624 break;
1625
1626 case AtomicExpr::AO__c11_atomic_fetch_add:
1627 case AtomicExpr::AO__c11_atomic_fetch_sub:
1628 case AtomicExpr::AO__atomic_fetch_add:
1629 case AtomicExpr::AO__atomic_fetch_sub:
1630 case AtomicExpr::AO__atomic_add_fetch:
1631 case AtomicExpr::AO__atomic_sub_fetch:
1632 IsAddSub = true;
1633 // Fall through.
1634 case AtomicExpr::AO__c11_atomic_fetch_and:
1635 case AtomicExpr::AO__c11_atomic_fetch_or:
1636 case AtomicExpr::AO__c11_atomic_fetch_xor:
1637 case AtomicExpr::AO__atomic_fetch_and:
1638 case AtomicExpr::AO__atomic_fetch_or:
1639 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001640 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001641 case AtomicExpr::AO__atomic_and_fetch:
1642 case AtomicExpr::AO__atomic_or_fetch:
1643 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001644 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001645 Form = Arithmetic;
1646 break;
1647
1648 case AtomicExpr::AO__c11_atomic_exchange:
1649 case AtomicExpr::AO__atomic_exchange_n:
1650 Form = Xchg;
1651 break;
1652
1653 case AtomicExpr::AO__atomic_exchange:
1654 Form = GNUXchg;
1655 break;
1656
1657 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1658 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1659 Form = C11CmpXchg;
1660 break;
1661
1662 case AtomicExpr::AO__atomic_compare_exchange:
1663 case AtomicExpr::AO__atomic_compare_exchange_n:
1664 Form = GNUCmpXchg;
1665 break;
1666 }
1667
1668 // Check we have the right number of arguments.
1669 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001670 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001671 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001672 << TheCall->getCallee()->getSourceRange();
1673 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001674 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1675 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001676 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001677 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001678 << TheCall->getCallee()->getSourceRange();
1679 return ExprError();
1680 }
1681
Richard Smithfeea8832012-04-12 05:08:17 +00001682 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001683 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001684 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1685 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1686 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001687 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001688 << Ptr->getType() << Ptr->getSourceRange();
1689 return ExprError();
1690 }
1691
Richard Smithfeea8832012-04-12 05:08:17 +00001692 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1693 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1694 QualType ValType = AtomTy; // 'C'
1695 if (IsC11) {
1696 if (!AtomTy->isAtomicType()) {
1697 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1698 << Ptr->getType() << Ptr->getSourceRange();
1699 return ExprError();
1700 }
Richard Smithe00921a2012-09-15 06:09:58 +00001701 if (AtomTy.isConstQualified()) {
1702 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1703 << Ptr->getType() << Ptr->getSourceRange();
1704 return ExprError();
1705 }
Richard Smithfeea8832012-04-12 05:08:17 +00001706 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001707 } else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1708 if (ValType.isConstQualified()) {
1709 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1710 << Ptr->getType() << Ptr->getSourceRange();
1711 return ExprError();
1712 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001713 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001714
Richard Smithfeea8832012-04-12 05:08:17 +00001715 // For an arithmetic operation, the implied arithmetic must be well-formed.
1716 if (Form == Arithmetic) {
1717 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1718 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1719 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1720 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1721 return ExprError();
1722 }
1723 if (!IsAddSub && !ValType->isIntegerType()) {
1724 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1725 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1726 return ExprError();
1727 }
David Majnemere85cff82015-01-28 05:48:06 +00001728 if (IsC11 && ValType->isPointerType() &&
1729 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1730 diag::err_incomplete_type)) {
1731 return ExprError();
1732 }
Richard Smithfeea8832012-04-12 05:08:17 +00001733 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1734 // For __atomic_*_n operations, the value type must be a scalar integral or
1735 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001736 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001737 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1738 return ExprError();
1739 }
1740
Eli Friedmanaa769812013-09-11 03:49:34 +00001741 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1742 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001743 // For GNU atomics, require a trivially-copyable type. This is not part of
1744 // the GNU atomics specification, but we enforce it for sanity.
1745 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001746 << Ptr->getType() << Ptr->getSourceRange();
1747 return ExprError();
1748 }
1749
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001750 switch (ValType.getObjCLifetime()) {
1751 case Qualifiers::OCL_None:
1752 case Qualifiers::OCL_ExplicitNone:
1753 // okay
1754 break;
1755
1756 case Qualifiers::OCL_Weak:
1757 case Qualifiers::OCL_Strong:
1758 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001759 // FIXME: Can this happen? By this point, ValType should be known
1760 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001761 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1762 << ValType << Ptr->getSourceRange();
1763 return ExprError();
1764 }
1765
David Majnemerc6eb6502015-06-03 00:26:35 +00001766 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1767 // volatile-ness of the pointee-type inject itself into the result or the
1768 // other operands.
1769 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001770 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001771 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001772 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001773 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001774 ResultType = Context.BoolTy;
1775
Richard Smithfeea8832012-04-12 05:08:17 +00001776 // The type of a parameter passed 'by value'. In the GNU atomics, such
1777 // arguments are actually passed as pointers.
1778 QualType ByValType = ValType; // 'CP'
1779 if (!IsC11 && !IsN)
1780 ByValType = Ptr->getType();
1781
Eric Fiseliera3a7c562015-10-04 00:11:02 +00001782 // FIXME: __atomic_load allows the first argument to be a a pointer to const
1783 // but not the second argument. We need to manually remove possible const
1784 // qualifiers.
1785
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001786 // The first argument --- the pointer --- has a fixed type; we
1787 // deduce the types of the rest of the arguments accordingly. Walk
1788 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001789 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001790 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001791 if (i < NumVals[Form] + 1) {
1792 switch (i) {
1793 case 1:
1794 // The second argument is the non-atomic operand. For arithmetic, this
1795 // is always passed by value, and for a compare_exchange it is always
1796 // passed by address. For the rest, GNU uses by-address and C11 uses
1797 // by-value.
1798 assert(Form != Load);
1799 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1800 Ty = ValType;
1801 else if (Form == Copy || Form == Xchg)
1802 Ty = ByValType;
1803 else if (Form == Arithmetic)
1804 Ty = Context.getPointerDiffType();
1805 else
1806 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1807 break;
1808 case 2:
1809 // The third argument to compare_exchange / GNU exchange is a
1810 // (pointer to a) desired value.
1811 Ty = ByValType;
1812 break;
1813 case 3:
1814 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1815 Ty = Context.BoolTy;
1816 break;
1817 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001818 } else {
1819 // The order(s) are always converted to int.
1820 Ty = Context.IntTy;
1821 }
Richard Smithfeea8832012-04-12 05:08:17 +00001822
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001823 InitializedEntity Entity =
1824 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001825 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001826 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1827 if (Arg.isInvalid())
1828 return true;
1829 TheCall->setArg(i, Arg.get());
1830 }
1831
Richard Smithfeea8832012-04-12 05:08:17 +00001832 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001833 SmallVector<Expr*, 5> SubExprs;
1834 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001835 switch (Form) {
1836 case Init:
1837 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001838 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001839 break;
1840 case Load:
1841 SubExprs.push_back(TheCall->getArg(1)); // Order
1842 break;
1843 case Copy:
1844 case Arithmetic:
1845 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001846 SubExprs.push_back(TheCall->getArg(2)); // Order
1847 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001848 break;
1849 case GNUXchg:
1850 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1851 SubExprs.push_back(TheCall->getArg(3)); // Order
1852 SubExprs.push_back(TheCall->getArg(1)); // Val1
1853 SubExprs.push_back(TheCall->getArg(2)); // Val2
1854 break;
1855 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001856 SubExprs.push_back(TheCall->getArg(3)); // Order
1857 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001858 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001859 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001860 break;
1861 case GNUCmpXchg:
1862 SubExprs.push_back(TheCall->getArg(4)); // Order
1863 SubExprs.push_back(TheCall->getArg(1)); // Val1
1864 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1865 SubExprs.push_back(TheCall->getArg(2)); // Val2
1866 SubExprs.push_back(TheCall->getArg(3)); // Weak
1867 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001868 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001869
1870 if (SubExprs.size() >= 2 && Form != Init) {
1871 llvm::APSInt Result(32);
1872 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1873 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001874 Diag(SubExprs[1]->getLocStart(),
1875 diag::warn_atomic_op_has_invalid_memory_order)
1876 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001877 }
1878
Fariborz Jahanian615de762013-05-28 17:37:39 +00001879 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1880 SubExprs, ResultType, Op,
1881 TheCall->getRParenLoc());
1882
1883 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1884 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1885 Context.AtomicUsesUnsupportedLibcall(AE))
1886 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1887 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001888
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001889 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001890}
1891
1892
John McCall29ad95b2011-08-27 01:09:30 +00001893/// checkBuiltinArgument - Given a call to a builtin function, perform
1894/// normal type-checking on the given argument, updating the call in
1895/// place. This is useful when a builtin function requires custom
1896/// type-checking for some of its arguments but not necessarily all of
1897/// them.
1898///
1899/// Returns true on error.
1900static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1901 FunctionDecl *Fn = E->getDirectCallee();
1902 assert(Fn && "builtin call without direct callee!");
1903
1904 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1905 InitializedEntity Entity =
1906 InitializedEntity::InitializeParameter(S.Context, Param);
1907
1908 ExprResult Arg = E->getArg(0);
1909 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1910 if (Arg.isInvalid())
1911 return true;
1912
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001913 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001914 return false;
1915}
1916
Chris Lattnerdc046542009-05-08 06:58:22 +00001917/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1918/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1919/// type of its first argument. The main ActOnCallExpr routines have already
1920/// promoted the types of arguments because all of these calls are prototyped as
1921/// void(...).
1922///
1923/// This function goes through and does final semantic checking for these
1924/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001925ExprResult
1926Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001927 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001928 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1929 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1930
1931 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001932 if (TheCall->getNumArgs() < 1) {
1933 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1934 << 0 << 1 << TheCall->getNumArgs()
1935 << TheCall->getCallee()->getSourceRange();
1936 return ExprError();
1937 }
Mike Stump11289f42009-09-09 15:08:12 +00001938
Chris Lattnerdc046542009-05-08 06:58:22 +00001939 // Inspect the first argument of the atomic builtin. This should always be
1940 // a pointer type, whose element is an integral scalar or pointer type.
1941 // Because it is a pointer type, we don't have to worry about any implicit
1942 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001943 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001944 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001945 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1946 if (FirstArgResult.isInvalid())
1947 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001948 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001949 TheCall->setArg(0, FirstArg);
1950
John McCall31168b02011-06-15 23:02:42 +00001951 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1952 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001953 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1954 << FirstArg->getType() << FirstArg->getSourceRange();
1955 return ExprError();
1956 }
Mike Stump11289f42009-09-09 15:08:12 +00001957
John McCall31168b02011-06-15 23:02:42 +00001958 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001959 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001960 !ValType->isBlockPointerType()) {
1961 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1962 << FirstArg->getType() << FirstArg->getSourceRange();
1963 return ExprError();
1964 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001965
John McCall31168b02011-06-15 23:02:42 +00001966 switch (ValType.getObjCLifetime()) {
1967 case Qualifiers::OCL_None:
1968 case Qualifiers::OCL_ExplicitNone:
1969 // okay
1970 break;
1971
1972 case Qualifiers::OCL_Weak:
1973 case Qualifiers::OCL_Strong:
1974 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001975 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001976 << ValType << FirstArg->getSourceRange();
1977 return ExprError();
1978 }
1979
John McCallb50451a2011-10-05 07:41:44 +00001980 // Strip any qualifiers off ValType.
1981 ValType = ValType.getUnqualifiedType();
1982
Chandler Carruth3973af72010-07-18 20:54:12 +00001983 // The majority of builtins return a value, but a few have special return
1984 // types, so allow them to override appropriately below.
1985 QualType ResultType = ValType;
1986
Chris Lattnerdc046542009-05-08 06:58:22 +00001987 // We need to figure out which concrete builtin this maps onto. For example,
1988 // __sync_fetch_and_add with a 2 byte object turns into
1989 // __sync_fetch_and_add_2.
1990#define BUILTIN_ROW(x) \
1991 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1992 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001993
Chris Lattnerdc046542009-05-08 06:58:22 +00001994 static const unsigned BuiltinIndices[][5] = {
1995 BUILTIN_ROW(__sync_fetch_and_add),
1996 BUILTIN_ROW(__sync_fetch_and_sub),
1997 BUILTIN_ROW(__sync_fetch_and_or),
1998 BUILTIN_ROW(__sync_fetch_and_and),
1999 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00002000 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00002001
Chris Lattnerdc046542009-05-08 06:58:22 +00002002 BUILTIN_ROW(__sync_add_and_fetch),
2003 BUILTIN_ROW(__sync_sub_and_fetch),
2004 BUILTIN_ROW(__sync_and_and_fetch),
2005 BUILTIN_ROW(__sync_or_and_fetch),
2006 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00002007 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00002008
Chris Lattnerdc046542009-05-08 06:58:22 +00002009 BUILTIN_ROW(__sync_val_compare_and_swap),
2010 BUILTIN_ROW(__sync_bool_compare_and_swap),
2011 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00002012 BUILTIN_ROW(__sync_lock_release),
2013 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00002014 };
Mike Stump11289f42009-09-09 15:08:12 +00002015#undef BUILTIN_ROW
2016
Chris Lattnerdc046542009-05-08 06:58:22 +00002017 // Determine the index of the size.
2018 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00002019 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00002020 case 1: SizeIndex = 0; break;
2021 case 2: SizeIndex = 1; break;
2022 case 4: SizeIndex = 2; break;
2023 case 8: SizeIndex = 3; break;
2024 case 16: SizeIndex = 4; break;
2025 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002026 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2027 << FirstArg->getType() << FirstArg->getSourceRange();
2028 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Chris Lattnerdc046542009-05-08 06:58:22 +00002031 // Each of these builtins has one pointer argument, followed by some number of
2032 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2033 // that we ignore. Find out which row of BuiltinIndices to read from as well
2034 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00002035 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00002036 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00002037 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00002038 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00002039 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00002040 case Builtin::BI__sync_fetch_and_add:
2041 case Builtin::BI__sync_fetch_and_add_1:
2042 case Builtin::BI__sync_fetch_and_add_2:
2043 case Builtin::BI__sync_fetch_and_add_4:
2044 case Builtin::BI__sync_fetch_and_add_8:
2045 case Builtin::BI__sync_fetch_and_add_16:
2046 BuiltinIndex = 0;
2047 break;
2048
2049 case Builtin::BI__sync_fetch_and_sub:
2050 case Builtin::BI__sync_fetch_and_sub_1:
2051 case Builtin::BI__sync_fetch_and_sub_2:
2052 case Builtin::BI__sync_fetch_and_sub_4:
2053 case Builtin::BI__sync_fetch_and_sub_8:
2054 case Builtin::BI__sync_fetch_and_sub_16:
2055 BuiltinIndex = 1;
2056 break;
2057
2058 case Builtin::BI__sync_fetch_and_or:
2059 case Builtin::BI__sync_fetch_and_or_1:
2060 case Builtin::BI__sync_fetch_and_or_2:
2061 case Builtin::BI__sync_fetch_and_or_4:
2062 case Builtin::BI__sync_fetch_and_or_8:
2063 case Builtin::BI__sync_fetch_and_or_16:
2064 BuiltinIndex = 2;
2065 break;
2066
2067 case Builtin::BI__sync_fetch_and_and:
2068 case Builtin::BI__sync_fetch_and_and_1:
2069 case Builtin::BI__sync_fetch_and_and_2:
2070 case Builtin::BI__sync_fetch_and_and_4:
2071 case Builtin::BI__sync_fetch_and_and_8:
2072 case Builtin::BI__sync_fetch_and_and_16:
2073 BuiltinIndex = 3;
2074 break;
Mike Stump11289f42009-09-09 15:08:12 +00002075
Douglas Gregor73722482011-11-28 16:30:08 +00002076 case Builtin::BI__sync_fetch_and_xor:
2077 case Builtin::BI__sync_fetch_and_xor_1:
2078 case Builtin::BI__sync_fetch_and_xor_2:
2079 case Builtin::BI__sync_fetch_and_xor_4:
2080 case Builtin::BI__sync_fetch_and_xor_8:
2081 case Builtin::BI__sync_fetch_and_xor_16:
2082 BuiltinIndex = 4;
2083 break;
2084
Hal Finkeld2208b52014-10-02 20:53:50 +00002085 case Builtin::BI__sync_fetch_and_nand:
2086 case Builtin::BI__sync_fetch_and_nand_1:
2087 case Builtin::BI__sync_fetch_and_nand_2:
2088 case Builtin::BI__sync_fetch_and_nand_4:
2089 case Builtin::BI__sync_fetch_and_nand_8:
2090 case Builtin::BI__sync_fetch_and_nand_16:
2091 BuiltinIndex = 5;
2092 WarnAboutSemanticsChange = true;
2093 break;
2094
Douglas Gregor73722482011-11-28 16:30:08 +00002095 case Builtin::BI__sync_add_and_fetch:
2096 case Builtin::BI__sync_add_and_fetch_1:
2097 case Builtin::BI__sync_add_and_fetch_2:
2098 case Builtin::BI__sync_add_and_fetch_4:
2099 case Builtin::BI__sync_add_and_fetch_8:
2100 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002101 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002102 break;
2103
2104 case Builtin::BI__sync_sub_and_fetch:
2105 case Builtin::BI__sync_sub_and_fetch_1:
2106 case Builtin::BI__sync_sub_and_fetch_2:
2107 case Builtin::BI__sync_sub_and_fetch_4:
2108 case Builtin::BI__sync_sub_and_fetch_8:
2109 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002110 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002111 break;
2112
2113 case Builtin::BI__sync_and_and_fetch:
2114 case Builtin::BI__sync_and_and_fetch_1:
2115 case Builtin::BI__sync_and_and_fetch_2:
2116 case Builtin::BI__sync_and_and_fetch_4:
2117 case Builtin::BI__sync_and_and_fetch_8:
2118 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002119 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002120 break;
2121
2122 case Builtin::BI__sync_or_and_fetch:
2123 case Builtin::BI__sync_or_and_fetch_1:
2124 case Builtin::BI__sync_or_and_fetch_2:
2125 case Builtin::BI__sync_or_and_fetch_4:
2126 case Builtin::BI__sync_or_and_fetch_8:
2127 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002128 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002129 break;
2130
2131 case Builtin::BI__sync_xor_and_fetch:
2132 case Builtin::BI__sync_xor_and_fetch_1:
2133 case Builtin::BI__sync_xor_and_fetch_2:
2134 case Builtin::BI__sync_xor_and_fetch_4:
2135 case Builtin::BI__sync_xor_and_fetch_8:
2136 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002137 BuiltinIndex = 10;
2138 break;
2139
2140 case Builtin::BI__sync_nand_and_fetch:
2141 case Builtin::BI__sync_nand_and_fetch_1:
2142 case Builtin::BI__sync_nand_and_fetch_2:
2143 case Builtin::BI__sync_nand_and_fetch_4:
2144 case Builtin::BI__sync_nand_and_fetch_8:
2145 case Builtin::BI__sync_nand_and_fetch_16:
2146 BuiltinIndex = 11;
2147 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002148 break;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Chris Lattnerdc046542009-05-08 06:58:22 +00002150 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002151 case Builtin::BI__sync_val_compare_and_swap_1:
2152 case Builtin::BI__sync_val_compare_and_swap_2:
2153 case Builtin::BI__sync_val_compare_and_swap_4:
2154 case Builtin::BI__sync_val_compare_and_swap_8:
2155 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002156 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002157 NumFixed = 2;
2158 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002159
Chris Lattnerdc046542009-05-08 06:58:22 +00002160 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002161 case Builtin::BI__sync_bool_compare_and_swap_1:
2162 case Builtin::BI__sync_bool_compare_and_swap_2:
2163 case Builtin::BI__sync_bool_compare_and_swap_4:
2164 case Builtin::BI__sync_bool_compare_and_swap_8:
2165 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002166 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002167 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002168 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002169 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002170
2171 case Builtin::BI__sync_lock_test_and_set:
2172 case Builtin::BI__sync_lock_test_and_set_1:
2173 case Builtin::BI__sync_lock_test_and_set_2:
2174 case Builtin::BI__sync_lock_test_and_set_4:
2175 case Builtin::BI__sync_lock_test_and_set_8:
2176 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002177 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002178 break;
2179
Chris Lattnerdc046542009-05-08 06:58:22 +00002180 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002181 case Builtin::BI__sync_lock_release_1:
2182 case Builtin::BI__sync_lock_release_2:
2183 case Builtin::BI__sync_lock_release_4:
2184 case Builtin::BI__sync_lock_release_8:
2185 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002186 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002187 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002188 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002189 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002190
2191 case Builtin::BI__sync_swap:
2192 case Builtin::BI__sync_swap_1:
2193 case Builtin::BI__sync_swap_2:
2194 case Builtin::BI__sync_swap_4:
2195 case Builtin::BI__sync_swap_8:
2196 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002197 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002198 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002199 }
Mike Stump11289f42009-09-09 15:08:12 +00002200
Chris Lattnerdc046542009-05-08 06:58:22 +00002201 // Now that we know how many fixed arguments we expect, first check that we
2202 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002203 if (TheCall->getNumArgs() < 1+NumFixed) {
2204 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2205 << 0 << 1+NumFixed << TheCall->getNumArgs()
2206 << TheCall->getCallee()->getSourceRange();
2207 return ExprError();
2208 }
Mike Stump11289f42009-09-09 15:08:12 +00002209
Hal Finkeld2208b52014-10-02 20:53:50 +00002210 if (WarnAboutSemanticsChange) {
2211 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2212 << TheCall->getCallee()->getSourceRange();
2213 }
2214
Chris Lattner5b9241b2009-05-08 15:36:58 +00002215 // Get the decl for the concrete builtin from this, we can tell what the
2216 // concrete integer type we should convert to is.
2217 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
Eric Christopher02d5d862015-08-06 01:01:12 +00002218 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002219 FunctionDecl *NewBuiltinDecl;
2220 if (NewBuiltinID == BuiltinID)
2221 NewBuiltinDecl = FDecl;
2222 else {
2223 // Perform builtin lookup to avoid redeclaring it.
2224 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2225 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2226 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2227 assert(Res.getFoundDecl());
2228 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002229 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002230 return ExprError();
2231 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002232
John McCallcf142162010-08-07 06:22:56 +00002233 // The first argument --- the pointer --- has a fixed type; we
2234 // deduce the types of the rest of the arguments accordingly. Walk
2235 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002236 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002237 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002238
Chris Lattnerdc046542009-05-08 06:58:22 +00002239 // GCC does an implicit conversion to the pointer or integer ValType. This
2240 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002241 // Initialize the argument.
2242 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2243 ValType, /*consume*/ false);
2244 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002245 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002246 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002247
Chris Lattnerdc046542009-05-08 06:58:22 +00002248 // Okay, we have something that *can* be converted to the right type. Check
2249 // to see if there is a potentially weird extension going on here. This can
2250 // happen when you do an atomic operation on something like an char* and
2251 // pass in 42. The 42 gets converted to char. This is even more strange
2252 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002253 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002254 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002255 }
Mike Stump11289f42009-09-09 15:08:12 +00002256
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002257 ASTContext& Context = this->getASTContext();
2258
2259 // Create a new DeclRefExpr to refer to the new decl.
2260 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2261 Context,
2262 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002263 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002264 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002265 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002266 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002267 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002268 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002269
Chris Lattnerdc046542009-05-08 06:58:22 +00002270 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002271 // FIXME: This loses syntactic information.
2272 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2273 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2274 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002275 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002276
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002277 // Change the result type of the call to match the original value type. This
2278 // is arbitrary, but the codegen for these builtins ins design to handle it
2279 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002280 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002281
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002282 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002283}
2284
Michael Zolotukhin84df1232015-09-08 23:52:33 +00002285/// SemaBuiltinNontemporalOverloaded - We have a call to
2286/// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2287/// overloaded function based on the pointer type of its last argument.
2288///
2289/// This function goes through and does final semantic checking for these
2290/// builtins.
2291ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2292 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2293 DeclRefExpr *DRE =
2294 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2295 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2296 unsigned BuiltinID = FDecl->getBuiltinID();
2297 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2298 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2299 "Unexpected nontemporal load/store builtin!");
2300 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2301 unsigned numArgs = isStore ? 2 : 1;
2302
2303 // Ensure that we have the proper number of arguments.
2304 if (checkArgCount(*this, TheCall, numArgs))
2305 return ExprError();
2306
2307 // Inspect the last argument of the nontemporal builtin. This should always
2308 // be a pointer type, from which we imply the type of the memory access.
2309 // Because it is a pointer type, we don't have to worry about any implicit
2310 // casts here.
2311 Expr *PointerArg = TheCall->getArg(numArgs - 1);
2312 ExprResult PointerArgResult =
2313 DefaultFunctionArrayLvalueConversion(PointerArg);
2314
2315 if (PointerArgResult.isInvalid())
2316 return ExprError();
2317 PointerArg = PointerArgResult.get();
2318 TheCall->setArg(numArgs - 1, PointerArg);
2319
2320 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2321 if (!pointerType) {
2322 Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2323 << PointerArg->getType() << PointerArg->getSourceRange();
2324 return ExprError();
2325 }
2326
2327 QualType ValType = pointerType->getPointeeType();
2328
2329 // Strip any qualifiers off ValType.
2330 ValType = ValType.getUnqualifiedType();
2331 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2332 !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2333 !ValType->isVectorType()) {
2334 Diag(DRE->getLocStart(),
2335 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2336 << PointerArg->getType() << PointerArg->getSourceRange();
2337 return ExprError();
2338 }
2339
2340 if (!isStore) {
2341 TheCall->setType(ValType);
2342 return TheCallResult;
2343 }
2344
2345 ExprResult ValArg = TheCall->getArg(0);
2346 InitializedEntity Entity = InitializedEntity::InitializeParameter(
2347 Context, ValType, /*consume*/ false);
2348 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2349 if (ValArg.isInvalid())
2350 return ExprError();
2351
2352 TheCall->setArg(0, ValArg.get());
2353 TheCall->setType(Context.VoidTy);
2354 return TheCallResult;
2355}
2356
Chris Lattner6436fb62009-02-18 06:01:06 +00002357/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002358/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002359/// Note: It might also make sense to do the UTF-16 conversion here (would
2360/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002361bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002362 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002363 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2364
Douglas Gregorfb65e592011-07-27 05:40:30 +00002365 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002366 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2367 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002368 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002369 }
Mike Stump11289f42009-09-09 15:08:12 +00002370
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002371 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002372 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002373 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002374 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002375 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002376 UTF16 *ToPtr = &ToBuf[0];
2377
2378 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2379 &ToPtr, ToPtr + NumBytes,
2380 strictConversion);
2381 // Check for conversion failure.
2382 if (Result != conversionOK)
2383 Diag(Arg->getLocStart(),
2384 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2385 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002386 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002387}
2388
Charles Davisc7d5c942015-09-17 20:55:33 +00002389/// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2390/// for validity. Emit an error and return true on failure; return false
2391/// on success.
2392bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
Chris Lattner08464942007-12-28 05:29:59 +00002393 Expr *Fn = TheCall->getCallee();
2394 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002395 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002396 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002397 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2398 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002399 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002400 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002401 return true;
2402 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002403
2404 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002405 return Diag(TheCall->getLocEnd(),
2406 diag::err_typecheck_call_too_few_args_at_least)
2407 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002408 }
2409
John McCall29ad95b2011-08-27 01:09:30 +00002410 // Type-check the first argument normally.
2411 if (checkBuiltinArgument(*this, TheCall, 0))
2412 return true;
2413
Chris Lattnere202e6a2007-12-20 00:05:45 +00002414 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002415 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002416 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002417 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002418 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002419 else if (FunctionDecl *FD = getCurFunctionDecl())
2420 isVariadic = FD->isVariadic();
2421 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002422 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002423
Chris Lattnere202e6a2007-12-20 00:05:45 +00002424 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002425 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2426 return true;
2427 }
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattner43be2e62007-12-19 23:59:04 +00002429 // Verify that the second argument to the builtin is the last argument of the
2430 // current function or method.
2431 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002432 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002433
Nico Weber9eea7642013-05-24 23:31:57 +00002434 // These are valid if SecondArgIsLastNamedArgument is false after the next
2435 // block.
2436 QualType Type;
2437 SourceLocation ParamLoc;
2438
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002439 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2440 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002441 // FIXME: This isn't correct for methods (results in bogus warning).
2442 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002443 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002444 if (CurBlock)
2445 LastArg = *(CurBlock->TheDecl->param_end()-1);
2446 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002447 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002448 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002449 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002450 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002451
2452 Type = PV->getType();
2453 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002454 }
2455 }
Mike Stump11289f42009-09-09 15:08:12 +00002456
Chris Lattner43be2e62007-12-19 23:59:04 +00002457 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002458 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002459 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002460 else if (Type->isReferenceType()) {
2461 Diag(Arg->getLocStart(),
2462 diag::warn_va_start_of_reference_type_is_undefined);
2463 Diag(ParamLoc, diag::note_parameter_type) << Type;
2464 }
2465
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002466 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002467 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002468}
Chris Lattner43be2e62007-12-19 23:59:04 +00002469
Charles Davisc7d5c942015-09-17 20:55:33 +00002470/// Check the arguments to '__builtin_va_start' for validity, and that
2471/// it was called from a function of the native ABI.
2472/// Emit an error and return true on failure; return false on success.
2473bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2474 // On x86-64 Unix, don't allow this in Win64 ABI functions.
2475 // On x64 Windows, don't allow this in System V ABI functions.
2476 // (Yes, that means there's no corresponding way to support variadic
2477 // System V ABI functions on Windows.)
2478 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2479 unsigned OS = Context.getTargetInfo().getTriple().getOS();
2480 clang::CallingConv CC = CC_C;
2481 if (const FunctionDecl *FD = getCurFunctionDecl())
2482 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2483 if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2484 (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2485 return Diag(TheCall->getCallee()->getLocStart(),
2486 diag::err_va_start_used_in_wrong_abi_function)
2487 << (OS != llvm::Triple::Win32);
2488 }
2489 return SemaBuiltinVAStartImpl(TheCall);
2490}
2491
2492/// Check the arguments to '__builtin_ms_va_start' for validity, and that
2493/// it was called from a Win64 ABI function.
2494/// Emit an error and return true on failure; return false on success.
2495bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2496 // This only makes sense for x86-64.
2497 const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2498 Expr *Callee = TheCall->getCallee();
2499 if (TT.getArch() != llvm::Triple::x86_64)
2500 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2501 // Don't allow this in System V ABI functions.
2502 clang::CallingConv CC = CC_C;
2503 if (const FunctionDecl *FD = getCurFunctionDecl())
2504 CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2505 if (CC == CC_X86_64SysV ||
2506 (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2507 return Diag(Callee->getLocStart(),
2508 diag::err_ms_va_start_used_in_sysv_function);
2509 return SemaBuiltinVAStartImpl(TheCall);
2510}
2511
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002512bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2513 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2514 // const char *named_addr);
2515
2516 Expr *Func = Call->getCallee();
2517
2518 if (Call->getNumArgs() < 3)
2519 return Diag(Call->getLocEnd(),
2520 diag::err_typecheck_call_too_few_args_at_least)
2521 << 0 /*function call*/ << 3 << Call->getNumArgs();
2522
2523 // Determine whether the current function is variadic or not.
2524 bool IsVariadic;
2525 if (BlockScopeInfo *CurBlock = getCurBlock())
2526 IsVariadic = CurBlock->TheDecl->isVariadic();
2527 else if (FunctionDecl *FD = getCurFunctionDecl())
2528 IsVariadic = FD->isVariadic();
2529 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2530 IsVariadic = MD->isVariadic();
2531 else
2532 llvm_unreachable("unexpected statement type");
2533
2534 if (!IsVariadic) {
2535 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2536 return true;
2537 }
2538
2539 // Type-check the first argument normally.
2540 if (checkBuiltinArgument(*this, Call, 0))
2541 return true;
2542
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002543 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002544 unsigned ArgNo;
2545 QualType Type;
2546 } ArgumentTypes[] = {
2547 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2548 { 2, Context.getSizeType() },
2549 };
2550
2551 for (const auto &AT : ArgumentTypes) {
2552 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2553 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2554 continue;
2555 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2556 << Arg->getType() << AT.Type << 1 /* different class */
2557 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2558 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2559 }
2560
2561 return false;
2562}
2563
Chris Lattner2da14fb2007-12-20 00:26:33 +00002564/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2565/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002566bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2567 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002568 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002569 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002570 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002571 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002572 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002573 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002574 << SourceRange(TheCall->getArg(2)->getLocStart(),
2575 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002576
John Wiegley01296292011-04-08 18:41:53 +00002577 ExprResult OrigArg0 = TheCall->getArg(0);
2578 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002579
Chris Lattner2da14fb2007-12-20 00:26:33 +00002580 // Do standard promotions between the two arguments, returning their common
2581 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002582 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002583 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2584 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002585
2586 // Make sure any conversions are pushed back into the call; this is
2587 // type safe since unordered compare builtins are declared as "_Bool
2588 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002589 TheCall->setArg(0, OrigArg0.get());
2590 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002591
John Wiegley01296292011-04-08 18:41:53 +00002592 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002593 return false;
2594
Chris Lattner2da14fb2007-12-20 00:26:33 +00002595 // If the common type isn't a real floating type, then the arguments were
2596 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002597 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002598 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002599 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002600 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2601 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002602
Chris Lattner2da14fb2007-12-20 00:26:33 +00002603 return false;
2604}
2605
Benjamin Kramer634fc102010-02-15 22:42:31 +00002606/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2607/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002608/// to check everything. We expect the last argument to be a floating point
2609/// value.
2610bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2611 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002612 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002613 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002614 if (TheCall->getNumArgs() > NumArgs)
2615 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002616 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002617 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002618 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002619 (*(TheCall->arg_end()-1))->getLocEnd());
2620
Benjamin Kramer64aae502010-02-16 10:07:31 +00002621 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002622
Eli Friedman7e4faac2009-08-31 20:06:00 +00002623 if (OrigArg->isTypeDependent())
2624 return false;
2625
Chris Lattner68784ef2010-05-06 05:50:07 +00002626 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002627 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002628 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002629 diag::err_typecheck_call_invalid_unary_fp)
2630 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002631
Chris Lattner68784ef2010-05-06 05:50:07 +00002632 // If this is an implicit conversion from float -> double, remove it.
2633 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2634 Expr *CastArg = Cast->getSubExpr();
2635 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2636 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2637 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002638 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002639 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002640 }
2641 }
2642
Eli Friedman7e4faac2009-08-31 20:06:00 +00002643 return false;
2644}
2645
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002646/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2647// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002648ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002649 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002650 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002651 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002652 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2653 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002654
Nate Begemana0110022010-06-08 00:16:34 +00002655 // Determine which of the following types of shufflevector we're checking:
2656 // 1) unary, vector mask: (lhs, mask)
2657 // 2) binary, vector mask: (lhs, rhs, mask)
2658 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2659 QualType resType = TheCall->getArg(0)->getType();
2660 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002661
Douglas Gregorc25f7662009-05-19 22:10:17 +00002662 if (!TheCall->getArg(0)->isTypeDependent() &&
2663 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002664 QualType LHSType = TheCall->getArg(0)->getType();
2665 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002666
Craig Topperbaca3892013-07-29 06:47:04 +00002667 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2668 return ExprError(Diag(TheCall->getLocStart(),
2669 diag::err_shufflevector_non_vector)
2670 << SourceRange(TheCall->getArg(0)->getLocStart(),
2671 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002672
Nate Begemana0110022010-06-08 00:16:34 +00002673 numElements = LHSType->getAs<VectorType>()->getNumElements();
2674 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002675
Nate Begemana0110022010-06-08 00:16:34 +00002676 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2677 // with mask. If so, verify that RHS is an integer vector type with the
2678 // same number of elts as lhs.
2679 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002680 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002681 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002682 return ExprError(Diag(TheCall->getLocStart(),
2683 diag::err_shufflevector_incompatible_vector)
2684 << SourceRange(TheCall->getArg(1)->getLocStart(),
2685 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002686 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002687 return ExprError(Diag(TheCall->getLocStart(),
2688 diag::err_shufflevector_incompatible_vector)
2689 << SourceRange(TheCall->getArg(0)->getLocStart(),
2690 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002691 } else if (numElements != numResElements) {
2692 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002693 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002694 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002695 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002696 }
2697
2698 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002699 if (TheCall->getArg(i)->isTypeDependent() ||
2700 TheCall->getArg(i)->isValueDependent())
2701 continue;
2702
Nate Begemana0110022010-06-08 00:16:34 +00002703 llvm::APSInt Result(32);
2704 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2705 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002706 diag::err_shufflevector_nonconstant_argument)
2707 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002708
Craig Topper50ad5b72013-08-03 17:40:38 +00002709 // Allow -1 which will be translated to undef in the IR.
2710 if (Result.isSigned() && Result.isAllOnesValue())
2711 continue;
2712
Chris Lattner7ab824e2008-08-10 02:05:13 +00002713 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002714 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002715 diag::err_shufflevector_argument_too_large)
2716 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002717 }
2718
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002719 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002720
Chris Lattner7ab824e2008-08-10 02:05:13 +00002721 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002722 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002723 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002724 }
2725
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002726 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2727 TheCall->getCallee()->getLocStart(),
2728 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002729}
Chris Lattner43be2e62007-12-19 23:59:04 +00002730
Hal Finkelc4d7c822013-09-18 03:29:45 +00002731/// SemaConvertVectorExpr - Handle __builtin_convertvector
2732ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2733 SourceLocation BuiltinLoc,
2734 SourceLocation RParenLoc) {
2735 ExprValueKind VK = VK_RValue;
2736 ExprObjectKind OK = OK_Ordinary;
2737 QualType DstTy = TInfo->getType();
2738 QualType SrcTy = E->getType();
2739
2740 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2741 return ExprError(Diag(BuiltinLoc,
2742 diag::err_convertvector_non_vector)
2743 << E->getSourceRange());
2744 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2745 return ExprError(Diag(BuiltinLoc,
2746 diag::err_convertvector_non_vector_type));
2747
2748 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2749 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2750 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2751 if (SrcElts != DstElts)
2752 return ExprError(Diag(BuiltinLoc,
2753 diag::err_convertvector_incompatible_vector)
2754 << E->getSourceRange());
2755 }
2756
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002757 return new (Context)
2758 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002759}
2760
Daniel Dunbarb7257262008-07-21 22:59:13 +00002761/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2762// This is declared to take (const void*, ...) and can take two
2763// optional constant int args.
2764bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002765 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002766
Chris Lattner3b054132008-11-19 05:08:23 +00002767 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002768 return Diag(TheCall->getLocEnd(),
2769 diag::err_typecheck_call_too_many_args_at_most)
2770 << 0 /*function call*/ << 3 << NumArgs
2771 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002772
2773 // Argument 0 is checked for us and the remaining arguments must be
2774 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002775 for (unsigned i = 1; i != NumArgs; ++i)
2776 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002777 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002778
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002779 return false;
2780}
2781
Hal Finkelf0417332014-07-17 14:25:55 +00002782/// SemaBuiltinAssume - Handle __assume (MS Extension).
2783// __assume does not evaluate its arguments, and should warn if its argument
2784// has side effects.
2785bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2786 Expr *Arg = TheCall->getArg(0);
2787 if (Arg->isInstantiationDependent()) return false;
2788
2789 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002790 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002791 << Arg->getSourceRange()
2792 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2793
2794 return false;
2795}
2796
2797/// Handle __builtin_assume_aligned. This is declared
2798/// as (const void*, size_t, ...) and can take one optional constant int arg.
2799bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2800 unsigned NumArgs = TheCall->getNumArgs();
2801
2802 if (NumArgs > 3)
2803 return Diag(TheCall->getLocEnd(),
2804 diag::err_typecheck_call_too_many_args_at_most)
2805 << 0 /*function call*/ << 3 << NumArgs
2806 << TheCall->getSourceRange();
2807
2808 // The alignment must be a constant integer.
2809 Expr *Arg = TheCall->getArg(1);
2810
2811 // We can't check the value of a dependent argument.
2812 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2813 llvm::APSInt Result;
2814 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2815 return true;
2816
2817 if (!Result.isPowerOf2())
2818 return Diag(TheCall->getLocStart(),
2819 diag::err_alignment_not_power_of_two)
2820 << Arg->getSourceRange();
2821 }
2822
2823 if (NumArgs > 2) {
2824 ExprResult Arg(TheCall->getArg(2));
2825 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2826 Context.getSizeType(), false);
2827 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2828 if (Arg.isInvalid()) return true;
2829 TheCall->setArg(2, Arg.get());
2830 }
Hal Finkelf0417332014-07-17 14:25:55 +00002831
2832 return false;
2833}
2834
Eric Christopher8d0c6212010-04-17 02:26:23 +00002835/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2836/// TheCall is a constant expression.
2837bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2838 llvm::APSInt &Result) {
2839 Expr *Arg = TheCall->getArg(ArgNum);
2840 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2841 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2842
2843 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2844
2845 if (!Arg->isIntegerConstantExpr(Result, Context))
2846 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002847 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002848
Chris Lattnerd545ad12009-09-23 06:06:36 +00002849 return false;
2850}
2851
Richard Sandiford28940af2014-04-16 08:47:51 +00002852/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2853/// TheCall is a constant expression in the range [Low, High].
2854bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2855 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002856 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002857
2858 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002859 Expr *Arg = TheCall->getArg(ArgNum);
2860 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002861 return false;
2862
Eric Christopher8d0c6212010-04-17 02:26:23 +00002863 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002864 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002865 return true;
2866
Richard Sandiford28940af2014-04-16 08:47:51 +00002867 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002868 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002869 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002870
2871 return false;
2872}
2873
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002874/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2875/// TheCall is an ARM/AArch64 special register string literal.
2876bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2877 int ArgNum, unsigned ExpectedFieldNum,
2878 bool AllowName) {
2879 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2880 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2881 BuiltinID == ARM::BI__builtin_arm_rsr ||
2882 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2883 BuiltinID == ARM::BI__builtin_arm_wsr ||
2884 BuiltinID == ARM::BI__builtin_arm_wsrp;
2885 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2886 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2887 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2888 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2889 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2890 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2891 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2892
2893 // We can't check the value of a dependent argument.
2894 Expr *Arg = TheCall->getArg(ArgNum);
2895 if (Arg->isTypeDependent() || Arg->isValueDependent())
2896 return false;
2897
2898 // Check if the argument is a string literal.
2899 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2900 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2901 << Arg->getSourceRange();
2902
2903 // Check the type of special register given.
2904 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2905 SmallVector<StringRef, 6> Fields;
2906 Reg.split(Fields, ":");
2907
2908 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2909 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2910 << Arg->getSourceRange();
2911
2912 // If the string is the name of a register then we cannot check that it is
2913 // valid here but if the string is of one the forms described in ACLE then we
2914 // can check that the supplied fields are integers and within the valid
2915 // ranges.
2916 if (Fields.size() > 1) {
2917 bool FiveFields = Fields.size() == 5;
2918
2919 bool ValidString = true;
2920 if (IsARMBuiltin) {
2921 ValidString &= Fields[0].startswith_lower("cp") ||
2922 Fields[0].startswith_lower("p");
2923 if (ValidString)
2924 Fields[0] =
2925 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2926
2927 ValidString &= Fields[2].startswith_lower("c");
2928 if (ValidString)
2929 Fields[2] = Fields[2].drop_front(1);
2930
2931 if (FiveFields) {
2932 ValidString &= Fields[3].startswith_lower("c");
2933 if (ValidString)
2934 Fields[3] = Fields[3].drop_front(1);
2935 }
2936 }
2937
2938 SmallVector<int, 5> Ranges;
2939 if (FiveFields)
2940 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2941 else
2942 Ranges.append({15, 7, 15});
2943
2944 for (unsigned i=0; i<Fields.size(); ++i) {
2945 int IntField;
2946 ValidString &= !Fields[i].getAsInteger(10, IntField);
2947 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2948 }
2949
2950 if (!ValidString)
2951 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2952 << Arg->getSourceRange();
2953
2954 } else if (IsAArch64Builtin && Fields.size() == 1) {
2955 // If the register name is one of those that appear in the condition below
2956 // and the special register builtin being used is one of the write builtins,
2957 // then we require that the argument provided for writing to the register
2958 // is an integer constant expression. This is because it will be lowered to
2959 // an MSR (immediate) instruction, so we need to know the immediate at
2960 // compile time.
2961 if (TheCall->getNumArgs() != 2)
2962 return false;
2963
2964 std::string RegLower = Reg.lower();
2965 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2966 RegLower != "pan" && RegLower != "uao")
2967 return false;
2968
2969 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2970 }
2971
2972 return false;
2973}
2974
Eli Friedmanc97d0142009-05-03 06:04:26 +00002975/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002976/// This checks that the target supports __builtin_longjmp and
2977/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002978bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002979 if (!Context.getTargetInfo().hasSjLjLowering())
2980 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2981 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2982
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002983 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002984 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002985
Eric Christopher8d0c6212010-04-17 02:26:23 +00002986 // TODO: This is less than ideal. Overload this to take a value.
2987 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2988 return true;
2989
2990 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002991 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2992 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2993
2994 return false;
2995}
2996
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002997
2998/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2999/// This checks that the target supports __builtin_setjmp.
3000bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3001 if (!Context.getTargetInfo().hasSjLjLowering())
3002 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3003 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3004 return false;
3005}
3006
Richard Smithd7293d72013-08-05 18:49:43 +00003007namespace {
3008enum StringLiteralCheckType {
3009 SLCT_NotALiteral,
3010 SLCT_UncheckedLiteral,
3011 SLCT_CheckedLiteral
3012};
3013}
3014
Richard Smith55ce3522012-06-25 20:30:08 +00003015// Determine if an expression is a string literal or constant string.
3016// If this function returns false on the arguments to a function expecting a
3017// format string, we will usually need to emit a warning.
3018// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00003019static StringLiteralCheckType
3020checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3021 bool HasVAListArg, unsigned format_idx,
3022 unsigned firstDataArg, Sema::FormatStringType Type,
3023 Sema::VariadicCallType CallType, bool InFunctionCall,
3024 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00003025 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00003026 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00003027 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003028
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003029 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00003030
Richard Smithd7293d72013-08-05 18:49:43 +00003031 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00003032 // Technically -Wformat-nonliteral does not warn about this case.
3033 // The behavior of printf and friends in this case is implementation
3034 // dependent. Ideally if the format string cannot be null then
3035 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00003036 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00003037
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003038 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00003039 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003040 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00003041 // The expression is a literal if both sub-expressions were, and it was
3042 // completely checked only if both sub-expressions were checked.
3043 const AbstractConditionalOperator *C =
3044 cast<AbstractConditionalOperator>(E);
3045 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00003046 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003047 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003048 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003049 if (Left == SLCT_NotALiteral)
3050 return SLCT_NotALiteral;
3051 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00003052 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003053 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003054 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003055 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003056 }
3057
3058 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00003059 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3060 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003061 }
3062
John McCallc07a0c72011-02-17 10:25:35 +00003063 case Stmt::OpaqueValueExprClass:
3064 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3065 E = src;
3066 goto tryAgain;
3067 }
Richard Smith55ce3522012-06-25 20:30:08 +00003068 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00003069
Ted Kremeneka8890832011-02-24 23:03:04 +00003070 case Stmt::PredefinedExprClass:
3071 // While __func__, etc., are technically not string literals, they
3072 // cannot contain format specifiers and thus are not a security
3073 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00003074 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00003075
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003076 case Stmt::DeclRefExprClass: {
3077 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003078
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003079 // As an exception, do not flag errors for variables binding to
3080 // const string literals.
3081 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3082 bool isConstant = false;
3083 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003084
Richard Smithd7293d72013-08-05 18:49:43 +00003085 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3086 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00003087 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00003088 isConstant = T.isConstant(S.Context) &&
3089 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00003090 } else if (T->isObjCObjectPointerType()) {
3091 // In ObjC, there is usually no "const ObjectPointer" type,
3092 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00003093 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003094 }
Mike Stump11289f42009-09-09 15:08:12 +00003095
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003096 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003097 if (const Expr *Init = VD->getAnyInitializer()) {
3098 // Look through initializers like const char c[] = { "foo" }
3099 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3100 if (InitList->isStringLiteralInit())
3101 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3102 }
Richard Smithd7293d72013-08-05 18:49:43 +00003103 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003104 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003105 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003106 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00003107 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003108 }
Mike Stump11289f42009-09-09 15:08:12 +00003109
Anders Carlssonb012ca92009-06-28 19:55:58 +00003110 // For vprintf* functions (i.e., HasVAListArg==true), we add a
3111 // special check to see if the format string is a function parameter
3112 // of the function calling the printf function. If the function
3113 // has an attribute indicating it is a printf-like function, then we
3114 // should suppress warnings concerning non-literals being used in a call
3115 // to a vprintf function. For example:
3116 //
3117 // void
3118 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3119 // va_list ap;
3120 // va_start(ap, fmt);
3121 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
3122 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00003123 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003124 if (HasVAListArg) {
3125 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3126 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3127 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00003128 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003129 // adjust for implicit parameter
3130 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3131 if (MD->isInstance())
3132 ++PVIndex;
3133 // We also check if the formats are compatible.
3134 // We can't pass a 'scanf' string to a 'printf' function.
3135 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00003136 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00003137 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00003138 }
3139 }
3140 }
3141 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003142 }
Mike Stump11289f42009-09-09 15:08:12 +00003143
Richard Smith55ce3522012-06-25 20:30:08 +00003144 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003145 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003146
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003147 case Stmt::CallExprClass:
3148 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003149 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00003150 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3151 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3152 unsigned ArgIndex = FA->getFormatIdx();
3153 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3154 if (MD->isInstance())
3155 --ArgIndex;
3156 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Richard Smithd7293d72013-08-05 18:49:43 +00003158 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003159 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00003160 Type, CallType, InFunctionCall,
3161 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003162 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3163 unsigned BuiltinID = FD->getBuiltinID();
3164 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3165 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3166 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00003167 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00003168 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003169 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003170 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003171 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003172 }
3173 }
Mike Stump11289f42009-09-09 15:08:12 +00003174
Richard Smith55ce3522012-06-25 20:30:08 +00003175 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00003176 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003177 case Stmt::ObjCStringLiteralClass:
3178 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00003179 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00003180
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003181 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003182 StrE = ObjCFExpr->getString();
3183 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003184 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00003185
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003186 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00003187 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
3188 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003189 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003190 }
Mike Stump11289f42009-09-09 15:08:12 +00003191
Richard Smith55ce3522012-06-25 20:30:08 +00003192 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003193 }
Mike Stump11289f42009-09-09 15:08:12 +00003194
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003195 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003196 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003197 }
3198}
3199
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003200Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003201 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003202 .Case("scanf", FST_Scanf)
3203 .Cases("printf", "printf0", FST_Printf)
3204 .Cases("NSString", "CFString", FST_NSString)
3205 .Case("strftime", FST_Strftime)
3206 .Case("strfmon", FST_Strfmon)
3207 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003208 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003209 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003210 .Default(FST_Unknown);
3211}
3212
Jordan Rose3e0ec582012-07-19 18:10:23 +00003213/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003214/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003215/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003216bool Sema::CheckFormatArguments(const FormatAttr *Format,
3217 ArrayRef<const Expr *> Args,
3218 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003219 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003220 SourceLocation Loc, SourceRange Range,
3221 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003222 FormatStringInfo FSI;
3223 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003224 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003225 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003226 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003227 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003228}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003229
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003230bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003231 bool HasVAListArg, unsigned format_idx,
3232 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003233 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003234 SourceLocation Loc, SourceRange Range,
3235 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003236 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003237 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003238 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003239 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003242 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003243
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003244 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003245 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003246 // Dynamically generated format strings are difficult to
3247 // automatically vet at compile time. Requiring that format strings
3248 // are string literals: (1) permits the checking of format strings by
3249 // the compiler and thereby (2) can practically remove the source of
3250 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003251
Mike Stump11289f42009-09-09 15:08:12 +00003252 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003253 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003254 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003255 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003256 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003257 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3258 format_idx, firstDataArg, Type, CallType,
3259 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003260 if (CT != SLCT_NotALiteral)
3261 // Literal format string found, check done!
3262 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003263
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003264 // Strftime is particular as it always uses a single 'time' argument,
3265 // so it is safe to pass a non-literal string.
3266 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003267 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003268
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003269 // Do not emit diag when the string param is a macro expansion and the
3270 // format is either NSString or CFString. This is a hack to prevent
3271 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3272 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003273 if (Type == FST_NSString &&
3274 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003275 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003276
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003277 // If there are no arguments specified, warn with -Wformat-security, otherwise
3278 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003279 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003280 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003281 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003282 << OrigFormatExpr->getSourceRange();
3283 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003284 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003285 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003286 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003287 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003288}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003289
Ted Kremenekab278de2010-01-28 23:39:18 +00003290namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003291class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3292protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003293 Sema &S;
3294 const StringLiteral *FExpr;
3295 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003296 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003297 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003298 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003299 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003300 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003301 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003302 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003303 bool usesPositionalArgs;
3304 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003305 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003306 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003307 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003308public:
Ted Kremenek02087932010-07-16 02:11:22 +00003309 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003310 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003311 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003312 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003313 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003314 Sema::VariadicCallType callType,
3315 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003316 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003317 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3318 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003319 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003320 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003321 inFunctionCall(inFunctionCall), CallType(callType),
3322 CheckedVarArgs(CheckedVarArgs) {
3323 CoveredArgs.resize(numDataArgs);
3324 CoveredArgs.reset();
3325 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003326
Ted Kremenek019d2242010-01-29 01:50:07 +00003327 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003328
Ted Kremenek02087932010-07-16 02:11:22 +00003329 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003330 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003331
Jordan Rose92303592012-09-08 04:00:03 +00003332 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003333 const analyze_format_string::FormatSpecifier &FS,
3334 const analyze_format_string::ConversionSpecifier &CS,
3335 const char *startSpecifier, unsigned specifierLen,
3336 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003337
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003338 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003339 const analyze_format_string::FormatSpecifier &FS,
3340 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003341
3342 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003343 const analyze_format_string::ConversionSpecifier &CS,
3344 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003345
Craig Toppere14c0f82014-03-12 04:55:44 +00003346 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003347
Craig Toppere14c0f82014-03-12 04:55:44 +00003348 void HandleInvalidPosition(const char *startSpecifier,
3349 unsigned specifierLen,
3350 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003351
Craig Toppere14c0f82014-03-12 04:55:44 +00003352 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003353
Craig Toppere14c0f82014-03-12 04:55:44 +00003354 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003355
Richard Trieu03cf7b72011-10-28 00:41:25 +00003356 template <typename Range>
3357 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3358 const Expr *ArgumentExpr,
3359 PartialDiagnostic PDiag,
3360 SourceLocation StringLoc,
3361 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003362 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003363
Ted Kremenek02087932010-07-16 02:11:22 +00003364protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003365 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3366 const char *startSpec,
3367 unsigned specifierLen,
3368 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003369
3370 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3371 const char *startSpec,
3372 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003373
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003374 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003375 CharSourceRange getSpecifierRange(const char *startSpecifier,
3376 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003377 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003378
Ted Kremenek5739de72010-01-29 01:06:55 +00003379 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003380
3381 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3382 const analyze_format_string::ConversionSpecifier &CS,
3383 const char *startSpecifier, unsigned specifierLen,
3384 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003385
3386 template <typename Range>
3387 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3388 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003389 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003390};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003391}
Ted Kremenekab278de2010-01-28 23:39:18 +00003392
Ted Kremenek02087932010-07-16 02:11:22 +00003393SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003394 return OrigFormatExpr->getSourceRange();
3395}
3396
Ted Kremenek02087932010-07-16 02:11:22 +00003397CharSourceRange CheckFormatHandler::
3398getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003399 SourceLocation Start = getLocationOfByte(startSpecifier);
3400 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3401
3402 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003403 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003404
3405 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003406}
3407
Ted Kremenek02087932010-07-16 02:11:22 +00003408SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003409 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003410}
3411
Ted Kremenek02087932010-07-16 02:11:22 +00003412void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3413 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003414 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3415 getLocationOfByte(startSpecifier),
3416 /*IsStringLocation*/true,
3417 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003418}
3419
Jordan Rose92303592012-09-08 04:00:03 +00003420void CheckFormatHandler::HandleInvalidLengthModifier(
3421 const analyze_format_string::FormatSpecifier &FS,
3422 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003423 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003424 using namespace analyze_format_string;
3425
3426 const LengthModifier &LM = FS.getLengthModifier();
3427 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3428
3429 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003430 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003431 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003432 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003433 getLocationOfByte(LM.getStart()),
3434 /*IsStringLocation*/true,
3435 getSpecifierRange(startSpecifier, specifierLen));
3436
3437 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3438 << FixedLM->toString()
3439 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3440
3441 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003442 FixItHint Hint;
3443 if (DiagID == diag::warn_format_nonsensical_length)
3444 Hint = FixItHint::CreateRemoval(LMRange);
3445
3446 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003447 getLocationOfByte(LM.getStart()),
3448 /*IsStringLocation*/true,
3449 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003450 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003451 }
3452}
3453
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003454void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003455 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003456 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003457 using namespace analyze_format_string;
3458
3459 const LengthModifier &LM = FS.getLengthModifier();
3460 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3461
3462 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003463 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003464 if (FixedLM) {
3465 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3466 << LM.toString() << 0,
3467 getLocationOfByte(LM.getStart()),
3468 /*IsStringLocation*/true,
3469 getSpecifierRange(startSpecifier, specifierLen));
3470
3471 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3472 << FixedLM->toString()
3473 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3474
3475 } else {
3476 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3477 << LM.toString() << 0,
3478 getLocationOfByte(LM.getStart()),
3479 /*IsStringLocation*/true,
3480 getSpecifierRange(startSpecifier, specifierLen));
3481 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003482}
3483
3484void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3485 const analyze_format_string::ConversionSpecifier &CS,
3486 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003487 using namespace analyze_format_string;
3488
3489 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003490 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003491 if (FixedCS) {
3492 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3493 << CS.toString() << /*conversion specifier*/1,
3494 getLocationOfByte(CS.getStart()),
3495 /*IsStringLocation*/true,
3496 getSpecifierRange(startSpecifier, specifierLen));
3497
3498 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3499 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3500 << FixedCS->toString()
3501 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3502 } else {
3503 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3504 << CS.toString() << /*conversion specifier*/1,
3505 getLocationOfByte(CS.getStart()),
3506 /*IsStringLocation*/true,
3507 getSpecifierRange(startSpecifier, specifierLen));
3508 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003509}
3510
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003511void CheckFormatHandler::HandlePosition(const char *startPos,
3512 unsigned posLen) {
3513 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3514 getLocationOfByte(startPos),
3515 /*IsStringLocation*/true,
3516 getSpecifierRange(startPos, posLen));
3517}
3518
Ted Kremenekd1668192010-02-27 01:41:03 +00003519void
Ted Kremenek02087932010-07-16 02:11:22 +00003520CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3521 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003522 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3523 << (unsigned) p,
3524 getLocationOfByte(startPos), /*IsStringLocation*/true,
3525 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003526}
3527
Ted Kremenek02087932010-07-16 02:11:22 +00003528void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003529 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003530 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3531 getLocationOfByte(startPos),
3532 /*IsStringLocation*/true,
3533 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003534}
3535
Ted Kremenek02087932010-07-16 02:11:22 +00003536void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003537 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003538 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003539 EmitFormatDiagnostic(
3540 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3541 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3542 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003543 }
Ted Kremenek02087932010-07-16 02:11:22 +00003544}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003545
Jordan Rose58bbe422012-07-19 18:10:08 +00003546// Note that this may return NULL if there was an error parsing or building
3547// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003548const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003549 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003550}
3551
3552void CheckFormatHandler::DoneProcessing() {
3553 // Does the number of data arguments exceed the number of
3554 // format conversions in the format string?
3555 if (!HasVAListArg) {
3556 // Find any arguments that weren't covered.
3557 CoveredArgs.flip();
3558 signed notCoveredArg = CoveredArgs.find_first();
3559 if (notCoveredArg >= 0) {
3560 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003561 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3562 SourceLocation Loc = E->getLocStart();
3563 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3564 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3565 Loc, /*IsStringLocation*/false,
3566 getFormatStringRange());
3567 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003568 }
Ted Kremenek02087932010-07-16 02:11:22 +00003569 }
3570 }
3571}
3572
Ted Kremenekce815422010-07-19 21:25:57 +00003573bool
3574CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3575 SourceLocation Loc,
3576 const char *startSpec,
3577 unsigned specifierLen,
3578 const char *csStart,
3579 unsigned csLen) {
3580
3581 bool keepGoing = true;
3582 if (argIndex < NumDataArgs) {
3583 // Consider the argument coverered, even though the specifier doesn't
3584 // make sense.
3585 CoveredArgs.set(argIndex);
3586 }
3587 else {
3588 // If argIndex exceeds the number of data arguments we
3589 // don't issue a warning because that is just a cascade of warnings (and
3590 // they may have intended '%%' anyway). We don't want to continue processing
3591 // the format string after this point, however, as we will like just get
3592 // gibberish when trying to match arguments.
3593 keepGoing = false;
3594 }
3595
Richard Trieu03cf7b72011-10-28 00:41:25 +00003596 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3597 << StringRef(csStart, csLen),
3598 Loc, /*IsStringLocation*/true,
3599 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003600
3601 return keepGoing;
3602}
3603
Richard Trieu03cf7b72011-10-28 00:41:25 +00003604void
3605CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3606 const char *startSpec,
3607 unsigned specifierLen) {
3608 EmitFormatDiagnostic(
3609 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3610 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3611}
3612
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003613bool
3614CheckFormatHandler::CheckNumArgs(
3615 const analyze_format_string::FormatSpecifier &FS,
3616 const analyze_format_string::ConversionSpecifier &CS,
3617 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3618
3619 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003620 PartialDiagnostic PDiag = FS.usesPositionalArg()
3621 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3622 << (argIndex+1) << NumDataArgs)
3623 : S.PDiag(diag::warn_printf_insufficient_data_args);
3624 EmitFormatDiagnostic(
3625 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3626 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003627 return false;
3628 }
3629 return true;
3630}
3631
Richard Trieu03cf7b72011-10-28 00:41:25 +00003632template<typename Range>
3633void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3634 SourceLocation Loc,
3635 bool IsStringLocation,
3636 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003637 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003638 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003639 Loc, IsStringLocation, StringRange, FixIt);
3640}
3641
3642/// \brief If the format string is not within the funcion call, emit a note
3643/// so that the function call and string are in diagnostic messages.
3644///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003645/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003646/// call and only one diagnostic message will be produced. Otherwise, an
3647/// extra note will be emitted pointing to location of the format string.
3648///
3649/// \param ArgumentExpr the expression that is passed as the format string
3650/// argument in the function call. Used for getting locations when two
3651/// diagnostics are emitted.
3652///
3653/// \param PDiag the callee should already have provided any strings for the
3654/// diagnostic message. This function only adds locations and fixits
3655/// to diagnostics.
3656///
3657/// \param Loc primary location for diagnostic. If two diagnostics are
3658/// required, one will be at Loc and a new SourceLocation will be created for
3659/// the other one.
3660///
3661/// \param IsStringLocation if true, Loc points to the format string should be
3662/// used for the note. Otherwise, Loc points to the argument list and will
3663/// be used with PDiag.
3664///
3665/// \param StringRange some or all of the string to highlight. This is
3666/// templated so it can accept either a CharSourceRange or a SourceRange.
3667///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003668/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003669template<typename Range>
3670void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3671 const Expr *ArgumentExpr,
3672 PartialDiagnostic PDiag,
3673 SourceLocation Loc,
3674 bool IsStringLocation,
3675 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003676 ArrayRef<FixItHint> FixIt) {
3677 if (InFunctionCall) {
3678 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3679 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003680 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003681 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003682 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3683 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003684
3685 const Sema::SemaDiagnosticBuilder &Note =
3686 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3687 diag::note_format_string_defined);
3688
3689 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003690 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003691 }
3692}
3693
Ted Kremenek02087932010-07-16 02:11:22 +00003694//===--- CHECK: Printf format string checking ------------------------------===//
3695
3696namespace {
3697class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003698 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003699public:
3700 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3701 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003702 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003703 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003704 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003705 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003706 Sema::VariadicCallType CallType,
3707 llvm::SmallBitVector &CheckedVarArgs)
3708 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3709 numDataArgs, beg, hasVAListArg, Args,
3710 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3711 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003712 {}
3713
Craig Toppere14c0f82014-03-12 04:55:44 +00003714
Ted Kremenek02087932010-07-16 02:11:22 +00003715 bool HandleInvalidPrintfConversionSpecifier(
3716 const analyze_printf::PrintfSpecifier &FS,
3717 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003718 unsigned specifierLen) override;
3719
Ted Kremenek02087932010-07-16 02:11:22 +00003720 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3721 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003722 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003723 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3724 const char *StartSpecifier,
3725 unsigned SpecifierLen,
3726 const Expr *E);
3727
Ted Kremenek02087932010-07-16 02:11:22 +00003728 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3729 const char *startSpecifier, unsigned specifierLen);
3730 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3731 const analyze_printf::OptionalAmount &Amt,
3732 unsigned type,
3733 const char *startSpecifier, unsigned specifierLen);
3734 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3735 const analyze_printf::OptionalFlag &flag,
3736 const char *startSpecifier, unsigned specifierLen);
3737 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3738 const analyze_printf::OptionalFlag &ignoredFlag,
3739 const analyze_printf::OptionalFlag &flag,
3740 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003741 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003742 const Expr *E);
Ted Kremenek2b417712015-07-02 05:39:16 +00003743
3744 void HandleEmptyObjCModifierFlag(const char *startFlag,
3745 unsigned flagLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003746
Ted Kremenek2b417712015-07-02 05:39:16 +00003747 void HandleInvalidObjCModifierFlag(const char *startFlag,
3748 unsigned flagLen) override;
3749
3750 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
3751 const char *flagsEnd,
3752 const char *conversionPosition)
3753 override;
3754};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003755}
Ted Kremenek02087932010-07-16 02:11:22 +00003756
3757bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3758 const analyze_printf::PrintfSpecifier &FS,
3759 const char *startSpecifier,
3760 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003761 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003762 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003763
Ted Kremenekce815422010-07-19 21:25:57 +00003764 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3765 getLocationOfByte(CS.getStart()),
3766 startSpecifier, specifierLen,
3767 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003768}
3769
Ted Kremenek02087932010-07-16 02:11:22 +00003770bool CheckPrintfHandler::HandleAmount(
3771 const analyze_format_string::OptionalAmount &Amt,
3772 unsigned k, const char *startSpecifier,
3773 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003774
3775 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003776 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003777 unsigned argIndex = Amt.getArgIndex();
3778 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003779 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3780 << k,
3781 getLocationOfByte(Amt.getStart()),
3782 /*IsStringLocation*/true,
3783 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003784 // Don't do any more checking. We will just emit
3785 // spurious errors.
3786 return false;
3787 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003788
Ted Kremenek5739de72010-01-29 01:06:55 +00003789 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003790 // Although not in conformance with C99, we also allow the argument to be
3791 // an 'unsigned int' as that is a reasonably safe case. GCC also
3792 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003793 CoveredArgs.set(argIndex);
3794 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003795 if (!Arg)
3796 return false;
3797
Ted Kremenek5739de72010-01-29 01:06:55 +00003798 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003799
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003800 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3801 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003802
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003803 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003804 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003805 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003806 << T << Arg->getSourceRange(),
3807 getLocationOfByte(Amt.getStart()),
3808 /*IsStringLocation*/true,
3809 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003810 // Don't do any more checking. We will just emit
3811 // spurious errors.
3812 return false;
3813 }
3814 }
3815 }
3816 return true;
3817}
Ted Kremenek5739de72010-01-29 01:06:55 +00003818
Tom Careb49ec692010-06-17 19:00:27 +00003819void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003820 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003821 const analyze_printf::OptionalAmount &Amt,
3822 unsigned type,
3823 const char *startSpecifier,
3824 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003825 const analyze_printf::PrintfConversionSpecifier &CS =
3826 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003827
Richard Trieu03cf7b72011-10-28 00:41:25 +00003828 FixItHint fixit =
3829 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3830 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3831 Amt.getConstantLength()))
3832 : FixItHint();
3833
3834 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3835 << type << CS.toString(),
3836 getLocationOfByte(Amt.getStart()),
3837 /*IsStringLocation*/true,
3838 getSpecifierRange(startSpecifier, specifierLen),
3839 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003840}
3841
Ted Kremenek02087932010-07-16 02:11:22 +00003842void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003843 const analyze_printf::OptionalFlag &flag,
3844 const char *startSpecifier,
3845 unsigned specifierLen) {
3846 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003847 const analyze_printf::PrintfConversionSpecifier &CS =
3848 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003849 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3850 << flag.toString() << CS.toString(),
3851 getLocationOfByte(flag.getPosition()),
3852 /*IsStringLocation*/true,
3853 getSpecifierRange(startSpecifier, specifierLen),
3854 FixItHint::CreateRemoval(
3855 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003856}
3857
3858void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003859 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003860 const analyze_printf::OptionalFlag &ignoredFlag,
3861 const analyze_printf::OptionalFlag &flag,
3862 const char *startSpecifier,
3863 unsigned specifierLen) {
3864 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003865 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3866 << ignoredFlag.toString() << flag.toString(),
3867 getLocationOfByte(ignoredFlag.getPosition()),
3868 /*IsStringLocation*/true,
3869 getSpecifierRange(startSpecifier, specifierLen),
3870 FixItHint::CreateRemoval(
3871 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003872}
3873
Ted Kremenek2b417712015-07-02 05:39:16 +00003874// void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3875// bool IsStringLocation, Range StringRange,
3876// ArrayRef<FixItHint> Fixit = None);
3877
3878void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
3879 unsigned flagLen) {
3880 // Warn about an empty flag.
3881 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
3882 getLocationOfByte(startFlag),
3883 /*IsStringLocation*/true,
3884 getSpecifierRange(startFlag, flagLen));
3885}
3886
3887void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
3888 unsigned flagLen) {
3889 // Warn about an invalid flag.
3890 auto Range = getSpecifierRange(startFlag, flagLen);
3891 StringRef flag(startFlag, flagLen);
3892 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3893 getLocationOfByte(startFlag),
3894 /*IsStringLocation*/true,
3895 Range, FixItHint::CreateRemoval(Range));
3896}
3897
3898void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3899 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
3900 // Warn about using '[...]' without a '@' conversion.
3901 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3902 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3903 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
3904 getLocationOfByte(conversionPosition),
3905 /*IsStringLocation*/true,
3906 Range, FixItHint::CreateRemoval(Range));
3907}
3908
Richard Smith55ce3522012-06-25 20:30:08 +00003909// Determines if the specified is a C++ class or struct containing
3910// a member with the specified name and kind (e.g. a CXXMethodDecl named
3911// "c_str()").
3912template<typename MemberKind>
3913static llvm::SmallPtrSet<MemberKind*, 1>
3914CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3915 const RecordType *RT = Ty->getAs<RecordType>();
3916 llvm::SmallPtrSet<MemberKind*, 1> Results;
3917
3918 if (!RT)
3919 return Results;
3920 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003921 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003922 return Results;
3923
Alp Tokerb6cc5922014-05-03 03:45:55 +00003924 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003925 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003926 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003927
3928 // We just need to include all members of the right kind turned up by the
3929 // filter, at this point.
3930 if (S.LookupQualifiedName(R, RT->getDecl()))
3931 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3932 NamedDecl *decl = (*I)->getUnderlyingDecl();
3933 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3934 Results.insert(FK);
3935 }
3936 return Results;
3937}
3938
Richard Smith2868a732014-02-28 01:36:39 +00003939/// Check if we could call '.c_str()' on an object.
3940///
3941/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3942/// allow the call, or if it would be ambiguous).
3943bool Sema::hasCStrMethod(const Expr *E) {
3944 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3945 MethodSet Results =
3946 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3947 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3948 MI != ME; ++MI)
3949 if ((*MI)->getMinRequiredArguments() == 0)
3950 return true;
3951 return false;
3952}
3953
Richard Smith55ce3522012-06-25 20:30:08 +00003954// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003955// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003956// Returns true when a c_str() conversion method is found.
3957bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003958 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003959 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3960
3961 MethodSet Results =
3962 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3963
3964 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3965 MI != ME; ++MI) {
3966 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003967 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003968 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003969 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003970 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003971 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3972 << "c_str()"
3973 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3974 return true;
3975 }
3976 }
3977
3978 return false;
3979}
3980
Ted Kremenekab278de2010-01-28 23:39:18 +00003981bool
Ted Kremenek02087932010-07-16 02:11:22 +00003982CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003983 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003984 const char *startSpecifier,
3985 unsigned specifierLen) {
3986
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003987 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003988 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003989 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003990
Ted Kremenek6cd69422010-07-19 22:01:06 +00003991 if (FS.consumesDataArgument()) {
3992 if (atFirstArg) {
3993 atFirstArg = false;
3994 usesPositionalArgs = FS.usesPositionalArg();
3995 }
3996 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003997 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3998 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003999 return false;
4000 }
Ted Kremenek5739de72010-01-29 01:06:55 +00004001 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004002
Ted Kremenekd1668192010-02-27 01:41:03 +00004003 // First check if the field width, precision, and conversion specifier
4004 // have matching data arguments.
4005 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4006 startSpecifier, specifierLen)) {
4007 return false;
4008 }
4009
4010 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4011 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00004012 return false;
4013 }
4014
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004015 if (!CS.consumesDataArgument()) {
4016 // FIXME: Technically specifying a precision or field width here
4017 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00004018 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00004019 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004020
Ted Kremenek4a49d982010-02-26 19:18:41 +00004021 // Consume the argument.
4022 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00004023 if (argIndex < NumDataArgs) {
4024 // The check to see if the argIndex is valid will come later.
4025 // We set the bit here because we may exit early from this
4026 // function if we encounter some other error.
4027 CoveredArgs.set(argIndex);
4028 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00004029
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004030 // FreeBSD kernel extensions.
4031 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4032 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4033 // We need at least two arguments.
4034 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4035 return false;
4036
4037 // Claim the second argument.
4038 CoveredArgs.set(argIndex + 1);
4039
4040 // Type check the first argument (int for %b, pointer for %D)
4041 const Expr *Ex = getDataArg(argIndex);
4042 const analyze_printf::ArgType &AT =
4043 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4044 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4045 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4046 EmitFormatDiagnostic(
4047 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4048 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4049 << false << Ex->getSourceRange(),
4050 Ex->getLocStart(), /*IsStringLocation*/false,
4051 getSpecifierRange(startSpecifier, specifierLen));
4052
4053 // Type check the second argument (char * for both %b and %D)
4054 Ex = getDataArg(argIndex + 1);
4055 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4056 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4057 EmitFormatDiagnostic(
4058 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4059 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4060 << false << Ex->getSourceRange(),
4061 Ex->getLocStart(), /*IsStringLocation*/false,
4062 getSpecifierRange(startSpecifier, specifierLen));
4063
4064 return true;
4065 }
4066
Ted Kremenek4a49d982010-02-26 19:18:41 +00004067 // Check for using an Objective-C specific conversion specifier
4068 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004069 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00004070 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4071 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00004072 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004073
Tom Careb49ec692010-06-17 19:00:27 +00004074 // Check for invalid use of field width
4075 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00004076 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00004077 startSpecifier, specifierLen);
4078 }
4079
4080 // Check for invalid use of precision
4081 if (!FS.hasValidPrecision()) {
4082 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4083 startSpecifier, specifierLen);
4084 }
4085
4086 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00004087 if (!FS.hasValidThousandsGroupingPrefix())
4088 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004089 if (!FS.hasValidLeadingZeros())
4090 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4091 if (!FS.hasValidPlusPrefix())
4092 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00004093 if (!FS.hasValidSpacePrefix())
4094 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004095 if (!FS.hasValidAlternativeForm())
4096 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4097 if (!FS.hasValidLeftJustified())
4098 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4099
4100 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00004101 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4102 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4103 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00004104 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4105 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4106 startSpecifier, specifierLen);
4107
4108 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004109 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4111 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004112 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004113 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004114 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004115 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4116 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00004117
Jordan Rose92303592012-09-08 04:00:03 +00004118 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4119 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4120
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004121 // The remaining checks depend on the data arguments.
4122 if (HasVAListArg)
4123 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004124
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004125 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00004126 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00004127
Jordan Rose58bbe422012-07-19 18:10:08 +00004128 const Expr *Arg = getDataArg(argIndex);
4129 if (!Arg)
4130 return true;
4131
4132 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00004133}
4134
Jordan Roseaee34382012-09-05 22:56:26 +00004135static bool requiresParensToAddCast(const Expr *E) {
4136 // FIXME: We should have a general way to reason about operator
4137 // precedence and whether parens are actually needed here.
4138 // Take care of a few common cases where they aren't.
4139 const Expr *Inside = E->IgnoreImpCasts();
4140 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4141 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4142
4143 switch (Inside->getStmtClass()) {
4144 case Stmt::ArraySubscriptExprClass:
4145 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004146 case Stmt::CharacterLiteralClass:
4147 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004148 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004149 case Stmt::FloatingLiteralClass:
4150 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004151 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004152 case Stmt::ObjCArrayLiteralClass:
4153 case Stmt::ObjCBoolLiteralExprClass:
4154 case Stmt::ObjCBoxedExprClass:
4155 case Stmt::ObjCDictionaryLiteralClass:
4156 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004157 case Stmt::ObjCIvarRefExprClass:
4158 case Stmt::ObjCMessageExprClass:
4159 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004160 case Stmt::ObjCStringLiteralClass:
4161 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004162 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00004163 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00004164 case Stmt::UnaryOperatorClass:
4165 return false;
4166 default:
4167 return true;
4168 }
4169}
4170
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004171static std::pair<QualType, StringRef>
4172shouldNotPrintDirectly(const ASTContext &Context,
4173 QualType IntendedTy,
4174 const Expr *E) {
4175 // Use a 'while' to peel off layers of typedefs.
4176 QualType TyTy = IntendedTy;
4177 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4178 StringRef Name = UserTy->getDecl()->getName();
4179 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4180 .Case("NSInteger", Context.LongTy)
4181 .Case("NSUInteger", Context.UnsignedLongTy)
4182 .Case("SInt32", Context.IntTy)
4183 .Case("UInt32", Context.UnsignedIntTy)
4184 .Default(QualType());
4185
4186 if (!CastTy.isNull())
4187 return std::make_pair(CastTy, Name);
4188
4189 TyTy = UserTy->desugar();
4190 }
4191
4192 // Strip parens if necessary.
4193 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4194 return shouldNotPrintDirectly(Context,
4195 PE->getSubExpr()->getType(),
4196 PE->getSubExpr());
4197
4198 // If this is a conditional expression, then its result type is constructed
4199 // via usual arithmetic conversions and thus there might be no necessary
4200 // typedef sugar there. Recurse to operands to check for NSInteger &
4201 // Co. usage condition.
4202 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4203 QualType TrueTy, FalseTy;
4204 StringRef TrueName, FalseName;
4205
4206 std::tie(TrueTy, TrueName) =
4207 shouldNotPrintDirectly(Context,
4208 CO->getTrueExpr()->getType(),
4209 CO->getTrueExpr());
4210 std::tie(FalseTy, FalseName) =
4211 shouldNotPrintDirectly(Context,
4212 CO->getFalseExpr()->getType(),
4213 CO->getFalseExpr());
4214
4215 if (TrueTy == FalseTy)
4216 return std::make_pair(TrueTy, TrueName);
4217 else if (TrueTy.isNull())
4218 return std::make_pair(FalseTy, FalseName);
4219 else if (FalseTy.isNull())
4220 return std::make_pair(TrueTy, TrueName);
4221 }
4222
4223 return std::make_pair(QualType(), StringRef());
4224}
4225
Richard Smith55ce3522012-06-25 20:30:08 +00004226bool
4227CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4228 const char *StartSpecifier,
4229 unsigned SpecifierLen,
4230 const Expr *E) {
4231 using namespace analyze_format_string;
4232 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004233 // Now type check the data expression that matches the
4234 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004235 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4236 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004237 if (!AT.isValid())
4238 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004239
Jordan Rose598ec092012-12-05 18:44:40 +00004240 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004241 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4242 ExprTy = TET->getUnderlyingExpr()->getType();
4243 }
4244
Seth Cantrellb4802962015-03-04 03:12:10 +00004245 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4246
4247 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004248 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004249 }
Jordan Rose98709982012-06-04 22:48:57 +00004250
Jordan Rose22b74712012-09-05 22:56:19 +00004251 // Look through argument promotions for our error message's reported type.
4252 // This includes the integral and floating promotions, but excludes array
4253 // and function pointer decay; seeing that an argument intended to be a
4254 // string has type 'char [6]' is probably more confusing than 'char *'.
4255 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4256 if (ICE->getCastKind() == CK_IntegralCast ||
4257 ICE->getCastKind() == CK_FloatingCast) {
4258 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004259 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004260
4261 // Check if we didn't match because of an implicit cast from a 'char'
4262 // or 'short' to an 'int'. This is done because printf is a varargs
4263 // function.
4264 if (ICE->getType() == S.Context.IntTy ||
4265 ICE->getType() == S.Context.UnsignedIntTy) {
4266 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004267 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004268 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004269 }
Jordan Rose98709982012-06-04 22:48:57 +00004270 }
Jordan Rose598ec092012-12-05 18:44:40 +00004271 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4272 // Special case for 'a', which has type 'int' in C.
4273 // Note, however, that we do /not/ want to treat multibyte constants like
4274 // 'MooV' as characters! This form is deprecated but still exists.
4275 if (ExprTy == S.Context.IntTy)
4276 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4277 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004278 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004279
Jordan Rosebc53ed12014-05-31 04:12:14 +00004280 // Look through enums to their underlying type.
4281 bool IsEnum = false;
4282 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4283 ExprTy = EnumTy->getDecl()->getIntegerType();
4284 IsEnum = true;
4285 }
4286
Jordan Rose0e5badd2012-12-05 18:44:49 +00004287 // %C in an Objective-C context prints a unichar, not a wchar_t.
4288 // If the argument is an integer of some kind, believe the %C and suggest
4289 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004290 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004291 if (ObjCContext &&
4292 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4293 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4294 !ExprTy->isCharType()) {
4295 // 'unichar' is defined as a typedef of unsigned short, but we should
4296 // prefer using the typedef if it is visible.
4297 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004298
4299 // While we are here, check if the value is an IntegerLiteral that happens
4300 // to be within the valid range.
4301 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4302 const llvm::APInt &V = IL->getValue();
4303 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4304 return true;
4305 }
4306
Jordan Rose0e5badd2012-12-05 18:44:49 +00004307 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4308 Sema::LookupOrdinaryName);
4309 if (S.LookupName(Result, S.getCurScope())) {
4310 NamedDecl *ND = Result.getFoundDecl();
4311 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4312 if (TD->getUnderlyingType() == IntendedTy)
4313 IntendedTy = S.Context.getTypedefType(TD);
4314 }
4315 }
4316 }
4317
4318 // Special-case some of Darwin's platform-independence types by suggesting
4319 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004320 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004321 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004322 QualType CastTy;
4323 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4324 if (!CastTy.isNull()) {
4325 IntendedTy = CastTy;
4326 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004327 }
4328 }
4329
Jordan Rose22b74712012-09-05 22:56:19 +00004330 // We may be able to offer a FixItHint if it is a supported type.
4331 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004332 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004333 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004334
Jordan Rose22b74712012-09-05 22:56:19 +00004335 if (success) {
4336 // Get the fix string from the fixed format specifier
4337 SmallString<16> buf;
4338 llvm::raw_svector_ostream os(buf);
4339 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004340
Jordan Roseaee34382012-09-05 22:56:26 +00004341 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4342
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004343 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004344 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4345 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4346 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4347 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004348 // In this case, the specifier is wrong and should be changed to match
4349 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004350 EmitFormatDiagnostic(S.PDiag(diag)
4351 << AT.getRepresentativeTypeName(S.Context)
4352 << IntendedTy << IsEnum << E->getSourceRange(),
4353 E->getLocStart(),
4354 /*IsStringLocation*/ false, SpecRange,
4355 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004356
4357 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004358 // The canonical type for formatting this value is different from the
4359 // actual type of the expression. (This occurs, for example, with Darwin's
4360 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4361 // should be printed as 'long' for 64-bit compatibility.)
4362 // Rather than emitting a normal format/argument mismatch, we want to
4363 // add a cast to the recommended type (and correct the format string
4364 // if necessary).
4365 SmallString<16> CastBuf;
4366 llvm::raw_svector_ostream CastFix(CastBuf);
4367 CastFix << "(";
4368 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4369 CastFix << ")";
4370
4371 SmallVector<FixItHint,4> Hints;
4372 if (!AT.matchesType(S.Context, IntendedTy))
4373 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4374
4375 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4376 // If there's already a cast present, just replace it.
4377 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4378 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4379
4380 } else if (!requiresParensToAddCast(E)) {
4381 // If the expression has high enough precedence,
4382 // just write the C-style cast.
4383 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4384 CastFix.str()));
4385 } else {
4386 // Otherwise, add parens around the expression as well as the cast.
4387 CastFix << "(";
4388 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4389 CastFix.str()));
4390
Alp Tokerb6cc5922014-05-03 03:45:55 +00004391 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004392 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4393 }
4394
Jordan Rose0e5badd2012-12-05 18:44:49 +00004395 if (ShouldNotPrintDirectly) {
4396 // The expression has a type that should not be printed directly.
4397 // We extract the name from the typedef because we don't want to show
4398 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004399 StringRef Name;
4400 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4401 Name = TypedefTy->getDecl()->getName();
4402 else
4403 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004404 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004405 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004406 << E->getSourceRange(),
4407 E->getLocStart(), /*IsStringLocation=*/false,
4408 SpecRange, Hints);
4409 } else {
4410 // In this case, the expression could be printed using a different
4411 // specifier, but we've decided that the specifier is probably correct
4412 // and we should cast instead. Just use the normal warning message.
4413 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004414 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4415 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004416 << E->getSourceRange(),
4417 E->getLocStart(), /*IsStringLocation*/false,
4418 SpecRange, Hints);
4419 }
Jordan Roseaee34382012-09-05 22:56:26 +00004420 }
Jordan Rose22b74712012-09-05 22:56:19 +00004421 } else {
4422 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4423 SpecifierLen);
4424 // Since the warning for passing non-POD types to variadic functions
4425 // was deferred until now, we emit a warning for non-POD
4426 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004427 switch (S.isValidVarArgType(ExprTy)) {
4428 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004429 case Sema::VAK_ValidInCXX11: {
4430 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4431 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4432 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4433 }
Richard Smithd7293d72013-08-05 18:49:43 +00004434
Seth Cantrellb4802962015-03-04 03:12:10 +00004435 EmitFormatDiagnostic(
4436 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4437 << IsEnum << CSR << E->getSourceRange(),
4438 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4439 break;
4440 }
Richard Smithd7293d72013-08-05 18:49:43 +00004441 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004442 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004443 EmitFormatDiagnostic(
4444 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004445 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004446 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004447 << CallType
4448 << AT.getRepresentativeTypeName(S.Context)
4449 << CSR
4450 << E->getSourceRange(),
4451 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004452 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004453 break;
4454
4455 case Sema::VAK_Invalid:
4456 if (ExprTy->isObjCObjectType())
4457 EmitFormatDiagnostic(
4458 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4459 << S.getLangOpts().CPlusPlus11
4460 << ExprTy
4461 << CallType
4462 << AT.getRepresentativeTypeName(S.Context)
4463 << CSR
4464 << E->getSourceRange(),
4465 E->getLocStart(), /*IsStringLocation*/false, CSR);
4466 else
4467 // FIXME: If this is an initializer list, suggest removing the braces
4468 // or inserting a cast to the target type.
4469 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4470 << isa<InitListExpr>(E) << ExprTy << CallType
4471 << AT.getRepresentativeTypeName(S.Context)
4472 << E->getSourceRange();
4473 break;
4474 }
4475
4476 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4477 "format string specifier index out of range");
4478 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004479 }
4480
Ted Kremenekab278de2010-01-28 23:39:18 +00004481 return true;
4482}
4483
Ted Kremenek02087932010-07-16 02:11:22 +00004484//===--- CHECK: Scanf format string checking ------------------------------===//
4485
4486namespace {
4487class CheckScanfHandler : public CheckFormatHandler {
4488public:
4489 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4490 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004491 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004492 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004493 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004494 Sema::VariadicCallType CallType,
4495 llvm::SmallBitVector &CheckedVarArgs)
4496 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4497 numDataArgs, beg, hasVAListArg,
4498 Args, formatIdx, inFunctionCall, CallType,
4499 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004500 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004501
4502 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4503 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004504 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004505
4506 bool HandleInvalidScanfConversionSpecifier(
4507 const analyze_scanf::ScanfSpecifier &FS,
4508 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004509 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004510
Craig Toppere14c0f82014-03-12 04:55:44 +00004511 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004512};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004513}
Ted Kremenekab278de2010-01-28 23:39:18 +00004514
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004515void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4516 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004517 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4518 getLocationOfByte(end), /*IsStringLocation*/true,
4519 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004520}
4521
Ted Kremenekce815422010-07-19 21:25:57 +00004522bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4523 const analyze_scanf::ScanfSpecifier &FS,
4524 const char *startSpecifier,
4525 unsigned specifierLen) {
4526
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004527 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004528 FS.getConversionSpecifier();
4529
4530 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4531 getLocationOfByte(CS.getStart()),
4532 startSpecifier, specifierLen,
4533 CS.getStart(), CS.getLength());
4534}
4535
Ted Kremenek02087932010-07-16 02:11:22 +00004536bool CheckScanfHandler::HandleScanfSpecifier(
4537 const analyze_scanf::ScanfSpecifier &FS,
4538 const char *startSpecifier,
4539 unsigned specifierLen) {
4540
4541 using namespace analyze_scanf;
4542 using namespace analyze_format_string;
4543
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004544 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004545
Ted Kremenek6cd69422010-07-19 22:01:06 +00004546 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4547 // be used to decide if we are using positional arguments consistently.
4548 if (FS.consumesDataArgument()) {
4549 if (atFirstArg) {
4550 atFirstArg = false;
4551 usesPositionalArgs = FS.usesPositionalArg();
4552 }
4553 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004554 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4555 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004556 return false;
4557 }
Ted Kremenek02087932010-07-16 02:11:22 +00004558 }
4559
4560 // Check if the field with is non-zero.
4561 const OptionalAmount &Amt = FS.getFieldWidth();
4562 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4563 if (Amt.getConstantAmount() == 0) {
4564 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4565 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004566 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4567 getLocationOfByte(Amt.getStart()),
4568 /*IsStringLocation*/true, R,
4569 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004570 }
4571 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004572
Ted Kremenek02087932010-07-16 02:11:22 +00004573 if (!FS.consumesDataArgument()) {
4574 // FIXME: Technically specifying a precision or field width here
4575 // makes no sense. Worth issuing a warning at some point.
4576 return true;
4577 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004578
Ted Kremenek02087932010-07-16 02:11:22 +00004579 // Consume the argument.
4580 unsigned argIndex = FS.getArgIndex();
4581 if (argIndex < NumDataArgs) {
4582 // The check to see if the argIndex is valid will come later.
4583 // We set the bit here because we may exit early from this
4584 // function if we encounter some other error.
4585 CoveredArgs.set(argIndex);
4586 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004587
Ted Kremenek4407ea42010-07-20 20:04:47 +00004588 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004589 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004590 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4591 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004592 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004593 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004594 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004595 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4596 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004597
Jordan Rose92303592012-09-08 04:00:03 +00004598 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4599 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4600
Ted Kremenek02087932010-07-16 02:11:22 +00004601 // The remaining checks depend on the data arguments.
4602 if (HasVAListArg)
4603 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004604
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004605 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004606 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004607
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004608 // Check that the argument type matches the format specifier.
4609 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004610 if (!Ex)
4611 return true;
4612
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004613 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004614
4615 if (!AT.isValid()) {
4616 return true;
4617 }
4618
Seth Cantrellb4802962015-03-04 03:12:10 +00004619 analyze_format_string::ArgType::MatchKind match =
4620 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004621 if (match == analyze_format_string::ArgType::Match) {
4622 return true;
4623 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004624
Seth Cantrell79340072015-03-04 05:58:08 +00004625 ScanfSpecifier fixedFS = FS;
4626 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4627 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004628
Seth Cantrell79340072015-03-04 05:58:08 +00004629 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4630 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4631 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4632 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004633
Seth Cantrell79340072015-03-04 05:58:08 +00004634 if (success) {
4635 // Get the fix string from the fixed format specifier.
4636 SmallString<128> buf;
4637 llvm::raw_svector_ostream os(buf);
4638 fixedFS.toString(os);
4639
4640 EmitFormatDiagnostic(
4641 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4642 << Ex->getType() << false << Ex->getSourceRange(),
4643 Ex->getLocStart(),
4644 /*IsStringLocation*/ false,
4645 getSpecifierRange(startSpecifier, specifierLen),
4646 FixItHint::CreateReplacement(
4647 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4648 } else {
4649 EmitFormatDiagnostic(S.PDiag(diag)
4650 << AT.getRepresentativeTypeName(S.Context)
4651 << Ex->getType() << false << Ex->getSourceRange(),
4652 Ex->getLocStart(),
4653 /*IsStringLocation*/ false,
4654 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004655 }
4656
Ted Kremenek02087932010-07-16 02:11:22 +00004657 return true;
4658}
4659
4660void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004661 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004662 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004663 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004664 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004665 bool inFunctionCall, VariadicCallType CallType,
4666 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004667
Ted Kremenekab278de2010-01-28 23:39:18 +00004668 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004669 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004670 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004671 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004672 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4673 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004674 return;
4675 }
Ted Kremenek02087932010-07-16 02:11:22 +00004676
Ted Kremenekab278de2010-01-28 23:39:18 +00004677 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004678 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004679 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004680 // Account for cases where the string literal is truncated in a declaration.
4681 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4682 assert(T && "String literal not of constant array type!");
4683 size_t TypeSize = T->getSize().getZExtValue();
4684 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004685 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004686
4687 // Emit a warning if the string literal is truncated and does not contain an
4688 // embedded null character.
4689 if (TypeSize <= StrRef.size() &&
4690 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4691 CheckFormatHandler::EmitFormatDiagnostic(
4692 *this, inFunctionCall, Args[format_idx],
4693 PDiag(diag::warn_printf_format_string_not_null_terminated),
4694 FExpr->getLocStart(),
4695 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4696 return;
4697 }
4698
Ted Kremenekab278de2010-01-28 23:39:18 +00004699 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004700 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004701 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004702 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004703 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4704 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004705 return;
4706 }
Ted Kremenek02087932010-07-16 02:11:22 +00004707
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004708 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004709 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004710 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004711 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004712 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004713 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004714
Hans Wennborg23926bd2011-12-15 10:25:47 +00004715 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004716 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004717 Context.getTargetInfo(),
4718 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004719 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004720 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004721 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004722 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004723 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004724
Hans Wennborg23926bd2011-12-15 10:25:47 +00004725 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004726 getLangOpts(),
4727 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004728 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004729 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004730}
4731
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004732bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4733 // Str - The format string. NOTE: this is NOT null-terminated!
4734 StringRef StrRef = FExpr->getString();
4735 const char *Str = StrRef.data();
4736 // Account for cases where the string literal is truncated in a declaration.
4737 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4738 assert(T && "String literal not of constant array type!");
4739 size_t TypeSize = T->getSize().getZExtValue();
4740 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4741 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4742 getLangOpts(),
4743 Context.getTargetInfo());
4744}
4745
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004746//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4747
4748// Returns the related absolute value function that is larger, of 0 if one
4749// does not exist.
4750static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4751 switch (AbsFunction) {
4752 default:
4753 return 0;
4754
4755 case Builtin::BI__builtin_abs:
4756 return Builtin::BI__builtin_labs;
4757 case Builtin::BI__builtin_labs:
4758 return Builtin::BI__builtin_llabs;
4759 case Builtin::BI__builtin_llabs:
4760 return 0;
4761
4762 case Builtin::BI__builtin_fabsf:
4763 return Builtin::BI__builtin_fabs;
4764 case Builtin::BI__builtin_fabs:
4765 return Builtin::BI__builtin_fabsl;
4766 case Builtin::BI__builtin_fabsl:
4767 return 0;
4768
4769 case Builtin::BI__builtin_cabsf:
4770 return Builtin::BI__builtin_cabs;
4771 case Builtin::BI__builtin_cabs:
4772 return Builtin::BI__builtin_cabsl;
4773 case Builtin::BI__builtin_cabsl:
4774 return 0;
4775
4776 case Builtin::BIabs:
4777 return Builtin::BIlabs;
4778 case Builtin::BIlabs:
4779 return Builtin::BIllabs;
4780 case Builtin::BIllabs:
4781 return 0;
4782
4783 case Builtin::BIfabsf:
4784 return Builtin::BIfabs;
4785 case Builtin::BIfabs:
4786 return Builtin::BIfabsl;
4787 case Builtin::BIfabsl:
4788 return 0;
4789
4790 case Builtin::BIcabsf:
4791 return Builtin::BIcabs;
4792 case Builtin::BIcabs:
4793 return Builtin::BIcabsl;
4794 case Builtin::BIcabsl:
4795 return 0;
4796 }
4797}
4798
4799// Returns the argument type of the absolute value function.
4800static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4801 unsigned AbsType) {
4802 if (AbsType == 0)
4803 return QualType();
4804
4805 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4806 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4807 if (Error != ASTContext::GE_None)
4808 return QualType();
4809
4810 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4811 if (!FT)
4812 return QualType();
4813
4814 if (FT->getNumParams() != 1)
4815 return QualType();
4816
4817 return FT->getParamType(0);
4818}
4819
4820// Returns the best absolute value function, or zero, based on type and
4821// current absolute value function.
4822static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4823 unsigned AbsFunctionKind) {
4824 unsigned BestKind = 0;
4825 uint64_t ArgSize = Context.getTypeSize(ArgType);
4826 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4827 Kind = getLargerAbsoluteValueFunction(Kind)) {
4828 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4829 if (Context.getTypeSize(ParamType) >= ArgSize) {
4830 if (BestKind == 0)
4831 BestKind = Kind;
4832 else if (Context.hasSameType(ParamType, ArgType)) {
4833 BestKind = Kind;
4834 break;
4835 }
4836 }
4837 }
4838 return BestKind;
4839}
4840
4841enum AbsoluteValueKind {
4842 AVK_Integer,
4843 AVK_Floating,
4844 AVK_Complex
4845};
4846
4847static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4848 if (T->isIntegralOrEnumerationType())
4849 return AVK_Integer;
4850 if (T->isRealFloatingType())
4851 return AVK_Floating;
4852 if (T->isAnyComplexType())
4853 return AVK_Complex;
4854
4855 llvm_unreachable("Type not integer, floating, or complex");
4856}
4857
4858// Changes the absolute value function to a different type. Preserves whether
4859// the function is a builtin.
4860static unsigned changeAbsFunction(unsigned AbsKind,
4861 AbsoluteValueKind ValueKind) {
4862 switch (ValueKind) {
4863 case AVK_Integer:
4864 switch (AbsKind) {
4865 default:
4866 return 0;
4867 case Builtin::BI__builtin_fabsf:
4868 case Builtin::BI__builtin_fabs:
4869 case Builtin::BI__builtin_fabsl:
4870 case Builtin::BI__builtin_cabsf:
4871 case Builtin::BI__builtin_cabs:
4872 case Builtin::BI__builtin_cabsl:
4873 return Builtin::BI__builtin_abs;
4874 case Builtin::BIfabsf:
4875 case Builtin::BIfabs:
4876 case Builtin::BIfabsl:
4877 case Builtin::BIcabsf:
4878 case Builtin::BIcabs:
4879 case Builtin::BIcabsl:
4880 return Builtin::BIabs;
4881 }
4882 case AVK_Floating:
4883 switch (AbsKind) {
4884 default:
4885 return 0;
4886 case Builtin::BI__builtin_abs:
4887 case Builtin::BI__builtin_labs:
4888 case Builtin::BI__builtin_llabs:
4889 case Builtin::BI__builtin_cabsf:
4890 case Builtin::BI__builtin_cabs:
4891 case Builtin::BI__builtin_cabsl:
4892 return Builtin::BI__builtin_fabsf;
4893 case Builtin::BIabs:
4894 case Builtin::BIlabs:
4895 case Builtin::BIllabs:
4896 case Builtin::BIcabsf:
4897 case Builtin::BIcabs:
4898 case Builtin::BIcabsl:
4899 return Builtin::BIfabsf;
4900 }
4901 case AVK_Complex:
4902 switch (AbsKind) {
4903 default:
4904 return 0;
4905 case Builtin::BI__builtin_abs:
4906 case Builtin::BI__builtin_labs:
4907 case Builtin::BI__builtin_llabs:
4908 case Builtin::BI__builtin_fabsf:
4909 case Builtin::BI__builtin_fabs:
4910 case Builtin::BI__builtin_fabsl:
4911 return Builtin::BI__builtin_cabsf;
4912 case Builtin::BIabs:
4913 case Builtin::BIlabs:
4914 case Builtin::BIllabs:
4915 case Builtin::BIfabsf:
4916 case Builtin::BIfabs:
4917 case Builtin::BIfabsl:
4918 return Builtin::BIcabsf;
4919 }
4920 }
4921 llvm_unreachable("Unable to convert function");
4922}
4923
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004924static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004925 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4926 if (!FnInfo)
4927 return 0;
4928
4929 switch (FDecl->getBuiltinID()) {
4930 default:
4931 return 0;
4932 case Builtin::BI__builtin_abs:
4933 case Builtin::BI__builtin_fabs:
4934 case Builtin::BI__builtin_fabsf:
4935 case Builtin::BI__builtin_fabsl:
4936 case Builtin::BI__builtin_labs:
4937 case Builtin::BI__builtin_llabs:
4938 case Builtin::BI__builtin_cabs:
4939 case Builtin::BI__builtin_cabsf:
4940 case Builtin::BI__builtin_cabsl:
4941 case Builtin::BIabs:
4942 case Builtin::BIlabs:
4943 case Builtin::BIllabs:
4944 case Builtin::BIfabs:
4945 case Builtin::BIfabsf:
4946 case Builtin::BIfabsl:
4947 case Builtin::BIcabs:
4948 case Builtin::BIcabsf:
4949 case Builtin::BIcabsl:
4950 return FDecl->getBuiltinID();
4951 }
4952 llvm_unreachable("Unknown Builtin type");
4953}
4954
4955// If the replacement is valid, emit a note with replacement function.
4956// Additionally, suggest including the proper header if not already included.
4957static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004958 unsigned AbsKind, QualType ArgType) {
4959 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004960 const char *HeaderName = nullptr;
4961 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004962 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4963 FunctionName = "std::abs";
4964 if (ArgType->isIntegralOrEnumerationType()) {
4965 HeaderName = "cstdlib";
4966 } else if (ArgType->isRealFloatingType()) {
4967 HeaderName = "cmath";
4968 } else {
4969 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004970 }
Richard Trieubeffb832014-04-15 23:47:53 +00004971
4972 // Lookup all std::abs
4973 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004974 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004975 R.suppressDiagnostics();
4976 S.LookupQualifiedName(R, Std);
4977
4978 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004979 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004980 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4981 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4982 } else {
4983 FDecl = dyn_cast<FunctionDecl>(I);
4984 }
4985 if (!FDecl)
4986 continue;
4987
4988 // Found std::abs(), check that they are the right ones.
4989 if (FDecl->getNumParams() != 1)
4990 continue;
4991
4992 // Check that the parameter type can handle the argument.
4993 QualType ParamType = FDecl->getParamDecl(0)->getType();
4994 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4995 S.Context.getTypeSize(ArgType) <=
4996 S.Context.getTypeSize(ParamType)) {
4997 // Found a function, don't need the header hint.
4998 EmitHeaderHint = false;
4999 break;
5000 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005001 }
Richard Trieubeffb832014-04-15 23:47:53 +00005002 }
5003 } else {
Eric Christopher02d5d862015-08-06 01:01:12 +00005004 FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
Richard Trieubeffb832014-04-15 23:47:53 +00005005 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5006
5007 if (HeaderName) {
5008 DeclarationName DN(&S.Context.Idents.get(FunctionName));
5009 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5010 R.suppressDiagnostics();
5011 S.LookupName(R, S.getCurScope());
5012
5013 if (R.isSingleResult()) {
5014 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5015 if (FD && FD->getBuiltinID() == AbsKind) {
5016 EmitHeaderHint = false;
5017 } else {
5018 return;
5019 }
5020 } else if (!R.empty()) {
5021 return;
5022 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005023 }
5024 }
5025
5026 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00005027 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005028
Richard Trieubeffb832014-04-15 23:47:53 +00005029 if (!HeaderName)
5030 return;
5031
5032 if (!EmitHeaderHint)
5033 return;
5034
Alp Toker5d96e0a2014-07-11 20:53:51 +00005035 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5036 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00005037}
5038
5039static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5040 if (!FDecl)
5041 return false;
5042
5043 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5044 return false;
5045
5046 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5047
5048 while (ND && ND->isInlineNamespace()) {
5049 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005050 }
Richard Trieubeffb832014-04-15 23:47:53 +00005051
5052 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5053 return false;
5054
5055 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5056 return false;
5057
5058 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005059}
5060
5061// Warn when using the wrong abs() function.
5062void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5063 const FunctionDecl *FDecl,
5064 IdentifierInfo *FnInfo) {
5065 if (Call->getNumArgs() != 1)
5066 return;
5067
5068 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00005069 bool IsStdAbs = IsFunctionStdAbs(FDecl);
5070 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005071 return;
5072
5073 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5074 QualType ParamType = Call->getArg(0)->getType();
5075
Alp Toker5d96e0a2014-07-11 20:53:51 +00005076 // Unsigned types cannot be negative. Suggest removing the absolute value
5077 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005078 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00005079 const char *FunctionName =
Eric Christopher02d5d862015-08-06 01:01:12 +00005080 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005081 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5082 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00005083 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005084 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5085 return;
5086 }
5087
David Majnemer7f77eb92015-11-15 03:04:34 +00005088 // Taking the absolute value of a pointer is very suspicious, they probably
5089 // wanted to index into an array, dereference a pointer, call a function, etc.
5090 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5091 unsigned DiagType = 0;
5092 if (ArgType->isFunctionType())
5093 DiagType = 1;
5094 else if (ArgType->isArrayType())
5095 DiagType = 2;
5096
5097 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5098 return;
5099 }
5100
Richard Trieubeffb832014-04-15 23:47:53 +00005101 // std::abs has overloads which prevent most of the absolute value problems
5102 // from occurring.
5103 if (IsStdAbs)
5104 return;
5105
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005106 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5107 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5108
5109 // The argument and parameter are the same kind. Check if they are the right
5110 // size.
5111 if (ArgValueKind == ParamValueKind) {
5112 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5113 return;
5114
5115 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5116 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5117 << FDecl << ArgType << ParamType;
5118
5119 if (NewAbsKind == 0)
5120 return;
5121
5122 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005123 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005124 return;
5125 }
5126
5127 // ArgValueKind != ParamValueKind
5128 // The wrong type of absolute value function was used. Attempt to find the
5129 // proper one.
5130 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5131 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5132 if (NewAbsKind == 0)
5133 return;
5134
5135 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5136 << FDecl << ParamValueKind << ArgValueKind;
5137
5138 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00005139 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00005140 return;
5141}
5142
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005143//===--- CHECK: Standard memory functions ---------------------------------===//
5144
Nico Weber0e6daef2013-12-26 23:38:39 +00005145/// \brief Takes the expression passed to the size_t parameter of functions
5146/// such as memcmp, strncat, etc and warns if it's a comparison.
5147///
5148/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5149static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5150 IdentifierInfo *FnName,
5151 SourceLocation FnLoc,
5152 SourceLocation RParenLoc) {
5153 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5154 if (!Size)
5155 return false;
5156
5157 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5158 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5159 return false;
5160
Nico Weber0e6daef2013-12-26 23:38:39 +00005161 SourceRange SizeRange = Size->getSourceRange();
5162 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5163 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00005164 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00005165 << FnName << FixItHint::CreateInsertion(
5166 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00005167 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00005168 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00005169 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00005170 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5171 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00005172
5173 return true;
5174}
5175
Reid Kleckner5fb5b122014-06-27 23:58:21 +00005176/// \brief Determine whether the given type is or contains a dynamic class type
5177/// (e.g., whether it has a vtable).
5178static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5179 bool &IsContained) {
5180 // Look through array types while ignoring qualifiers.
5181 const Type *Ty = T->getBaseElementTypeUnsafe();
5182 IsContained = false;
5183
5184 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5185 RD = RD ? RD->getDefinition() : nullptr;
5186 if (!RD)
5187 return nullptr;
5188
5189 if (RD->isDynamicClass())
5190 return RD;
5191
5192 // Check all the fields. If any bases were dynamic, the class is dynamic.
5193 // It's impossible for a class to transitively contain itself by value, so
5194 // infinite recursion is impossible.
5195 for (auto *FD : RD->fields()) {
5196 bool SubContained;
5197 if (const CXXRecordDecl *ContainedRD =
5198 getContainedDynamicClass(FD->getType(), SubContained)) {
5199 IsContained = true;
5200 return ContainedRD;
5201 }
5202 }
5203
5204 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00005205}
5206
Chandler Carruth889ed862011-06-21 23:04:20 +00005207/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005208/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00005209static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00005210 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005211 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5212 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5213 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005214
Craig Topperc3ec1492014-05-26 06:22:03 +00005215 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005216}
5217
Chandler Carruth889ed862011-06-21 23:04:20 +00005218/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00005219static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005220 if (const UnaryExprOrTypeTraitExpr *SizeOf =
5221 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5222 if (SizeOf->getKind() == clang::UETT_SizeOf)
5223 return SizeOf->getTypeOfArgument();
5224
5225 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00005226}
5227
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005228/// \brief Check for dangerous or invalid arguments to memset().
5229///
Chandler Carruthac687262011-06-03 06:23:57 +00005230/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005231/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5232/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005233///
5234/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005235void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00005236 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00005237 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00005238 assert(BId != 0);
5239
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005240 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00005241 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00005242 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00005243 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00005244 return;
5245
Anna Zaks22122702012-01-17 00:37:07 +00005246 unsigned LastArg = (BId == Builtin::BImemset ||
5247 BId == Builtin::BIstrndup ? 1 : 2);
5248 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005249 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005250
Nico Weber0e6daef2013-12-26 23:38:39 +00005251 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5252 Call->getLocStart(), Call->getRParenLoc()))
5253 return;
5254
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005255 // We have special checking when the length is a sizeof expression.
5256 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5257 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5258 llvm::FoldingSetNodeID SizeOfArgID;
5259
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005260 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5261 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005262 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005263
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005264 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005265 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005266 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005267 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005268
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005269 // Never warn about void type pointers. This can be used to suppress
5270 // false positives.
5271 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005272 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005273
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005274 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5275 // actually comparing the expressions for equality. Because computing the
5276 // expression IDs can be expensive, we only do this if the diagnostic is
5277 // enabled.
5278 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005279 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5280 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005281 // We only compute IDs for expressions if the warning is enabled, and
5282 // cache the sizeof arg's ID.
5283 if (SizeOfArgID == llvm::FoldingSetNodeID())
5284 SizeOfArg->Profile(SizeOfArgID, Context, true);
5285 llvm::FoldingSetNodeID DestID;
5286 Dest->Profile(DestID, Context, true);
5287 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005288 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5289 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005290 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005291 StringRef ReadableName = FnName->getName();
5292
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005293 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005294 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005295 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005296 if (!PointeeTy->isIncompleteType() &&
5297 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005298 ActionIdx = 2; // If the pointee's size is sizeof(char),
5299 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005300
5301 // If the function is defined as a builtin macro, do not show macro
5302 // expansion.
5303 SourceLocation SL = SizeOfArg->getExprLoc();
5304 SourceRange DSR = Dest->getSourceRange();
5305 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005306 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005307
5308 if (SM.isMacroArgExpansion(SL)) {
5309 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5310 SL = SM.getSpellingLoc(SL);
5311 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5312 SM.getSpellingLoc(DSR.getEnd()));
5313 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5314 SM.getSpellingLoc(SSR.getEnd()));
5315 }
5316
Anna Zaksd08d9152012-05-30 23:14:52 +00005317 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005318 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005319 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005320 << PointeeTy
5321 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005322 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005323 << SSR);
5324 DiagRuntimeBehavior(SL, SizeOfArg,
5325 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5326 << ActionIdx
5327 << SSR);
5328
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005329 break;
5330 }
5331 }
5332
5333 // Also check for cases where the sizeof argument is the exact same
5334 // type as the memory argument, and where it points to a user-defined
5335 // record type.
5336 if (SizeOfArgTy != QualType()) {
5337 if (PointeeTy->isRecordType() &&
5338 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5339 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5340 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5341 << FnName << SizeOfArgTy << ArgIdx
5342 << PointeeTy << Dest->getSourceRange()
5343 << LenExpr->getSourceRange());
5344 break;
5345 }
Nico Weberc5e73862011-06-14 16:14:58 +00005346 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005347 } else if (DestTy->isArrayType()) {
5348 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005349 }
Nico Weberc5e73862011-06-14 16:14:58 +00005350
Nico Weberc44b35e2015-03-21 17:37:46 +00005351 if (PointeeTy == QualType())
5352 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005353
Nico Weberc44b35e2015-03-21 17:37:46 +00005354 // Always complain about dynamic classes.
5355 bool IsContained;
5356 if (const CXXRecordDecl *ContainedRD =
5357 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005358
Nico Weberc44b35e2015-03-21 17:37:46 +00005359 unsigned OperationType = 0;
5360 // "overwritten" if we're warning about the destination for any call
5361 // but memcmp; otherwise a verb appropriate to the call.
5362 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5363 if (BId == Builtin::BImemcpy)
5364 OperationType = 1;
5365 else if(BId == Builtin::BImemmove)
5366 OperationType = 2;
5367 else if (BId == Builtin::BImemcmp)
5368 OperationType = 3;
5369 }
5370
John McCall31168b02011-06-15 23:02:42 +00005371 DiagRuntimeBehavior(
5372 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005373 PDiag(diag::warn_dyn_class_memaccess)
5374 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5375 << FnName << IsContained << ContainedRD << OperationType
5376 << Call->getCallee()->getSourceRange());
5377 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5378 BId != Builtin::BImemset)
5379 DiagRuntimeBehavior(
5380 Dest->getExprLoc(), Dest,
5381 PDiag(diag::warn_arc_object_memaccess)
5382 << ArgIdx << FnName << PointeeTy
5383 << Call->getCallee()->getSourceRange());
5384 else
5385 continue;
5386
5387 DiagRuntimeBehavior(
5388 Dest->getExprLoc(), Dest,
5389 PDiag(diag::note_bad_memaccess_silence)
5390 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5391 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005392 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005393
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005394}
5395
Ted Kremenek6865f772011-08-18 20:55:45 +00005396// A little helper routine: ignore addition and subtraction of integer literals.
5397// This intentionally does not ignore all integer constant expressions because
5398// we don't want to remove sizeof().
5399static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5400 Ex = Ex->IgnoreParenCasts();
5401
5402 for (;;) {
5403 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5404 if (!BO || !BO->isAdditiveOp())
5405 break;
5406
5407 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5408 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5409
5410 if (isa<IntegerLiteral>(RHS))
5411 Ex = LHS;
5412 else if (isa<IntegerLiteral>(LHS))
5413 Ex = RHS;
5414 else
5415 break;
5416 }
5417
5418 return Ex;
5419}
5420
Anna Zaks13b08572012-08-08 21:42:23 +00005421static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5422 ASTContext &Context) {
5423 // Only handle constant-sized or VLAs, but not flexible members.
5424 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5425 // Only issue the FIXIT for arrays of size > 1.
5426 if (CAT->getSize().getSExtValue() <= 1)
5427 return false;
5428 } else if (!Ty->isVariableArrayType()) {
5429 return false;
5430 }
5431 return true;
5432}
5433
Ted Kremenek6865f772011-08-18 20:55:45 +00005434// Warn if the user has made the 'size' argument to strlcpy or strlcat
5435// be the size of the source, instead of the destination.
5436void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5437 IdentifierInfo *FnName) {
5438
5439 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005440 unsigned NumArgs = Call->getNumArgs();
5441 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005442 return;
5443
5444 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5445 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005446 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005447
5448 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5449 Call->getLocStart(), Call->getRParenLoc()))
5450 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005451
5452 // Look for 'strlcpy(dst, x, sizeof(x))'
5453 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5454 CompareWithSrc = Ex;
5455 else {
5456 // Look for 'strlcpy(dst, x, strlen(x))'
5457 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005458 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5459 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005460 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5461 }
5462 }
5463
5464 if (!CompareWithSrc)
5465 return;
5466
5467 // Determine if the argument to sizeof/strlen is equal to the source
5468 // argument. In principle there's all kinds of things you could do
5469 // here, for instance creating an == expression and evaluating it with
5470 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5471 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5472 if (!SrcArgDRE)
5473 return;
5474
5475 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5476 if (!CompareWithSrcDRE ||
5477 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5478 return;
5479
5480 const Expr *OriginalSizeArg = Call->getArg(2);
5481 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5482 << OriginalSizeArg->getSourceRange() << FnName;
5483
5484 // Output a FIXIT hint if the destination is an array (rather than a
5485 // pointer to an array). This could be enhanced to handle some
5486 // pointers if we know the actual size, like if DstArg is 'array+2'
5487 // we could say 'sizeof(array)-2'.
5488 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005489 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005490 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005491
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005492 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005493 llvm::raw_svector_ostream OS(sizeString);
5494 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005495 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005496 OS << ")";
5497
5498 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5499 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5500 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005501}
5502
Anna Zaks314cd092012-02-01 19:08:57 +00005503/// Check if two expressions refer to the same declaration.
5504static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5505 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5506 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5507 return D1->getDecl() == D2->getDecl();
5508 return false;
5509}
5510
5511static const Expr *getStrlenExprArg(const Expr *E) {
5512 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5513 const FunctionDecl *FD = CE->getDirectCallee();
5514 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005515 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005516 return CE->getArg(0)->IgnoreParenCasts();
5517 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005518 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005519}
5520
5521// Warn on anti-patterns as the 'size' argument to strncat.
5522// The correct size argument should look like following:
5523// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5524void Sema::CheckStrncatArguments(const CallExpr *CE,
5525 IdentifierInfo *FnName) {
5526 // Don't crash if the user has the wrong number of arguments.
5527 if (CE->getNumArgs() < 3)
5528 return;
5529 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5530 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5531 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5532
Nico Weber0e6daef2013-12-26 23:38:39 +00005533 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5534 CE->getRParenLoc()))
5535 return;
5536
Anna Zaks314cd092012-02-01 19:08:57 +00005537 // Identify common expressions, which are wrongly used as the size argument
5538 // to strncat and may lead to buffer overflows.
5539 unsigned PatternType = 0;
5540 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5541 // - sizeof(dst)
5542 if (referToTheSameDecl(SizeOfArg, DstArg))
5543 PatternType = 1;
5544 // - sizeof(src)
5545 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5546 PatternType = 2;
5547 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5548 if (BE->getOpcode() == BO_Sub) {
5549 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5550 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5551 // - sizeof(dst) - strlen(dst)
5552 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5553 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5554 PatternType = 1;
5555 // - sizeof(src) - (anything)
5556 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5557 PatternType = 2;
5558 }
5559 }
5560
5561 if (PatternType == 0)
5562 return;
5563
Anna Zaks5069aa32012-02-03 01:27:37 +00005564 // Generate the diagnostic.
5565 SourceLocation SL = LenArg->getLocStart();
5566 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005567 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005568
5569 // If the function is defined as a builtin macro, do not show macro expansion.
5570 if (SM.isMacroArgExpansion(SL)) {
5571 SL = SM.getSpellingLoc(SL);
5572 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5573 SM.getSpellingLoc(SR.getEnd()));
5574 }
5575
Anna Zaks13b08572012-08-08 21:42:23 +00005576 // Check if the destination is an array (rather than a pointer to an array).
5577 QualType DstTy = DstArg->getType();
5578 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5579 Context);
5580 if (!isKnownSizeArray) {
5581 if (PatternType == 1)
5582 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5583 else
5584 Diag(SL, diag::warn_strncat_src_size) << SR;
5585 return;
5586 }
5587
Anna Zaks314cd092012-02-01 19:08:57 +00005588 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005589 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005590 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005591 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005592
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005593 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005594 llvm::raw_svector_ostream OS(sizeString);
5595 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005596 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005597 OS << ") - ";
5598 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005599 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005600 OS << ") - 1";
5601
Anna Zaks5069aa32012-02-03 01:27:37 +00005602 Diag(SL, diag::note_strncat_wrong_size)
5603 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005604}
5605
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005606//===--- CHECK: Return Address of Stack Variable --------------------------===//
5607
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005608static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5609 Decl *ParentDecl);
5610static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5611 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005612
5613/// CheckReturnStackAddr - Check if a return statement returns the address
5614/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005615static void
5616CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5617 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005618
Craig Topperc3ec1492014-05-26 06:22:03 +00005619 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005620 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005621
5622 // Perform checking for returned stack addresses, local blocks,
5623 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005624 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005625 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005626 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005627 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005628 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005629 }
5630
Craig Topperc3ec1492014-05-26 06:22:03 +00005631 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005632 return; // Nothing suspicious was found.
5633
5634 SourceLocation diagLoc;
5635 SourceRange diagRange;
5636 if (refVars.empty()) {
5637 diagLoc = stackE->getLocStart();
5638 diagRange = stackE->getSourceRange();
5639 } else {
5640 // We followed through a reference variable. 'stackE' contains the
5641 // problematic expression but we will warn at the return statement pointing
5642 // at the reference variable. We will later display the "trail" of
5643 // reference variables using notes.
5644 diagLoc = refVars[0]->getLocStart();
5645 diagRange = refVars[0]->getSourceRange();
5646 }
5647
5648 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Craig Topperda7b27f2015-11-17 05:40:09 +00005649 S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005650 << DR->getDecl()->getDeclName() << diagRange;
5651 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005652 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005653 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005654 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005655 } else { // local temporary.
Craig Topperda7b27f2015-11-17 05:40:09 +00005656 S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5657 << lhsType->isReferenceType() << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005658 }
5659
5660 // Display the "trail" of reference variables that we followed until we
5661 // found the problematic expression using notes.
5662 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5663 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5664 // If this var binds to another reference var, show the range of the next
5665 // var, otherwise the var binds to the problematic expression, in which case
5666 // show the range of the expression.
5667 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5668 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005669 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5670 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005671 }
5672}
5673
5674/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5675/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005676/// to a location on the stack, a local block, an address of a label, or a
5677/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005678/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005679/// encounter a subexpression that (1) clearly does not lead to one of the
5680/// above problematic expressions (2) is something we cannot determine leads to
5681/// a problematic expression based on such local checking.
5682///
5683/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5684/// the expression that they point to. Such variables are added to the
5685/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005686///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005687/// EvalAddr processes expressions that are pointers that are used as
5688/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005689/// At the base case of the recursion is a check for the above problematic
5690/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005691///
5692/// This implementation handles:
5693///
5694/// * pointer-to-pointer casts
5695/// * implicit conversions from array references to pointers
5696/// * taking the address of fields
5697/// * arbitrary interplay between "&" and "*" operators
5698/// * pointer arithmetic from an address of a stack variable
5699/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005700static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5701 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005702 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005703 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005704
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005705 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005706 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005707 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005708 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005709 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005710
Peter Collingbourne91147592011-04-15 00:35:48 +00005711 E = E->IgnoreParens();
5712
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005713 // Our "symbolic interpreter" is just a dispatch off the currently
5714 // viewed AST node. We then recursively traverse the AST by calling
5715 // EvalAddr and EvalVal appropriately.
5716 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005717 case Stmt::DeclRefExprClass: {
5718 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5719
Richard Smith40f08eb2014-01-30 22:05:38 +00005720 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005721 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005722 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005723
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005724 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5725 // If this is a reference variable, follow through to the expression that
5726 // it points to.
5727 if (V->hasLocalStorage() &&
5728 V->getType()->isReferenceType() && V->hasInit()) {
5729 // Add the reference variable to the "trail".
5730 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005731 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005732 }
5733
Craig Topperc3ec1492014-05-26 06:22:03 +00005734 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005735 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005736
Chris Lattner934edb22007-12-28 05:31:15 +00005737 case Stmt::UnaryOperatorClass: {
5738 // The only unary operator that make sense to handle here
5739 // is AddrOf. All others don't make sense as pointers.
5740 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005741
John McCalle3027922010-08-25 11:45:40 +00005742 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005743 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005744 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005745 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005746 }
Mike Stump11289f42009-09-09 15:08:12 +00005747
Chris Lattner934edb22007-12-28 05:31:15 +00005748 case Stmt::BinaryOperatorClass: {
5749 // Handle pointer arithmetic. All other binary operators are not valid
5750 // in this context.
5751 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005752 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005753
John McCalle3027922010-08-25 11:45:40 +00005754 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005755 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005756
Chris Lattner934edb22007-12-28 05:31:15 +00005757 Expr *Base = B->getLHS();
5758
5759 // Determine which argument is the real pointer base. It could be
5760 // the RHS argument instead of the LHS.
5761 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005762
Chris Lattner934edb22007-12-28 05:31:15 +00005763 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005764 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005765 }
Steve Naroff2752a172008-09-10 19:17:48 +00005766
Chris Lattner934edb22007-12-28 05:31:15 +00005767 // For conditional operators we need to see if either the LHS or RHS are
5768 // valid DeclRefExpr*s. If one of them is valid, we return it.
5769 case Stmt::ConditionalOperatorClass: {
5770 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005771
Chris Lattner934edb22007-12-28 05:31:15 +00005772 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005773 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5774 if (Expr *LHSExpr = C->getLHS()) {
5775 // In C++, we can have a throw-expression, which has 'void' type.
5776 if (!LHSExpr->getType()->isVoidType())
5777 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005778 return LHS;
5779 }
Chris Lattner934edb22007-12-28 05:31:15 +00005780
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005781 // In C++, we can have a throw-expression, which has 'void' type.
5782 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005783 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005784
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005785 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005786 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005787
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005788 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005789 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005790 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005791 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005792
5793 case Stmt::AddrLabelExprClass:
5794 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005795
John McCall28fc7092011-11-10 05:35:25 +00005796 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005797 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5798 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005799
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005800 // For casts, we need to handle conversions from arrays to
5801 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005802 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005803 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005804 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005805 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005806 case Stmt::CXXStaticCastExprClass:
5807 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005808 case Stmt::CXXConstCastExprClass:
5809 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005810 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5811 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005812 case CK_LValueToRValue:
5813 case CK_NoOp:
5814 case CK_BaseToDerived:
5815 case CK_DerivedToBase:
5816 case CK_UncheckedDerivedToBase:
5817 case CK_Dynamic:
5818 case CK_CPointerToObjCPointerCast:
5819 case CK_BlockPointerToObjCPointerCast:
5820 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005821 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005822
5823 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005824 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005825
Richard Trieudadefde2014-07-02 04:39:38 +00005826 case CK_BitCast:
5827 if (SubExpr->getType()->isAnyPointerType() ||
5828 SubExpr->getType()->isBlockPointerType() ||
5829 SubExpr->getType()->isObjCQualifiedIdType())
5830 return EvalAddr(SubExpr, refVars, ParentDecl);
5831 else
5832 return nullptr;
5833
Eli Friedman8195ad72012-02-23 23:04:32 +00005834 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005835 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005836 }
Chris Lattner934edb22007-12-28 05:31:15 +00005837 }
Mike Stump11289f42009-09-09 15:08:12 +00005838
Douglas Gregorfe314812011-06-21 17:03:29 +00005839 case Stmt::MaterializeTemporaryExprClass:
5840 if (Expr *Result = EvalAddr(
5841 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005842 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005843 return Result;
5844
5845 return E;
5846
Chris Lattner934edb22007-12-28 05:31:15 +00005847 // Everything else: we simply don't reason about them.
5848 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005849 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005850 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005851}
Mike Stump11289f42009-09-09 15:08:12 +00005852
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005853
5854/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5855/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005856static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5857 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005858do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005859 // We should only be called for evaluating non-pointer expressions, or
5860 // expressions with a pointer type that are not used as references but instead
5861 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005862
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005863 // Our "symbolic interpreter" is just a dispatch off the currently
5864 // viewed AST node. We then recursively traverse the AST by calling
5865 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005866
5867 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005868 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005869 case Stmt::ImplicitCastExprClass: {
5870 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005871 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005872 E = IE->getSubExpr();
5873 continue;
5874 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005875 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005876 }
5877
John McCall28fc7092011-11-10 05:35:25 +00005878 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005879 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005880
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005881 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005882 // When we hit a DeclRefExpr we are looking at code that refers to a
5883 // variable's name. If it's not a reference variable we check if it has
5884 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005885 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005886
Richard Smith40f08eb2014-01-30 22:05:38 +00005887 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005888 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005889 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005890
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005891 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5892 // Check if it refers to itself, e.g. "int& i = i;".
5893 if (V == ParentDecl)
5894 return DR;
5895
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005896 if (V->hasLocalStorage()) {
5897 if (!V->getType()->isReferenceType())
5898 return DR;
5899
5900 // Reference variable, follow through to the expression that
5901 // it points to.
5902 if (V->hasInit()) {
5903 // Add the reference variable to the "trail".
5904 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005905 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005906 }
5907 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005908 }
Mike Stump11289f42009-09-09 15:08:12 +00005909
Craig Topperc3ec1492014-05-26 06:22:03 +00005910 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005911 }
Mike Stump11289f42009-09-09 15:08:12 +00005912
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005913 case Stmt::UnaryOperatorClass: {
5914 // The only unary operator that make sense to handle here
5915 // is Deref. All others don't resolve to a "name." This includes
5916 // handling all sorts of rvalues passed to a unary operator.
5917 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005918
John McCalle3027922010-08-25 11:45:40 +00005919 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005920 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005921
Craig Topperc3ec1492014-05-26 06:22:03 +00005922 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005923 }
Mike Stump11289f42009-09-09 15:08:12 +00005924
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005925 case Stmt::ArraySubscriptExprClass: {
5926 // Array subscripts are potential references to data on the stack. We
5927 // retrieve the DeclRefExpr* for the array variable if it indeed
5928 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005929 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005930 }
Mike Stump11289f42009-09-09 15:08:12 +00005931
Alexey Bataev1a3320e2015-08-25 14:24:04 +00005932 case Stmt::OMPArraySectionExprClass: {
5933 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5934 ParentDecl);
5935 }
5936
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005937 case Stmt::ConditionalOperatorClass: {
5938 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005939 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005940 ConditionalOperator *C = cast<ConditionalOperator>(E);
5941
Anders Carlsson801c5c72007-11-30 19:04:31 +00005942 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005943 if (Expr *LHSExpr = C->getLHS()) {
5944 // In C++, we can have a throw-expression, which has 'void' type.
5945 if (!LHSExpr->getType()->isVoidType())
5946 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5947 return LHS;
5948 }
5949
5950 // In C++, we can have a throw-expression, which has 'void' type.
5951 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005952 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005953
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005954 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005955 }
Mike Stump11289f42009-09-09 15:08:12 +00005956
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005957 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005958 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005959 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005960
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005961 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005962 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005963 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005964
5965 // Check whether the member type is itself a reference, in which case
5966 // we're not going to refer to the member, but to what the member refers to.
5967 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005968 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005969
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005970 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005971 }
Mike Stump11289f42009-09-09 15:08:12 +00005972
Douglas Gregorfe314812011-06-21 17:03:29 +00005973 case Stmt::MaterializeTemporaryExprClass:
5974 if (Expr *Result = EvalVal(
5975 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005976 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005977 return Result;
5978
5979 return E;
5980
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005981 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005982 // Check that we don't return or take the address of a reference to a
5983 // temporary. This is only useful in C++.
5984 if (!E->isTypeDependent() && E->isRValue())
5985 return E;
5986
5987 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005988 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005989 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005990} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005991}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005992
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005993void
5994Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5995 SourceLocation ReturnLoc,
5996 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005997 const AttrVec *Attrs,
5998 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005999 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6000
6001 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00006002 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6003 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00006004 CheckNonNullExpr(*this, RetValExp))
6005 Diag(ReturnLoc, diag::warn_null_ret)
6006 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00006007
6008 // C++11 [basic.stc.dynamic.allocation]p4:
6009 // If an allocation function declared with a non-throwing
6010 // exception-specification fails to allocate storage, it shall return
6011 // a null pointer. Any other allocation function that fails to allocate
6012 // storage shall indicate failure only by throwing an exception [...]
6013 if (FD) {
6014 OverloadedOperatorKind Op = FD->getOverloadedOperator();
6015 if (Op == OO_New || Op == OO_Array_New) {
6016 const FunctionProtoType *Proto
6017 = FD->getType()->castAs<FunctionProtoType>();
6018 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6019 CheckNonNullExpr(*this, RetValExp))
6020 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6021 << FD << getLangOpts().CPlusPlus11;
6022 }
6023 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00006024}
6025
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006026//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6027
6028/// Check for comparisons of floating point operands using != and ==.
6029/// Issue a warning if these are no self-comparisons, as they are not likely
6030/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00006031void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00006032 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6033 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006034
6035 // Special case: check for x == x (which is OK).
6036 // Do not emit warnings for such cases.
6037 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6038 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6039 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00006040 return;
Mike Stump11289f42009-09-09 15:08:12 +00006041
6042
Ted Kremenekeda40e22007-11-29 00:59:04 +00006043 // Special case: check for comparisons against literals that can be exactly
6044 // represented by APFloat. In such cases, do not emit a warning. This
6045 // is a heuristic: often comparison against such literals are used to
6046 // detect if a value in a variable has not changed. This clearly can
6047 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00006048 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6049 if (FLL->isExact())
6050 return;
6051 } else
6052 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6053 if (FLR->isExact())
6054 return;
Mike Stump11289f42009-09-09 15:08:12 +00006055
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006056 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00006057 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006058 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006059 return;
Mike Stump11289f42009-09-09 15:08:12 +00006060
David Blaikie1f4ff152012-07-16 20:47:22 +00006061 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00006062 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00006063 return;
Mike Stump11289f42009-09-09 15:08:12 +00006064
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006065 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00006066 Diag(Loc, diag::warn_floatingpoint_eq)
6067 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00006068}
John McCallca01b222010-01-04 23:21:16 +00006069
John McCall70aa5392010-01-06 05:24:50 +00006070//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6071//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00006072
John McCall70aa5392010-01-06 05:24:50 +00006073namespace {
John McCallca01b222010-01-04 23:21:16 +00006074
John McCall70aa5392010-01-06 05:24:50 +00006075/// Structure recording the 'active' range of an integer-valued
6076/// expression.
6077struct IntRange {
6078 /// The number of bits active in the int.
6079 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00006080
John McCall70aa5392010-01-06 05:24:50 +00006081 /// True if the int is known not to have negative values.
6082 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00006083
John McCall70aa5392010-01-06 05:24:50 +00006084 IntRange(unsigned Width, bool NonNegative)
6085 : Width(Width), NonNegative(NonNegative)
6086 {}
John McCallca01b222010-01-04 23:21:16 +00006087
John McCall817d4af2010-11-10 23:38:19 +00006088 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00006089 static IntRange forBoolType() {
6090 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00006091 }
6092
John McCall817d4af2010-11-10 23:38:19 +00006093 /// Returns the range of an opaque value of the given integral type.
6094 static IntRange forValueOfType(ASTContext &C, QualType T) {
6095 return forValueOfCanonicalType(C,
6096 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00006097 }
6098
John McCall817d4af2010-11-10 23:38:19 +00006099 /// Returns the range of an opaque value of a canonical integral type.
6100 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00006101 assert(T->isCanonicalUnqualified());
6102
6103 if (const VectorType *VT = dyn_cast<VectorType>(T))
6104 T = VT->getElementType().getTypePtr();
6105 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6106 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006107 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6108 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00006109
David Majnemer6a426652013-06-07 22:07:20 +00006110 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00006111 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00006112 EnumDecl *Enum = ET->getDecl();
6113 if (!Enum->isCompleteDefinition())
6114 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00006115
David Majnemer6a426652013-06-07 22:07:20 +00006116 unsigned NumPositive = Enum->getNumPositiveBits();
6117 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00006118
David Majnemer6a426652013-06-07 22:07:20 +00006119 if (NumNegative == 0)
6120 return IntRange(NumPositive, true/*NonNegative*/);
6121 else
6122 return IntRange(std::max(NumPositive + 1, NumNegative),
6123 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00006124 }
John McCall70aa5392010-01-06 05:24:50 +00006125
6126 const BuiltinType *BT = cast<BuiltinType>(T);
6127 assert(BT->isInteger());
6128
6129 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6130 }
6131
John McCall817d4af2010-11-10 23:38:19 +00006132 /// Returns the "target" range of a canonical integral type, i.e.
6133 /// the range of values expressible in the type.
6134 ///
6135 /// This matches forValueOfCanonicalType except that enums have the
6136 /// full range of their type, not the range of their enumerators.
6137 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6138 assert(T->isCanonicalUnqualified());
6139
6140 if (const VectorType *VT = dyn_cast<VectorType>(T))
6141 T = VT->getElementType().getTypePtr();
6142 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6143 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006144 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6145 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006146 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00006147 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00006148
6149 const BuiltinType *BT = cast<BuiltinType>(T);
6150 assert(BT->isInteger());
6151
6152 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6153 }
6154
6155 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00006156 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00006157 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00006158 L.NonNegative && R.NonNegative);
6159 }
6160
John McCall817d4af2010-11-10 23:38:19 +00006161 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00006162 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00006163 return IntRange(std::min(L.Width, R.Width),
6164 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00006165 }
6166};
6167
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006168static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
6169 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006170 if (value.isSigned() && value.isNegative())
6171 return IntRange(value.getMinSignedBits(), false);
6172
6173 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00006174 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006175
6176 // isNonNegative() just checks the sign bit without considering
6177 // signedness.
6178 return IntRange(value.getActiveBits(), true);
6179}
6180
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006181static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6182 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006183 if (result.isInt())
6184 return GetValueRange(C, result.getInt(), MaxWidth);
6185
6186 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00006187 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6188 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6189 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6190 R = IntRange::join(R, El);
6191 }
John McCall70aa5392010-01-06 05:24:50 +00006192 return R;
6193 }
6194
6195 if (result.isComplexInt()) {
6196 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6197 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6198 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00006199 }
6200
6201 // This can happen with lossless casts to intptr_t of "based" lvalues.
6202 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00006203 // FIXME: The only reason we need to pass the type in here is to get
6204 // the sign right on this one case. It would be nice if APValue
6205 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006206 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00006207 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00006208}
John McCall70aa5392010-01-06 05:24:50 +00006209
Eli Friedmane6d33952013-07-08 20:20:06 +00006210static QualType GetExprType(Expr *E) {
6211 QualType Ty = E->getType();
6212 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6213 Ty = AtomicRHS->getValueType();
6214 return Ty;
6215}
6216
John McCall70aa5392010-01-06 05:24:50 +00006217/// Pseudo-evaluate the given integer expression, estimating the
6218/// range of values it might take.
6219///
6220/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006221static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00006222 E = E->IgnoreParens();
6223
6224 // Try a full evaluation first.
6225 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006226 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00006227 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00006228
6229 // I think we only want to look through implicit casts here; if the
6230 // user has an explicit widening cast, we should treat the value as
6231 // being of the new, wider type.
6232 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00006233 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00006234 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6235
Eli Friedmane6d33952013-07-08 20:20:06 +00006236 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00006237
John McCalle3027922010-08-25 11:45:40 +00006238 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00006239
John McCall70aa5392010-01-06 05:24:50 +00006240 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00006241 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00006242 return OutputTypeRange;
6243
6244 IntRange SubRange
6245 = GetExprRange(C, CE->getSubExpr(),
6246 std::min(MaxWidth, OutputTypeRange.Width));
6247
6248 // Bail out if the subexpr's range is as wide as the cast type.
6249 if (SubRange.Width >= OutputTypeRange.Width)
6250 return OutputTypeRange;
6251
6252 // Otherwise, we take the smaller width, and we're non-negative if
6253 // either the output type or the subexpr is.
6254 return IntRange(SubRange.Width,
6255 SubRange.NonNegative || OutputTypeRange.NonNegative);
6256 }
6257
6258 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6259 // If we can fold the condition, just take that operand.
6260 bool CondResult;
6261 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6262 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6263 : CO->getFalseExpr(),
6264 MaxWidth);
6265
6266 // Otherwise, conservatively merge.
6267 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6268 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6269 return IntRange::join(L, R);
6270 }
6271
6272 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6273 switch (BO->getOpcode()) {
6274
6275 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006276 case BO_LAnd:
6277 case BO_LOr:
6278 case BO_LT:
6279 case BO_GT:
6280 case BO_LE:
6281 case BO_GE:
6282 case BO_EQ:
6283 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006284 return IntRange::forBoolType();
6285
John McCallc3688382011-07-13 06:35:24 +00006286 // The type of the assignments is the type of the LHS, so the RHS
6287 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006288 case BO_MulAssign:
6289 case BO_DivAssign:
6290 case BO_RemAssign:
6291 case BO_AddAssign:
6292 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006293 case BO_XorAssign:
6294 case BO_OrAssign:
6295 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006296 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006297
John McCallc3688382011-07-13 06:35:24 +00006298 // Simple assignments just pass through the RHS, which will have
6299 // been coerced to the LHS type.
6300 case BO_Assign:
6301 // TODO: bitfields?
6302 return GetExprRange(C, BO->getRHS(), MaxWidth);
6303
John McCall70aa5392010-01-06 05:24:50 +00006304 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006305 case BO_PtrMemD:
6306 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006307 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006308
John McCall2ce81ad2010-01-06 22:07:33 +00006309 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006310 case BO_And:
6311 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006312 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6313 GetExprRange(C, BO->getRHS(), MaxWidth));
6314
John McCall70aa5392010-01-06 05:24:50 +00006315 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006316 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006317 // ...except that we want to treat '1 << (blah)' as logically
6318 // positive. It's an important idiom.
6319 if (IntegerLiteral *I
6320 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6321 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006322 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006323 return IntRange(R.Width, /*NonNegative*/ true);
6324 }
6325 }
6326 // fallthrough
6327
John McCalle3027922010-08-25 11:45:40 +00006328 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006329 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006330
John McCall2ce81ad2010-01-06 22:07:33 +00006331 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006332 case BO_Shr:
6333 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006334 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6335
6336 // If the shift amount is a positive constant, drop the width by
6337 // that much.
6338 llvm::APSInt shift;
6339 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6340 shift.isNonNegative()) {
6341 unsigned zext = shift.getZExtValue();
6342 if (zext >= L.Width)
6343 L.Width = (L.NonNegative ? 0 : 1);
6344 else
6345 L.Width -= zext;
6346 }
6347
6348 return L;
6349 }
6350
6351 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006352 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006353 return GetExprRange(C, BO->getRHS(), MaxWidth);
6354
John McCall2ce81ad2010-01-06 22:07:33 +00006355 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006356 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006357 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006358 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006359 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006360
John McCall51431812011-07-14 22:39:48 +00006361 // The width of a division result is mostly determined by the size
6362 // of the LHS.
6363 case BO_Div: {
6364 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006365 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006366 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6367
6368 // If the divisor is constant, use that.
6369 llvm::APSInt divisor;
6370 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6371 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6372 if (log2 >= L.Width)
6373 L.Width = (L.NonNegative ? 0 : 1);
6374 else
6375 L.Width = std::min(L.Width - log2, MaxWidth);
6376 return L;
6377 }
6378
6379 // Otherwise, just use the LHS's width.
6380 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6381 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6382 }
6383
6384 // The result of a remainder can't be larger than the result of
6385 // either side.
6386 case BO_Rem: {
6387 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006388 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006389 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6390 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6391
6392 IntRange meet = IntRange::meet(L, R);
6393 meet.Width = std::min(meet.Width, MaxWidth);
6394 return meet;
6395 }
6396
6397 // The default behavior is okay for these.
6398 case BO_Mul:
6399 case BO_Add:
6400 case BO_Xor:
6401 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006402 break;
6403 }
6404
John McCall51431812011-07-14 22:39:48 +00006405 // The default case is to treat the operation as if it were closed
6406 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006407 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6408 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6409 return IntRange::join(L, R);
6410 }
6411
6412 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6413 switch (UO->getOpcode()) {
6414 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006415 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006416 return IntRange::forBoolType();
6417
6418 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006419 case UO_Deref:
6420 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006421 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006422
6423 default:
6424 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6425 }
6426 }
6427
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006428 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6429 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6430
John McCalld25db7e2013-05-06 21:39:12 +00006431 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006432 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006433 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006434
Eli Friedmane6d33952013-07-08 20:20:06 +00006435 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006436}
John McCall263a48b2010-01-04 23:31:57 +00006437
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006438static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006439 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006440}
6441
John McCall263a48b2010-01-04 23:31:57 +00006442/// Checks whether the given value, which currently has the given
6443/// source semantics, has the same value when coerced through the
6444/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006445static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6446 const llvm::fltSemantics &Src,
6447 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006448 llvm::APFloat truncated = value;
6449
6450 bool ignored;
6451 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6452 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6453
6454 return truncated.bitwiseIsEqual(value);
6455}
6456
6457/// Checks whether the given value, which currently has the given
6458/// source semantics, has the same value when coerced through the
6459/// target semantics.
6460///
6461/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006462static bool IsSameFloatAfterCast(const APValue &value,
6463 const llvm::fltSemantics &Src,
6464 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006465 if (value.isFloat())
6466 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6467
6468 if (value.isVector()) {
6469 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6470 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6471 return false;
6472 return true;
6473 }
6474
6475 assert(value.isComplexFloat());
6476 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6477 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6478}
6479
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006480static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006481
Ted Kremenek6274be42010-09-23 21:43:44 +00006482static bool IsZero(Sema &S, Expr *E) {
6483 // Suppress cases where we are comparing against an enum constant.
6484 if (const DeclRefExpr *DR =
6485 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6486 if (isa<EnumConstantDecl>(DR->getDecl()))
6487 return false;
6488
6489 // Suppress cases where the '0' value is expanded from a macro.
6490 if (E->getLocStart().isMacroID())
6491 return false;
6492
John McCallcc7e5bf2010-05-06 08:58:33 +00006493 llvm::APSInt Value;
6494 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6495}
6496
John McCall2551c1b2010-10-06 00:25:24 +00006497static bool HasEnumType(Expr *E) {
6498 // Strip off implicit integral promotions.
6499 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006500 if (ICE->getCastKind() != CK_IntegralCast &&
6501 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006502 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006503 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006504 }
6505
6506 return E->getType()->isEnumeralType();
6507}
6508
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006509static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006510 // Disable warning in template instantiations.
6511 if (!S.ActiveTemplateInstantiations.empty())
6512 return;
6513
John McCalle3027922010-08-25 11:45:40 +00006514 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006515 if (E->isValueDependent())
6516 return;
6517
John McCalle3027922010-08-25 11:45:40 +00006518 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006519 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006520 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006521 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006522 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006523 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006524 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006525 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006526 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006527 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006528 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006529 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006530 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006531 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006532 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006533 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6534 }
6535}
6536
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006537static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006538 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006539 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006540 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006541 // Disable warning in template instantiations.
6542 if (!S.ActiveTemplateInstantiations.empty())
6543 return;
6544
Richard Trieu0f097742014-04-04 04:13:47 +00006545 // TODO: Investigate using GetExprRange() to get tighter bounds
6546 // on the bit ranges.
6547 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006548 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006549 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006550 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6551 unsigned OtherWidth = OtherRange.Width;
6552
6553 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6554
Richard Trieu560910c2012-11-14 22:50:24 +00006555 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006556 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006557 return;
6558
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006559 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006560 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006561
Richard Trieu0f097742014-04-04 04:13:47 +00006562 // Used for diagnostic printout.
6563 enum {
6564 LiteralConstant = 0,
6565 CXXBoolLiteralTrue,
6566 CXXBoolLiteralFalse
6567 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006568
Richard Trieu0f097742014-04-04 04:13:47 +00006569 if (!OtherIsBooleanType) {
6570 QualType ConstantT = Constant->getType();
6571 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006572
Richard Trieu0f097742014-04-04 04:13:47 +00006573 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6574 return;
6575 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6576 "comparison with non-integer type");
6577
6578 bool ConstantSigned = ConstantT->isSignedIntegerType();
6579 bool CommonSigned = CommonT->isSignedIntegerType();
6580
6581 bool EqualityOnly = false;
6582
6583 if (CommonSigned) {
6584 // The common type is signed, therefore no signed to unsigned conversion.
6585 if (!OtherRange.NonNegative) {
6586 // Check that the constant is representable in type OtherT.
6587 if (ConstantSigned) {
6588 if (OtherWidth >= Value.getMinSignedBits())
6589 return;
6590 } else { // !ConstantSigned
6591 if (OtherWidth >= Value.getActiveBits() + 1)
6592 return;
6593 }
6594 } else { // !OtherSigned
6595 // Check that the constant is representable in type OtherT.
6596 // Negative values are out of range.
6597 if (ConstantSigned) {
6598 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6599 return;
6600 } else { // !ConstantSigned
6601 if (OtherWidth >= Value.getActiveBits())
6602 return;
6603 }
Richard Trieu560910c2012-11-14 22:50:24 +00006604 }
Richard Trieu0f097742014-04-04 04:13:47 +00006605 } else { // !CommonSigned
6606 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006607 if (OtherWidth >= Value.getActiveBits())
6608 return;
Craig Toppercf360162014-06-18 05:13:11 +00006609 } else { // OtherSigned
6610 assert(!ConstantSigned &&
6611 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006612 // Check to see if the constant is representable in OtherT.
6613 if (OtherWidth > Value.getActiveBits())
6614 return;
6615 // Check to see if the constant is equivalent to a negative value
6616 // cast to CommonT.
6617 if (S.Context.getIntWidth(ConstantT) ==
6618 S.Context.getIntWidth(CommonT) &&
6619 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6620 return;
6621 // The constant value rests between values that OtherT can represent
6622 // after conversion. Relational comparison still works, but equality
6623 // comparisons will be tautological.
6624 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006625 }
6626 }
Richard Trieu0f097742014-04-04 04:13:47 +00006627
6628 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6629
6630 if (op == BO_EQ || op == BO_NE) {
6631 IsTrue = op == BO_NE;
6632 } else if (EqualityOnly) {
6633 return;
6634 } else if (RhsConstant) {
6635 if (op == BO_GT || op == BO_GE)
6636 IsTrue = !PositiveConstant;
6637 else // op == BO_LT || op == BO_LE
6638 IsTrue = PositiveConstant;
6639 } else {
6640 if (op == BO_LT || op == BO_LE)
6641 IsTrue = !PositiveConstant;
6642 else // op == BO_GT || op == BO_GE
6643 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006644 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006645 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006646 // Other isKnownToHaveBooleanValue
6647 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6648 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6649 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6650
6651 static const struct LinkedConditions {
6652 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6653 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6654 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6655 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6656 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6657 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6658
6659 } TruthTable = {
6660 // Constant on LHS. | Constant on RHS. |
6661 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6662 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6663 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6664 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6665 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6666 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6667 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6668 };
6669
6670 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6671
6672 enum ConstantValue ConstVal = Zero;
6673 if (Value.isUnsigned() || Value.isNonNegative()) {
6674 if (Value == 0) {
6675 LiteralOrBoolConstant =
6676 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6677 ConstVal = Zero;
6678 } else if (Value == 1) {
6679 LiteralOrBoolConstant =
6680 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6681 ConstVal = One;
6682 } else {
6683 LiteralOrBoolConstant = LiteralConstant;
6684 ConstVal = GT_One;
6685 }
6686 } else {
6687 ConstVal = LT_Zero;
6688 }
6689
6690 CompareBoolWithConstantResult CmpRes;
6691
6692 switch (op) {
6693 case BO_LT:
6694 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6695 break;
6696 case BO_GT:
6697 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6698 break;
6699 case BO_LE:
6700 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6701 break;
6702 case BO_GE:
6703 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6704 break;
6705 case BO_EQ:
6706 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6707 break;
6708 case BO_NE:
6709 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6710 break;
6711 default:
6712 CmpRes = Unkwn;
6713 break;
6714 }
6715
6716 if (CmpRes == AFals) {
6717 IsTrue = false;
6718 } else if (CmpRes == ATrue) {
6719 IsTrue = true;
6720 } else {
6721 return;
6722 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006723 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006724
6725 // If this is a comparison to an enum constant, include that
6726 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006727 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006728 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6729 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6730
6731 SmallString<64> PrettySourceValue;
6732 llvm::raw_svector_ostream OS(PrettySourceValue);
6733 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006734 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006735 else
6736 OS << Value;
6737
Richard Trieu0f097742014-04-04 04:13:47 +00006738 S.DiagRuntimeBehavior(
6739 E->getOperatorLoc(), E,
6740 S.PDiag(diag::warn_out_of_range_compare)
6741 << OS.str() << LiteralOrBoolConstant
6742 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6743 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006744}
6745
John McCallcc7e5bf2010-05-06 08:58:33 +00006746/// Analyze the operands of the given comparison. Implements the
6747/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006748static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006749 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6750 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006751}
John McCall263a48b2010-01-04 23:31:57 +00006752
John McCallca01b222010-01-04 23:21:16 +00006753/// \brief Implements -Wsign-compare.
6754///
Richard Trieu82402a02011-09-15 21:56:47 +00006755/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006756static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006757 // The type the comparison is being performed in.
6758 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006759
6760 // Only analyze comparison operators where both sides have been converted to
6761 // the same type.
6762 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6763 return AnalyzeImpConvsInComparison(S, E);
6764
6765 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006766 if (E->isValueDependent())
6767 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006768
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006769 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6770 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006771
6772 bool IsComparisonConstant = false;
6773
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006774 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006775 // of 'true' or 'false'.
6776 if (T->isIntegralType(S.Context)) {
6777 llvm::APSInt RHSValue;
6778 bool IsRHSIntegralLiteral =
6779 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6780 llvm::APSInt LHSValue;
6781 bool IsLHSIntegralLiteral =
6782 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6783 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6784 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6785 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6786 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6787 else
6788 IsComparisonConstant =
6789 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006790 } else if (!T->hasUnsignedIntegerRepresentation())
6791 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006792
John McCallcc7e5bf2010-05-06 08:58:33 +00006793 // We don't do anything special if this isn't an unsigned integral
6794 // comparison: we're only interested in integral comparisons, and
6795 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006796 //
6797 // We also don't care about value-dependent expressions or expressions
6798 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006799 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006800 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006801
John McCallcc7e5bf2010-05-06 08:58:33 +00006802 // Check to see if one of the (unmodified) operands is of different
6803 // signedness.
6804 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006805 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6806 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006807 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006808 signedOperand = LHS;
6809 unsignedOperand = RHS;
6810 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6811 signedOperand = RHS;
6812 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006813 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006814 CheckTrivialUnsignedComparison(S, E);
6815 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006816 }
6817
John McCallcc7e5bf2010-05-06 08:58:33 +00006818 // Otherwise, calculate the effective range of the signed operand.
6819 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006820
John McCallcc7e5bf2010-05-06 08:58:33 +00006821 // Go ahead and analyze implicit conversions in the operands. Note
6822 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006823 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6824 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006825
John McCallcc7e5bf2010-05-06 08:58:33 +00006826 // If the signed range is non-negative, -Wsign-compare won't fire,
6827 // but we should still check for comparisons which are always true
6828 // or false.
6829 if (signedRange.NonNegative)
6830 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006831
6832 // For (in)equality comparisons, if the unsigned operand is a
6833 // constant which cannot collide with a overflowed signed operand,
6834 // then reinterpreting the signed operand as unsigned will not
6835 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006836 if (E->isEqualityOp()) {
6837 unsigned comparisonWidth = S.Context.getIntWidth(T);
6838 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006839
John McCallcc7e5bf2010-05-06 08:58:33 +00006840 // We should never be unable to prove that the unsigned operand is
6841 // non-negative.
6842 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6843
6844 if (unsignedRange.Width < comparisonWidth)
6845 return;
6846 }
6847
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006848 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6849 S.PDiag(diag::warn_mixed_sign_comparison)
6850 << LHS->getType() << RHS->getType()
6851 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006852}
6853
John McCall1f425642010-11-11 03:21:53 +00006854/// Analyzes an attempt to assign the given value to a bitfield.
6855///
6856/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006857static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6858 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006859 assert(Bitfield->isBitField());
6860 if (Bitfield->isInvalidDecl())
6861 return false;
6862
John McCalldeebbcf2010-11-11 05:33:51 +00006863 // White-list bool bitfields.
6864 if (Bitfield->getType()->isBooleanType())
6865 return false;
6866
Douglas Gregor789adec2011-02-04 13:09:01 +00006867 // Ignore value- or type-dependent expressions.
6868 if (Bitfield->getBitWidth()->isValueDependent() ||
6869 Bitfield->getBitWidth()->isTypeDependent() ||
6870 Init->isValueDependent() ||
6871 Init->isTypeDependent())
6872 return false;
6873
John McCall1f425642010-11-11 03:21:53 +00006874 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6875
Richard Smith5fab0c92011-12-28 19:48:30 +00006876 llvm::APSInt Value;
6877 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006878 return false;
6879
John McCall1f425642010-11-11 03:21:53 +00006880 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006881 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006882
6883 if (OriginalWidth <= FieldWidth)
6884 return false;
6885
Eli Friedmanc267a322012-01-26 23:11:39 +00006886 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006887 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006888 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006889
Eli Friedmanc267a322012-01-26 23:11:39 +00006890 // Check whether the stored value is equal to the original value.
6891 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006892 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006893 return false;
6894
Eli Friedmanc267a322012-01-26 23:11:39 +00006895 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006896 // therefore don't strictly fit into a signed bitfield of width 1.
6897 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006898 return false;
6899
John McCall1f425642010-11-11 03:21:53 +00006900 std::string PrettyValue = Value.toString(10);
6901 std::string PrettyTrunc = TruncatedValue.toString(10);
6902
6903 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6904 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6905 << Init->getSourceRange();
6906
6907 return true;
6908}
6909
John McCalld2a53122010-11-09 23:24:47 +00006910/// Analyze the given simple or compound assignment for warning-worthy
6911/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006912static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006913 // Just recurse on the LHS.
6914 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6915
6916 // We want to recurse on the RHS as normal unless we're assigning to
6917 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006918 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006919 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006920 E->getOperatorLoc())) {
6921 // Recurse, ignoring any implicit conversions on the RHS.
6922 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6923 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006924 }
6925 }
6926
6927 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6928}
6929
John McCall263a48b2010-01-04 23:31:57 +00006930/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006931static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006932 SourceLocation CContext, unsigned diag,
6933 bool pruneControlFlow = false) {
6934 if (pruneControlFlow) {
6935 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6936 S.PDiag(diag)
6937 << SourceType << T << E->getSourceRange()
6938 << SourceRange(CContext));
6939 return;
6940 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006941 S.Diag(E->getExprLoc(), diag)
6942 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6943}
6944
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006945/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006946static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006947 SourceLocation CContext, unsigned diag,
6948 bool pruneControlFlow = false) {
6949 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006950}
6951
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006952/// Diagnose an implicit cast from a literal expression. Does not warn when the
6953/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006954void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6955 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006956 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006957 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006958 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006959 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6960 T->hasUnsignedIntegerRepresentation());
6961 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006962 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006963 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006964 return;
6965
Eli Friedman07185912013-08-29 23:44:43 +00006966 // FIXME: Force the precision of the source value down so we don't print
6967 // digits which are usually useless (we don't really care here if we
6968 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6969 // would automatically print the shortest representation, but it's a bit
6970 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006971 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006972 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6973 precision = (precision * 59 + 195) / 196;
6974 Value.toString(PrettySourceValue, precision);
6975
David Blaikie9b88cc02012-05-15 17:18:27 +00006976 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006977 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6978 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6979 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006980 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006981
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006982 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006983 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6984 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006985}
6986
John McCall18a2c2c2010-11-09 22:22:12 +00006987std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6988 if (!Range.Width) return "0";
6989
6990 llvm::APSInt ValueInRange = Value;
6991 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006992 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006993 return ValueInRange.toString(10);
6994}
6995
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006996static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6997 if (!isa<ImplicitCastExpr>(Ex))
6998 return false;
6999
7000 Expr *InnerE = Ex->IgnoreParenImpCasts();
7001 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7002 const Type *Source =
7003 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7004 if (Target->isDependentType())
7005 return false;
7006
7007 const BuiltinType *FloatCandidateBT =
7008 dyn_cast<BuiltinType>(ToBool ? Source : Target);
7009 const Type *BoolCandidateType = ToBool ? Target : Source;
7010
7011 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7012 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7013}
7014
7015void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7016 SourceLocation CC) {
7017 unsigned NumArgs = TheCall->getNumArgs();
7018 for (unsigned i = 0; i < NumArgs; ++i) {
7019 Expr *CurrA = TheCall->getArg(i);
7020 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7021 continue;
7022
7023 bool IsSwapped = ((i > 0) &&
7024 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7025 IsSwapped |= ((i < (NumArgs - 1)) &&
7026 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7027 if (IsSwapped) {
7028 // Warn on this floating-point to bool conversion.
7029 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7030 CurrA->getType(), CC,
7031 diag::warn_impcast_floating_point_to_bool);
7032 }
7033 }
7034}
7035
Richard Trieu5b993502014-10-15 03:42:06 +00007036static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
7037 SourceLocation CC) {
7038 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7039 E->getExprLoc()))
7040 return;
7041
7042 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7043 const Expr::NullPointerConstantKind NullKind =
7044 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7045 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7046 return;
7047
7048 // Return if target type is a safe conversion.
7049 if (T->isAnyPointerType() || T->isBlockPointerType() ||
7050 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7051 return;
7052
7053 SourceLocation Loc = E->getSourceRange().getBegin();
7054
7055 // __null is usually wrapped in a macro. Go up a macro if that is the case.
7056 if (NullKind == Expr::NPCK_GNUNull) {
7057 if (Loc.isMacroID())
7058 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7059 }
7060
7061 // Only warn if the null and context location are in the same macro expansion.
7062 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7063 return;
7064
7065 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7066 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7067 << FixItHint::CreateReplacement(Loc,
7068 S.getFixItZeroLiteralForType(T, Loc));
7069}
7070
Douglas Gregor5054cb02015-07-07 03:58:22 +00007071static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7072 ObjCArrayLiteral *ArrayLiteral);
7073static void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7074 ObjCDictionaryLiteral *DictionaryLiteral);
7075
7076/// Check a single element within a collection literal against the
7077/// target element type.
7078static void checkObjCCollectionLiteralElement(Sema &S,
7079 QualType TargetElementType,
7080 Expr *Element,
7081 unsigned ElementKind) {
7082 // Skip a bitcast to 'id' or qualified 'id'.
7083 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7084 if (ICE->getCastKind() == CK_BitCast &&
7085 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7086 Element = ICE->getSubExpr();
7087 }
7088
7089 QualType ElementType = Element->getType();
7090 ExprResult ElementResult(Element);
7091 if (ElementType->getAs<ObjCObjectPointerType>() &&
7092 S.CheckSingleAssignmentConstraints(TargetElementType,
7093 ElementResult,
7094 false, false)
7095 != Sema::Compatible) {
7096 S.Diag(Element->getLocStart(),
7097 diag::warn_objc_collection_literal_element)
7098 << ElementType << ElementKind << TargetElementType
7099 << Element->getSourceRange();
7100 }
7101
7102 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7103 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7104 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7105 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7106}
7107
7108/// Check an Objective-C array literal being converted to the given
7109/// target type.
7110static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7111 ObjCArrayLiteral *ArrayLiteral) {
7112 if (!S.NSArrayDecl)
7113 return;
7114
7115 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7116 if (!TargetObjCPtr)
7117 return;
7118
7119 if (TargetObjCPtr->isUnspecialized() ||
7120 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7121 != S.NSArrayDecl->getCanonicalDecl())
7122 return;
7123
7124 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7125 if (TypeArgs.size() != 1)
7126 return;
7127
7128 QualType TargetElementType = TypeArgs[0];
7129 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7130 checkObjCCollectionLiteralElement(S, TargetElementType,
7131 ArrayLiteral->getElement(I),
7132 0);
7133 }
7134}
7135
7136/// Check an Objective-C dictionary literal being converted to the given
7137/// target type.
7138static void checkObjCDictionaryLiteral(
7139 Sema &S, QualType TargetType,
7140 ObjCDictionaryLiteral *DictionaryLiteral) {
7141 if (!S.NSDictionaryDecl)
7142 return;
7143
7144 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7145 if (!TargetObjCPtr)
7146 return;
7147
7148 if (TargetObjCPtr->isUnspecialized() ||
7149 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7150 != S.NSDictionaryDecl->getCanonicalDecl())
7151 return;
7152
7153 auto TypeArgs = TargetObjCPtr->getTypeArgs();
7154 if (TypeArgs.size() != 2)
7155 return;
7156
7157 QualType TargetKeyType = TypeArgs[0];
7158 QualType TargetObjectType = TypeArgs[1];
7159 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7160 auto Element = DictionaryLiteral->getKeyValueElement(I);
7161 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7162 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7163 }
7164}
7165
John McCallcc7e5bf2010-05-06 08:58:33 +00007166void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00007167 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007168 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00007169
John McCallcc7e5bf2010-05-06 08:58:33 +00007170 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7171 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7172 if (Source == Target) return;
7173 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00007174
Chandler Carruthc22845a2011-07-26 05:40:03 +00007175 // If the conversion context location is invalid don't complain. We also
7176 // don't want to emit a warning if the issue occurs from the expansion of
7177 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7178 // delay this check as long as possible. Once we detect we are in that
7179 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007180 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00007181 return;
7182
Richard Trieu021baa32011-09-23 20:10:00 +00007183 // Diagnose implicit casts to bool.
7184 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7185 if (isa<StringLiteral>(E))
7186 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00007187 // and expressions, for instance, assert(0 && "error here"), are
7188 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00007189 return DiagnoseImpCast(S, E, T, CC,
7190 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00007191 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7192 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7193 // This covers the literal expressions that evaluate to Objective-C
7194 // objects.
7195 return DiagnoseImpCast(S, E, T, CC,
7196 diag::warn_impcast_objective_c_literal_to_bool);
7197 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007198 if (Source->isPointerType() || Source->canDecayToPointerType()) {
7199 // Warn on pointer to bool conversion that is always true.
7200 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7201 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00007202 }
Richard Trieu021baa32011-09-23 20:10:00 +00007203 }
John McCall263a48b2010-01-04 23:31:57 +00007204
Douglas Gregor5054cb02015-07-07 03:58:22 +00007205 // Check implicit casts from Objective-C collection literals to specialized
7206 // collection types, e.g., NSArray<NSString *> *.
7207 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7208 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7209 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7210 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7211
John McCall263a48b2010-01-04 23:31:57 +00007212 // Strip vector types.
7213 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007214 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007215 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007216 return;
John McCallacf0ee52010-10-08 02:01:28 +00007217 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007218 }
Chris Lattneree7286f2011-06-14 04:51:15 +00007219
7220 // If the vector cast is cast between two vectors of the same size, it is
7221 // a bitcast, not a conversion.
7222 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7223 return;
John McCall263a48b2010-01-04 23:31:57 +00007224
7225 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7226 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7227 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00007228 if (auto VecTy = dyn_cast<VectorType>(Target))
7229 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00007230
7231 // Strip complex types.
7232 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007233 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007234 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007235 return;
7236
John McCallacf0ee52010-10-08 02:01:28 +00007237 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007238 }
John McCall263a48b2010-01-04 23:31:57 +00007239
7240 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7241 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7242 }
7243
7244 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7245 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7246
7247 // If the source is floating point...
7248 if (SourceBT && SourceBT->isFloatingPoint()) {
7249 // ...and the target is floating point...
7250 if (TargetBT && TargetBT->isFloatingPoint()) {
7251 // ...then warn if we're dropping FP rank.
7252
7253 // Builtin FP kinds are ordered by increasing FP rank.
7254 if (SourceBT->getKind() > TargetBT->getKind()) {
7255 // Don't warn about float constants that are precisely
7256 // representable in the target type.
7257 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00007258 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00007259 // Value might be a float, a float vector, or a float complex.
7260 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00007261 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7262 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00007263 return;
7264 }
7265
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007266 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007267 return;
7268
John McCallacf0ee52010-10-08 02:01:28 +00007269 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
George Burgess IV148e0d32015-10-29 00:28:52 +00007270
7271 }
7272 // ... or possibly if we're increasing rank, too
7273 else if (TargetBT->getKind() > SourceBT->getKind()) {
7274 if (S.SourceMgr.isInSystemMacro(CC))
7275 return;
7276
7277 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
John McCall263a48b2010-01-04 23:31:57 +00007278 }
7279 return;
7280 }
7281
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007282 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00007283 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007284 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007285 return;
7286
Chandler Carruth22c7a792011-02-17 11:05:49 +00007287 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00007288 // We also want to warn on, e.g., "int i = -1.234"
7289 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7290 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7291 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7292
Chandler Carruth016ef402011-04-10 08:36:24 +00007293 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
7294 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00007295 } else {
7296 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7297 }
7298 }
John McCall263a48b2010-01-04 23:31:57 +00007299
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007300 // If the target is bool, warn if expr is a function or method call.
7301 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
7302 isa<CallExpr>(E)) {
7303 // Check last argument of function call to see if it is an
7304 // implicit cast from a type matching the type the result
7305 // is being cast to.
7306 CallExpr *CEx = cast<CallExpr>(E);
7307 unsigned NumArgs = CEx->getNumArgs();
7308 if (NumArgs > 0) {
7309 Expr *LastA = CEx->getArg(NumArgs - 1);
7310 Expr *InnerE = LastA->IgnoreParenImpCasts();
7311 const Type *InnerType =
7312 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7313 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7314 // Warn on this floating-point to bool conversion
7315 DiagnoseImpCast(S, E, T, CC,
7316 diag::warn_impcast_floating_point_to_bool);
7317 }
7318 }
7319 }
John McCall263a48b2010-01-04 23:31:57 +00007320 return;
7321 }
7322
Richard Trieu5b993502014-10-15 03:42:06 +00007323 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00007324
David Blaikie9366d2b2012-06-19 21:19:06 +00007325 if (!Source->isIntegerType() || !Target->isIntegerType())
7326 return;
7327
David Blaikie7555b6a2012-05-15 16:56:36 +00007328 // TODO: remove this early return once the false positives for constant->bool
7329 // in templates, macros, etc, are reduced or removed.
7330 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7331 return;
7332
John McCallcc7e5bf2010-05-06 08:58:33 +00007333 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00007334 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00007335
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007336 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00007337 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007338 // TODO: this should happen for bitfield stores, too.
7339 llvm::APSInt Value(32);
7340 if (E->isIntegerConstantExpr(Value, S.Context)) {
7341 if (S.SourceMgr.isInSystemMacro(CC))
7342 return;
7343
John McCall18a2c2c2010-11-09 22:22:12 +00007344 std::string PrettySourceValue = Value.toString(10);
7345 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007346
Ted Kremenek33ba9952011-10-22 02:37:33 +00007347 S.DiagRuntimeBehavior(E->getExprLoc(), E,
7348 S.PDiag(diag::warn_impcast_integer_precision_constant)
7349 << PrettySourceValue << PrettyTargetValue
7350 << E->getType() << T << E->getSourceRange()
7351 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00007352 return;
7353 }
7354
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007355 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7356 if (S.SourceMgr.isInSystemMacro(CC))
7357 return;
7358
David Blaikie9455da02012-04-12 22:40:54 +00007359 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00007360 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7361 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007362 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007363 }
7364
7365 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7366 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7367 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007368
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007369 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007370 return;
7371
John McCallcc7e5bf2010-05-06 08:58:33 +00007372 unsigned DiagID = diag::warn_impcast_integer_sign;
7373
7374 // Traditionally, gcc has warned about this under -Wsign-compare.
7375 // We also want to warn about it in -Wconversion.
7376 // So if -Wconversion is off, use a completely identical diagnostic
7377 // in the sign-compare group.
7378 // The conditional-checking code will
7379 if (ICContext) {
7380 DiagID = diag::warn_impcast_integer_sign_conditional;
7381 *ICContext = true;
7382 }
7383
John McCallacf0ee52010-10-08 02:01:28 +00007384 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007385 }
7386
Douglas Gregora78f1932011-02-22 02:45:07 +00007387 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007388 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7389 // type, to give us better diagnostics.
7390 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007391 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007392 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7393 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7394 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7395 SourceType = S.Context.getTypeDeclType(Enum);
7396 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7397 }
7398 }
7399
Douglas Gregora78f1932011-02-22 02:45:07 +00007400 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7401 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007402 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7403 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007404 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007405 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007406 return;
7407
Douglas Gregor364f7db2011-03-12 00:14:31 +00007408 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007409 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007410 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007411
John McCall263a48b2010-01-04 23:31:57 +00007412 return;
7413}
7414
David Blaikie18e9ac72012-05-15 21:57:38 +00007415void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7416 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007417
7418void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007419 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007420 E = E->IgnoreParenImpCasts();
7421
7422 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007423 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007424
John McCallacf0ee52010-10-08 02:01:28 +00007425 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007426 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007427 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007428 return;
7429}
7430
David Blaikie18e9ac72012-05-15 21:57:38 +00007431void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7432 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007433 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007434
7435 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007436 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7437 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007438
7439 // If -Wconversion would have warned about either of the candidates
7440 // for a signedness conversion to the context type...
7441 if (!Suspicious) return;
7442
7443 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007444 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007445 return;
7446
John McCallcc7e5bf2010-05-06 08:58:33 +00007447 // ...then check whether it would have warned about either of the
7448 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007449 if (E->getType() == T) return;
7450
7451 Suspicious = false;
7452 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7453 E->getType(), CC, &Suspicious);
7454 if (!Suspicious)
7455 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007456 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007457}
7458
Richard Trieu65724892014-11-15 06:37:39 +00007459/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7460/// Input argument E is a logical expression.
7461static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7462 if (S.getLangOpts().Bool)
7463 return;
7464 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7465}
7466
John McCallcc7e5bf2010-05-06 08:58:33 +00007467/// AnalyzeImplicitConversions - Find and report any interesting
7468/// implicit conversions in the given expression. There are a couple
7469/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007470void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007471 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007472 Expr *E = OrigE->IgnoreParenImpCasts();
7473
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007474 if (E->isTypeDependent() || E->isValueDependent())
7475 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007476
John McCallcc7e5bf2010-05-06 08:58:33 +00007477 // For conditional operators, we analyze the arguments as if they
7478 // were being fed directly into the output.
7479 if (isa<ConditionalOperator>(E)) {
7480 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007481 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007482 return;
7483 }
7484
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007485 // Check implicit argument conversions for function calls.
7486 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7487 CheckImplicitArgumentConversions(S, Call, CC);
7488
John McCallcc7e5bf2010-05-06 08:58:33 +00007489 // Go ahead and check any implicit conversions we might have skipped.
7490 // The non-canonical typecheck is just an optimization;
7491 // CheckImplicitConversion will filter out dead implicit conversions.
7492 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007493 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007494
7495 // Now continue drilling into this expression.
Richard Smithd7bed4d2015-11-22 02:57:17 +00007496
7497 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
7498 // The bound subexpressions in a PseudoObjectExpr are not reachable
7499 // as transitive children.
7500 // FIXME: Use a more uniform representation for this.
7501 for (auto *SE : POE->semantics())
7502 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7503 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007504 }
Richard Smithd7bed4d2015-11-22 02:57:17 +00007505
John McCallcc7e5bf2010-05-06 08:58:33 +00007506 // Skip past explicit casts.
7507 if (isa<ExplicitCastExpr>(E)) {
7508 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007509 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007510 }
7511
John McCalld2a53122010-11-09 23:24:47 +00007512 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7513 // Do a somewhat different check with comparison operators.
7514 if (BO->isComparisonOp())
7515 return AnalyzeComparison(S, BO);
7516
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007517 // And with simple assignments.
7518 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007519 return AnalyzeAssignment(S, BO);
7520 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007521
7522 // These break the otherwise-useful invariant below. Fortunately,
7523 // we don't really need to recurse into them, because any internal
7524 // expressions should have been analyzed already when they were
7525 // built into statements.
7526 if (isa<StmtExpr>(E)) return;
7527
7528 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007529 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007530
7531 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007532 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007533 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007534 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Benjamin Kramer642f1732015-07-02 21:03:14 +00007535 for (Stmt *SubStmt : E->children()) {
7536 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007537 if (!ChildExpr)
7538 continue;
7539
Richard Trieu955231d2014-01-25 01:10:35 +00007540 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007541 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007542 // Ignore checking string literals that are in logical and operators.
7543 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007544 continue;
7545 AnalyzeImplicitConversions(S, ChildExpr, CC);
7546 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007547
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007548 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007549 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7550 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007551 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007552
7553 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7554 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007555 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007556 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007557
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007558 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7559 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007560 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007561}
7562
7563} // end anonymous namespace
7564
Richard Trieu3bb8b562014-02-26 02:36:06 +00007565enum {
7566 AddressOf,
7567 FunctionPointer,
7568 ArrayPointer
7569};
7570
Richard Trieuc1888e02014-06-28 23:25:37 +00007571// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7572// Returns true when emitting a warning about taking the address of a reference.
7573static bool CheckForReference(Sema &SemaRef, const Expr *E,
7574 PartialDiagnostic PD) {
7575 E = E->IgnoreParenImpCasts();
7576
7577 const FunctionDecl *FD = nullptr;
7578
7579 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7580 if (!DRE->getDecl()->getType()->isReferenceType())
7581 return false;
7582 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7583 if (!M->getMemberDecl()->getType()->isReferenceType())
7584 return false;
7585 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007586 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007587 return false;
7588 FD = Call->getDirectCallee();
7589 } else {
7590 return false;
7591 }
7592
7593 SemaRef.Diag(E->getExprLoc(), PD);
7594
7595 // If possible, point to location of function.
7596 if (FD) {
7597 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7598 }
7599
7600 return true;
7601}
7602
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007603// Returns true if the SourceLocation is expanded from any macro body.
7604// Returns false if the SourceLocation is invalid, is from not in a macro
7605// expansion, or is from expanded from a top-level macro argument.
7606static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7607 if (Loc.isInvalid())
7608 return false;
7609
7610 while (Loc.isMacroID()) {
7611 if (SM.isMacroBodyExpansion(Loc))
7612 return true;
7613 Loc = SM.getImmediateMacroCallerLoc(Loc);
7614 }
7615
7616 return false;
7617}
7618
Richard Trieu3bb8b562014-02-26 02:36:06 +00007619/// \brief Diagnose pointers that are always non-null.
7620/// \param E the expression containing the pointer
7621/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7622/// compared to a null pointer
7623/// \param IsEqual True when the comparison is equal to a null pointer
7624/// \param Range Extra SourceRange to highlight in the diagnostic
7625void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7626 Expr::NullPointerConstantKind NullKind,
7627 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007628 if (!E)
7629 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007630
7631 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007632 if (E->getExprLoc().isMacroID()) {
7633 const SourceManager &SM = getSourceManager();
7634 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7635 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007636 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007637 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007638 E = E->IgnoreImpCasts();
7639
7640 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7641
Richard Trieuf7432752014-06-06 21:39:26 +00007642 if (isa<CXXThisExpr>(E)) {
7643 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7644 : diag::warn_this_bool_conversion;
7645 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7646 return;
7647 }
7648
Richard Trieu3bb8b562014-02-26 02:36:06 +00007649 bool IsAddressOf = false;
7650
7651 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7652 if (UO->getOpcode() != UO_AddrOf)
7653 return;
7654 IsAddressOf = true;
7655 E = UO->getSubExpr();
7656 }
7657
Richard Trieuc1888e02014-06-28 23:25:37 +00007658 if (IsAddressOf) {
7659 unsigned DiagID = IsCompare
7660 ? diag::warn_address_of_reference_null_compare
7661 : diag::warn_address_of_reference_bool_conversion;
7662 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7663 << IsEqual;
7664 if (CheckForReference(*this, E, PD)) {
7665 return;
7666 }
7667 }
7668
Richard Trieu3bb8b562014-02-26 02:36:06 +00007669 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007670 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007671 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7672 D = R->getDecl();
7673 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7674 D = M->getMemberDecl();
7675 }
7676
7677 // Weak Decls can be null.
7678 if (!D || D->isWeak())
7679 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007680
7681 // Check for parameter decl with nonnull attribute
7682 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7683 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7684 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7685 unsigned NumArgs = FD->getNumParams();
7686 llvm::SmallBitVector AttrNonNull(NumArgs);
7687 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7688 if (!NonNull->args_size()) {
7689 AttrNonNull.set(0, NumArgs);
7690 break;
7691 }
7692 for (unsigned Val : NonNull->args()) {
7693 if (Val >= NumArgs)
7694 continue;
7695 AttrNonNull.set(Val);
7696 }
7697 }
7698 if (!AttrNonNull.empty())
7699 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007700 if (FD->getParamDecl(i) == PV &&
7701 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007702 std::string Str;
7703 llvm::raw_string_ostream S(Str);
7704 E->printPretty(S, nullptr, getPrintingPolicy());
7705 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7706 : diag::warn_cast_nonnull_to_bool;
7707 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7708 << Range << IsEqual;
7709 return;
7710 }
7711 }
7712 }
7713
Richard Trieu3bb8b562014-02-26 02:36:06 +00007714 QualType T = D->getType();
7715 const bool IsArray = T->isArrayType();
7716 const bool IsFunction = T->isFunctionType();
7717
Richard Trieuc1888e02014-06-28 23:25:37 +00007718 // Address of function is used to silence the function warning.
7719 if (IsAddressOf && IsFunction) {
7720 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007721 }
7722
7723 // Found nothing.
7724 if (!IsAddressOf && !IsFunction && !IsArray)
7725 return;
7726
7727 // Pretty print the expression for the diagnostic.
7728 std::string Str;
7729 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007730 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007731
7732 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7733 : diag::warn_impcast_pointer_to_bool;
7734 unsigned DiagType;
7735 if (IsAddressOf)
7736 DiagType = AddressOf;
7737 else if (IsFunction)
7738 DiagType = FunctionPointer;
7739 else if (IsArray)
7740 DiagType = ArrayPointer;
7741 else
7742 llvm_unreachable("Could not determine diagnostic.");
7743 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7744 << Range << IsEqual;
7745
7746 if (!IsFunction)
7747 return;
7748
7749 // Suggest '&' to silence the function warning.
7750 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7751 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7752
7753 // Check to see if '()' fixit should be emitted.
7754 QualType ReturnType;
7755 UnresolvedSet<4> NonTemplateOverloads;
7756 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7757 if (ReturnType.isNull())
7758 return;
7759
7760 if (IsCompare) {
7761 // There are two cases here. If there is null constant, the only suggest
7762 // for a pointer return type. If the null is 0, then suggest if the return
7763 // type is a pointer or an integer type.
7764 if (!ReturnType->isPointerType()) {
7765 if (NullKind == Expr::NPCK_ZeroExpression ||
7766 NullKind == Expr::NPCK_ZeroLiteral) {
7767 if (!ReturnType->isIntegerType())
7768 return;
7769 } else {
7770 return;
7771 }
7772 }
7773 } else { // !IsCompare
7774 // For function to bool, only suggest if the function pointer has bool
7775 // return type.
7776 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7777 return;
7778 }
7779 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007780 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007781}
7782
7783
John McCallcc7e5bf2010-05-06 08:58:33 +00007784/// Diagnoses "dangerous" implicit conversions within the given
7785/// expression (which is a full expression). Implements -Wconversion
7786/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007787///
7788/// \param CC the "context" location of the implicit conversion, i.e.
7789/// the most location of the syntactic entity requiring the implicit
7790/// conversion
7791void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007792 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007793 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007794 return;
7795
7796 // Don't diagnose for value- or type-dependent expressions.
7797 if (E->isTypeDependent() || E->isValueDependent())
7798 return;
7799
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007800 // Check for array bounds violations in cases where the check isn't triggered
7801 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7802 // ArraySubscriptExpr is on the RHS of a variable initialization.
7803 CheckArrayAccess(E);
7804
John McCallacf0ee52010-10-08 02:01:28 +00007805 // This is not the right CC for (e.g.) a variable initialization.
7806 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007807}
7808
Richard Trieu65724892014-11-15 06:37:39 +00007809/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7810/// Input argument E is a logical expression.
7811void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7812 ::CheckBoolLikeConversion(*this, E, CC);
7813}
7814
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007815/// Diagnose when expression is an integer constant expression and its evaluation
7816/// results in integer overflow
7817void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007818 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7819 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007820}
7821
Richard Smithc406cb72013-01-17 01:17:56 +00007822namespace {
7823/// \brief Visitor for expressions which looks for unsequenced operations on the
7824/// same object.
7825class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007826 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7827
Richard Smithc406cb72013-01-17 01:17:56 +00007828 /// \brief A tree of sequenced regions within an expression. Two regions are
7829 /// unsequenced if one is an ancestor or a descendent of the other. When we
7830 /// finish processing an expression with sequencing, such as a comma
7831 /// expression, we fold its tree nodes into its parent, since they are
7832 /// unsequenced with respect to nodes we will visit later.
7833 class SequenceTree {
7834 struct Value {
7835 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7836 unsigned Parent : 31;
7837 bool Merged : 1;
7838 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007839 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007840
7841 public:
7842 /// \brief A region within an expression which may be sequenced with respect
7843 /// to some other region.
7844 class Seq {
7845 explicit Seq(unsigned N) : Index(N) {}
7846 unsigned Index;
7847 friend class SequenceTree;
7848 public:
7849 Seq() : Index(0) {}
7850 };
7851
7852 SequenceTree() { Values.push_back(Value(0)); }
7853 Seq root() const { return Seq(0); }
7854
7855 /// \brief Create a new sequence of operations, which is an unsequenced
7856 /// subset of \p Parent. This sequence of operations is sequenced with
7857 /// respect to other children of \p Parent.
7858 Seq allocate(Seq Parent) {
7859 Values.push_back(Value(Parent.Index));
7860 return Seq(Values.size() - 1);
7861 }
7862
7863 /// \brief Merge a sequence of operations into its parent.
7864 void merge(Seq S) {
7865 Values[S.Index].Merged = true;
7866 }
7867
7868 /// \brief Determine whether two operations are unsequenced. This operation
7869 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7870 /// should have been merged into its parent as appropriate.
7871 bool isUnsequenced(Seq Cur, Seq Old) {
7872 unsigned C = representative(Cur.Index);
7873 unsigned Target = representative(Old.Index);
7874 while (C >= Target) {
7875 if (C == Target)
7876 return true;
7877 C = Values[C].Parent;
7878 }
7879 return false;
7880 }
7881
7882 private:
7883 /// \brief Pick a representative for a sequence.
7884 unsigned representative(unsigned K) {
7885 if (Values[K].Merged)
7886 // Perform path compression as we go.
7887 return Values[K].Parent = representative(Values[K].Parent);
7888 return K;
7889 }
7890 };
7891
7892 /// An object for which we can track unsequenced uses.
7893 typedef NamedDecl *Object;
7894
7895 /// Different flavors of object usage which we track. We only track the
7896 /// least-sequenced usage of each kind.
7897 enum UsageKind {
7898 /// A read of an object. Multiple unsequenced reads are OK.
7899 UK_Use,
7900 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007901 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007902 UK_ModAsValue,
7903 /// A modification of an object which is not sequenced before the value
7904 /// computation of the expression, such as n++.
7905 UK_ModAsSideEffect,
7906
7907 UK_Count = UK_ModAsSideEffect + 1
7908 };
7909
7910 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007911 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007912 Expr *Use;
7913 SequenceTree::Seq Seq;
7914 };
7915
7916 struct UsageInfo {
7917 UsageInfo() : Diagnosed(false) {}
7918 Usage Uses[UK_Count];
7919 /// Have we issued a diagnostic for this variable already?
7920 bool Diagnosed;
7921 };
7922 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7923
7924 Sema &SemaRef;
7925 /// Sequenced regions within the expression.
7926 SequenceTree Tree;
7927 /// Declaration modifications and references which we have seen.
7928 UsageInfoMap UsageMap;
7929 /// The region we are currently within.
7930 SequenceTree::Seq Region;
7931 /// Filled in with declarations which were modified as a side-effect
7932 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007933 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007934 /// Expressions to check later. We defer checking these to reduce
7935 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007936 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007937
7938 /// RAII object wrapping the visitation of a sequenced subexpression of an
7939 /// expression. At the end of this process, the side-effects of the evaluation
7940 /// become sequenced with respect to the value computation of the result, so
7941 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7942 /// UK_ModAsValue.
7943 struct SequencedSubexpression {
7944 SequencedSubexpression(SequenceChecker &Self)
7945 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7946 Self.ModAsSideEffect = &ModAsSideEffect;
7947 }
7948 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007949 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7950 MI != ME; ++MI) {
7951 UsageInfo &U = Self.UsageMap[MI->first];
7952 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7953 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7954 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007955 }
7956 Self.ModAsSideEffect = OldModAsSideEffect;
7957 }
7958
7959 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007960 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7961 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007962 };
7963
Richard Smith40238f02013-06-20 22:21:56 +00007964 /// RAII object wrapping the visitation of a subexpression which we might
7965 /// choose to evaluate as a constant. If any subexpression is evaluated and
7966 /// found to be non-constant, this allows us to suppress the evaluation of
7967 /// the outer expression.
7968 class EvaluationTracker {
7969 public:
7970 EvaluationTracker(SequenceChecker &Self)
7971 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7972 Self.EvalTracker = this;
7973 }
7974 ~EvaluationTracker() {
7975 Self.EvalTracker = Prev;
7976 if (Prev)
7977 Prev->EvalOK &= EvalOK;
7978 }
7979
7980 bool evaluate(const Expr *E, bool &Result) {
7981 if (!EvalOK || E->isValueDependent())
7982 return false;
7983 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7984 return EvalOK;
7985 }
7986
7987 private:
7988 SequenceChecker &Self;
7989 EvaluationTracker *Prev;
7990 bool EvalOK;
7991 } *EvalTracker;
7992
Richard Smithc406cb72013-01-17 01:17:56 +00007993 /// \brief Find the object which is produced by the specified expression,
7994 /// if any.
7995 Object getObject(Expr *E, bool Mod) const {
7996 E = E->IgnoreParenCasts();
7997 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7998 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7999 return getObject(UO->getSubExpr(), Mod);
8000 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8001 if (BO->getOpcode() == BO_Comma)
8002 return getObject(BO->getRHS(), Mod);
8003 if (Mod && BO->isAssignmentOp())
8004 return getObject(BO->getLHS(), Mod);
8005 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8006 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8007 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8008 return ME->getMemberDecl();
8009 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8010 // FIXME: If this is a reference, map through to its value.
8011 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00008012 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00008013 }
8014
8015 /// \brief Note that an object was modified or used by an expression.
8016 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8017 Usage &U = UI.Uses[UK];
8018 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8019 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8020 ModAsSideEffect->push_back(std::make_pair(O, U));
8021 U.Use = Ref;
8022 U.Seq = Region;
8023 }
8024 }
8025 /// \brief Check whether a modification or use conflicts with a prior usage.
8026 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8027 bool IsModMod) {
8028 if (UI.Diagnosed)
8029 return;
8030
8031 const Usage &U = UI.Uses[OtherKind];
8032 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8033 return;
8034
8035 Expr *Mod = U.Use;
8036 Expr *ModOrUse = Ref;
8037 if (OtherKind == UK_Use)
8038 std::swap(Mod, ModOrUse);
8039
8040 SemaRef.Diag(Mod->getExprLoc(),
8041 IsModMod ? diag::warn_unsequenced_mod_mod
8042 : diag::warn_unsequenced_mod_use)
8043 << O << SourceRange(ModOrUse->getExprLoc());
8044 UI.Diagnosed = true;
8045 }
8046
8047 void notePreUse(Object O, Expr *Use) {
8048 UsageInfo &U = UsageMap[O];
8049 // Uses conflict with other modifications.
8050 checkUsage(O, U, Use, UK_ModAsValue, false);
8051 }
8052 void notePostUse(Object O, Expr *Use) {
8053 UsageInfo &U = UsageMap[O];
8054 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8055 addUsage(U, O, Use, UK_Use);
8056 }
8057
8058 void notePreMod(Object O, Expr *Mod) {
8059 UsageInfo &U = UsageMap[O];
8060 // Modifications conflict with other modifications and with uses.
8061 checkUsage(O, U, Mod, UK_ModAsValue, true);
8062 checkUsage(O, U, Mod, UK_Use, false);
8063 }
8064 void notePostMod(Object O, Expr *Use, UsageKind UK) {
8065 UsageInfo &U = UsageMap[O];
8066 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8067 addUsage(U, O, Use, UK);
8068 }
8069
8070public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008071 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00008072 : Base(S.Context), SemaRef(S), Region(Tree.root()),
8073 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008074 Visit(E);
8075 }
8076
8077 void VisitStmt(Stmt *S) {
8078 // Skip all statements which aren't expressions for now.
8079 }
8080
8081 void VisitExpr(Expr *E) {
8082 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00008083 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008084 }
8085
8086 void VisitCastExpr(CastExpr *E) {
8087 Object O = Object();
8088 if (E->getCastKind() == CK_LValueToRValue)
8089 O = getObject(E->getSubExpr(), false);
8090
8091 if (O)
8092 notePreUse(O, E);
8093 VisitExpr(E);
8094 if (O)
8095 notePostUse(O, E);
8096 }
8097
8098 void VisitBinComma(BinaryOperator *BO) {
8099 // C++11 [expr.comma]p1:
8100 // Every value computation and side effect associated with the left
8101 // expression is sequenced before every value computation and side
8102 // effect associated with the right expression.
8103 SequenceTree::Seq LHS = Tree.allocate(Region);
8104 SequenceTree::Seq RHS = Tree.allocate(Region);
8105 SequenceTree::Seq OldRegion = Region;
8106
8107 {
8108 SequencedSubexpression SeqLHS(*this);
8109 Region = LHS;
8110 Visit(BO->getLHS());
8111 }
8112
8113 Region = RHS;
8114 Visit(BO->getRHS());
8115
8116 Region = OldRegion;
8117
8118 // Forget that LHS and RHS are sequenced. They are both unsequenced
8119 // with respect to other stuff.
8120 Tree.merge(LHS);
8121 Tree.merge(RHS);
8122 }
8123
8124 void VisitBinAssign(BinaryOperator *BO) {
8125 // The modification is sequenced after the value computation of the LHS
8126 // and RHS, so check it before inspecting the operands and update the
8127 // map afterwards.
8128 Object O = getObject(BO->getLHS(), true);
8129 if (!O)
8130 return VisitExpr(BO);
8131
8132 notePreMod(O, BO);
8133
8134 // C++11 [expr.ass]p7:
8135 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8136 // only once.
8137 //
8138 // Therefore, for a compound assignment operator, O is considered used
8139 // everywhere except within the evaluation of E1 itself.
8140 if (isa<CompoundAssignOperator>(BO))
8141 notePreUse(O, BO);
8142
8143 Visit(BO->getLHS());
8144
8145 if (isa<CompoundAssignOperator>(BO))
8146 notePostUse(O, BO);
8147
8148 Visit(BO->getRHS());
8149
Richard Smith83e37bee2013-06-26 23:16:51 +00008150 // C++11 [expr.ass]p1:
8151 // the assignment is sequenced [...] before the value computation of the
8152 // assignment expression.
8153 // C11 6.5.16/3 has no such rule.
8154 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8155 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008156 }
8157 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8158 VisitBinAssign(CAO);
8159 }
8160
8161 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8162 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8163 void VisitUnaryPreIncDec(UnaryOperator *UO) {
8164 Object O = getObject(UO->getSubExpr(), true);
8165 if (!O)
8166 return VisitExpr(UO);
8167
8168 notePreMod(O, UO);
8169 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00008170 // C++11 [expr.pre.incr]p1:
8171 // the expression ++x is equivalent to x+=1
8172 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8173 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00008174 }
8175
8176 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8177 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8178 void VisitUnaryPostIncDec(UnaryOperator *UO) {
8179 Object O = getObject(UO->getSubExpr(), true);
8180 if (!O)
8181 return VisitExpr(UO);
8182
8183 notePreMod(O, UO);
8184 Visit(UO->getSubExpr());
8185 notePostMod(O, UO, UK_ModAsSideEffect);
8186 }
8187
8188 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8189 void VisitBinLOr(BinaryOperator *BO) {
8190 // The side-effects of the LHS of an '&&' are sequenced before the
8191 // value computation of the RHS, and hence before the value computation
8192 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8193 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00008194 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008195 {
8196 SequencedSubexpression Sequenced(*this);
8197 Visit(BO->getLHS());
8198 }
8199
8200 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008201 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008202 if (!Result)
8203 Visit(BO->getRHS());
8204 } else {
8205 // Check for unsequenced operations in the RHS, treating it as an
8206 // entirely separate evaluation.
8207 //
8208 // FIXME: If there are operations in the RHS which are unsequenced
8209 // with respect to operations outside the RHS, and those operations
8210 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00008211 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008212 }
Richard Smithc406cb72013-01-17 01:17:56 +00008213 }
8214 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00008215 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00008216 {
8217 SequencedSubexpression Sequenced(*this);
8218 Visit(BO->getLHS());
8219 }
8220
8221 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008222 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00008223 if (Result)
8224 Visit(BO->getRHS());
8225 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00008226 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00008227 }
Richard Smithc406cb72013-01-17 01:17:56 +00008228 }
8229
8230 // Only visit the condition, unless we can be sure which subexpression will
8231 // be chosen.
8232 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00008233 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00008234 {
8235 SequencedSubexpression Sequenced(*this);
8236 Visit(CO->getCond());
8237 }
Richard Smithc406cb72013-01-17 01:17:56 +00008238
8239 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00008240 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00008241 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008242 else {
Richard Smithd33f5202013-01-17 23:18:09 +00008243 WorkList.push_back(CO->getTrueExpr());
8244 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00008245 }
Richard Smithc406cb72013-01-17 01:17:56 +00008246 }
8247
Richard Smithe3dbfe02013-06-30 10:40:20 +00008248 void VisitCallExpr(CallExpr *CE) {
8249 // C++11 [intro.execution]p15:
8250 // When calling a function [...], every value computation and side effect
8251 // associated with any argument expression, or with the postfix expression
8252 // designating the called function, is sequenced before execution of every
8253 // expression or statement in the body of the function [and thus before
8254 // the value computation of its result].
8255 SequencedSubexpression Sequenced(*this);
8256 Base::VisitCallExpr(CE);
8257
8258 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8259 }
8260
Richard Smithc406cb72013-01-17 01:17:56 +00008261 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00008262 // This is a call, so all subexpressions are sequenced before the result.
8263 SequencedSubexpression Sequenced(*this);
8264
Richard Smithc406cb72013-01-17 01:17:56 +00008265 if (!CCE->isListInitialization())
8266 return VisitExpr(CCE);
8267
8268 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008269 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008270 SequenceTree::Seq Parent = Region;
8271 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8272 E = CCE->arg_end();
8273 I != E; ++I) {
8274 Region = Tree.allocate(Parent);
8275 Elts.push_back(Region);
8276 Visit(*I);
8277 }
8278
8279 // Forget that the initializers are sequenced.
8280 Region = Parent;
8281 for (unsigned I = 0; I < Elts.size(); ++I)
8282 Tree.merge(Elts[I]);
8283 }
8284
8285 void VisitInitListExpr(InitListExpr *ILE) {
8286 if (!SemaRef.getLangOpts().CPlusPlus11)
8287 return VisitExpr(ILE);
8288
8289 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008290 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00008291 SequenceTree::Seq Parent = Region;
8292 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8293 Expr *E = ILE->getInit(I);
8294 if (!E) continue;
8295 Region = Tree.allocate(Parent);
8296 Elts.push_back(Region);
8297 Visit(E);
8298 }
8299
8300 // Forget that the initializers are sequenced.
8301 Region = Parent;
8302 for (unsigned I = 0; I < Elts.size(); ++I)
8303 Tree.merge(Elts[I]);
8304 }
8305};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008306}
Richard Smithc406cb72013-01-17 01:17:56 +00008307
8308void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00008309 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00008310 WorkList.push_back(E);
8311 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00008312 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00008313 SequenceChecker(*this, Item, WorkList);
8314 }
Richard Smithc406cb72013-01-17 01:17:56 +00008315}
8316
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008317void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8318 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00008319 CheckImplicitConversions(E, CheckLoc);
8320 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008321 if (!IsConstexpr && !E->isValueDependent())
8322 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00008323}
8324
John McCall1f425642010-11-11 03:21:53 +00008325void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8326 FieldDecl *BitField,
8327 Expr *Init) {
8328 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8329}
8330
David Majnemer61a5bbf2015-04-07 22:08:51 +00008331static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8332 SourceLocation Loc) {
8333 if (!PType->isVariablyModifiedType())
8334 return;
8335 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8336 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8337 return;
8338 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00008339 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8340 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8341 return;
8342 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00008343 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8344 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8345 return;
8346 }
8347
8348 const ArrayType *AT = S.Context.getAsArrayType(PType);
8349 if (!AT)
8350 return;
8351
8352 if (AT->getSizeModifier() != ArrayType::Star) {
8353 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8354 return;
8355 }
8356
8357 S.Diag(Loc, diag::err_array_star_in_function_definition);
8358}
8359
Mike Stump0c2ec772010-01-21 03:59:47 +00008360/// CheckParmsForFunctionDef - Check that the parameters of the given
8361/// function are appropriate for the definition of a function. This
8362/// takes care of any checks that cannot be performed on the
8363/// declaration itself, e.g., that the types of each of the function
8364/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008365bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8366 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008367 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008368 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008369 for (; P != PEnd; ++P) {
8370 ParmVarDecl *Param = *P;
8371
Mike Stump0c2ec772010-01-21 03:59:47 +00008372 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8373 // function declarator that is part of a function definition of
8374 // that function shall not have incomplete type.
8375 //
8376 // This is also C++ [dcl.fct]p6.
8377 if (!Param->isInvalidDecl() &&
8378 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008379 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008380 Param->setInvalidDecl();
8381 HasInvalidParm = true;
8382 }
8383
8384 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8385 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008386 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008387 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008388 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008389 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008390 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008391
8392 // C99 6.7.5.3p12:
8393 // If the function declarator is not part of a definition of that
8394 // function, parameters may have incomplete type and may use the [*]
8395 // notation in their sequences of declarator specifiers to specify
8396 // variable length array types.
8397 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008398 // FIXME: This diagnostic should point the '[*]' if source-location
8399 // information is added for it.
8400 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008401
8402 // MSVC destroys objects passed by value in the callee. Therefore a
8403 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008404 // object's destructor. However, we don't perform any direct access check
8405 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008406 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8407 .getCXXABI()
8408 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008409 if (!Param->isInvalidDecl()) {
8410 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8411 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8412 if (!ClassDecl->isInvalidDecl() &&
8413 !ClassDecl->hasIrrelevantDestructor() &&
8414 !ClassDecl->isDependentContext()) {
8415 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8416 MarkFunctionReferenced(Param->getLocation(), Destructor);
8417 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8418 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008419 }
8420 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008421 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008422 }
8423
8424 return HasInvalidParm;
8425}
John McCall2b5c1b22010-08-12 21:44:57 +00008426
8427/// CheckCastAlign - Implements -Wcast-align, which warns when a
8428/// pointer cast increases the alignment requirements.
8429void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8430 // This is actually a lot of work to potentially be doing on every
8431 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008432 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008433 return;
8434
8435 // Ignore dependent types.
8436 if (T->isDependentType() || Op->getType()->isDependentType())
8437 return;
8438
8439 // Require that the destination be a pointer type.
8440 const PointerType *DestPtr = T->getAs<PointerType>();
8441 if (!DestPtr) return;
8442
8443 // If the destination has alignment 1, we're done.
8444 QualType DestPointee = DestPtr->getPointeeType();
8445 if (DestPointee->isIncompleteType()) return;
8446 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8447 if (DestAlign.isOne()) return;
8448
8449 // Require that the source be a pointer type.
8450 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8451 if (!SrcPtr) return;
8452 QualType SrcPointee = SrcPtr->getPointeeType();
8453
8454 // Whitelist casts from cv void*. We already implicitly
8455 // whitelisted casts to cv void*, since they have alignment 1.
8456 // Also whitelist casts involving incomplete types, which implicitly
8457 // includes 'void'.
8458 if (SrcPointee->isIncompleteType()) return;
8459
8460 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8461 if (SrcAlign >= DestAlign) return;
8462
8463 Diag(TRange.getBegin(), diag::warn_cast_align)
8464 << Op->getType() << T
8465 << static_cast<unsigned>(SrcAlign.getQuantity())
8466 << static_cast<unsigned>(DestAlign.getQuantity())
8467 << TRange << Op->getSourceRange();
8468}
8469
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008470static const Type* getElementType(const Expr *BaseExpr) {
8471 const Type* EltType = BaseExpr->getType().getTypePtr();
8472 if (EltType->isAnyPointerType())
8473 return EltType->getPointeeType().getTypePtr();
8474 else if (EltType->isArrayType())
8475 return EltType->getBaseElementTypeUnsafe();
8476 return EltType;
8477}
8478
Chandler Carruth28389f02011-08-05 09:10:50 +00008479/// \brief Check whether this array fits the idiom of a size-one tail padded
8480/// array member of a struct.
8481///
8482/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8483/// commonly used to emulate flexible arrays in C89 code.
8484static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8485 const NamedDecl *ND) {
8486 if (Size != 1 || !ND) return false;
8487
8488 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8489 if (!FD) return false;
8490
8491 // Don't consider sizes resulting from macro expansions or template argument
8492 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008493
8494 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008495 while (TInfo) {
8496 TypeLoc TL = TInfo->getTypeLoc();
8497 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008498 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8499 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008500 TInfo = TDL->getTypeSourceInfo();
8501 continue;
8502 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008503 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8504 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008505 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8506 return false;
8507 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008508 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008509 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008510
8511 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008512 if (!RD) return false;
8513 if (RD->isUnion()) return false;
8514 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8515 if (!CRD->isStandardLayout()) return false;
8516 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008517
Benjamin Kramer8c543672011-08-06 03:04:42 +00008518 // See if this is the last field decl in the record.
8519 const Decl *D = FD;
8520 while ((D = D->getNextDeclInContext()))
8521 if (isa<FieldDecl>(D))
8522 return false;
8523 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008524}
8525
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008526void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008527 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008528 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008529 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008530 if (IndexExpr->isValueDependent())
8531 return;
8532
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008533 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008534 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008535 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008536 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008537 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008538 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008539
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008540 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008541 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008542 return;
Richard Smith13f67182011-12-16 19:31:14 +00008543 if (IndexNegated)
8544 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008545
Craig Topperc3ec1492014-05-26 06:22:03 +00008546 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008547 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8548 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008549 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008550 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008551
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008552 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008553 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008554 if (!size.isStrictlyPositive())
8555 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008556
8557 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008558 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008559 // Make sure we're comparing apples to apples when comparing index to size
8560 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8561 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008562 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008563 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008564 if (ptrarith_typesize != array_typesize) {
8565 // There's a cast to a different size type involved
8566 uint64_t ratio = array_typesize / ptrarith_typesize;
8567 // TODO: Be smarter about handling cases where array_typesize is not a
8568 // multiple of ptrarith_typesize
8569 if (ptrarith_typesize * ratio == array_typesize)
8570 size *= llvm::APInt(size.getBitWidth(), ratio);
8571 }
8572 }
8573
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008574 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008575 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008576 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008577 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008578
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008579 // For array subscripting the index must be less than size, but for pointer
8580 // arithmetic also allow the index (offset) to be equal to size since
8581 // computing the next address after the end of the array is legal and
8582 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008583 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008584 return;
8585
8586 // Also don't warn for arrays of size 1 which are members of some
8587 // structure. These are often used to approximate flexible arrays in C89
8588 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008589 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008590 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008591
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008592 // Suppress the warning if the subscript expression (as identified by the
8593 // ']' location) and the index expression are both from macro expansions
8594 // within a system header.
8595 if (ASE) {
8596 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8597 ASE->getRBracketLoc());
8598 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8599 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8600 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008601 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008602 return;
8603 }
8604 }
8605
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008606 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008607 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008608 DiagID = diag::warn_array_index_exceeds_bounds;
8609
8610 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8611 PDiag(DiagID) << index.toString(10, true)
8612 << size.toString(10, true)
8613 << (unsigned)size.getLimitedValue(~0U)
8614 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008615 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008616 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008617 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008618 DiagID = diag::warn_ptr_arith_precedes_bounds;
8619 if (index.isNegative()) index = -index;
8620 }
8621
8622 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8623 PDiag(DiagID) << index.toString(10, true)
8624 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008625 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008626
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008627 if (!ND) {
8628 // Try harder to find a NamedDecl to point at in the note.
8629 while (const ArraySubscriptExpr *ASE =
8630 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8631 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8632 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8633 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8634 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8635 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8636 }
8637
Chandler Carruth1af88f12011-02-17 21:10:52 +00008638 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008639 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8640 PDiag(diag::note_array_index_out_of_bounds)
8641 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008642}
8643
Ted Kremenekdf26df72011-03-01 18:41:00 +00008644void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008645 int AllowOnePastEnd = 0;
8646 while (expr) {
8647 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008648 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008649 case Stmt::ArraySubscriptExprClass: {
8650 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008651 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008652 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008653 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008654 }
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008655 case Stmt::OMPArraySectionExprClass: {
8656 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
8657 if (ASE->getLowerBound())
8658 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
8659 /*ASE=*/nullptr, AllowOnePastEnd > 0);
8660 return;
8661 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008662 case Stmt::UnaryOperatorClass: {
8663 // Only unwrap the * and & unary operators
8664 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8665 expr = UO->getSubExpr();
8666 switch (UO->getOpcode()) {
8667 case UO_AddrOf:
8668 AllowOnePastEnd++;
8669 break;
8670 case UO_Deref:
8671 AllowOnePastEnd--;
8672 break;
8673 default:
8674 return;
8675 }
8676 break;
8677 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008678 case Stmt::ConditionalOperatorClass: {
8679 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8680 if (const Expr *lhs = cond->getLHS())
8681 CheckArrayAccess(lhs);
8682 if (const Expr *rhs = cond->getRHS())
8683 CheckArrayAccess(rhs);
8684 return;
8685 }
8686 default:
8687 return;
8688 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008689 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008690}
John McCall31168b02011-06-15 23:02:42 +00008691
8692//===--- CHECK: Objective-C retain cycles ----------------------------------//
8693
8694namespace {
8695 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008696 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008697 VarDecl *Variable;
8698 SourceRange Range;
8699 SourceLocation Loc;
8700 bool Indirect;
8701
8702 void setLocsFrom(Expr *e) {
8703 Loc = e->getExprLoc();
8704 Range = e->getSourceRange();
8705 }
8706 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008707}
John McCall31168b02011-06-15 23:02:42 +00008708
8709/// Consider whether capturing the given variable can possibly lead to
8710/// a retain cycle.
8711static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008712 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008713 // lifetime. In MRR, it's captured strongly if the variable is
8714 // __block and has an appropriate type.
8715 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8716 return false;
8717
8718 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008719 if (ref)
8720 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008721 return true;
8722}
8723
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008724static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008725 while (true) {
8726 e = e->IgnoreParens();
8727 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8728 switch (cast->getCastKind()) {
8729 case CK_BitCast:
8730 case CK_LValueBitCast:
8731 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008732 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008733 e = cast->getSubExpr();
8734 continue;
8735
John McCall31168b02011-06-15 23:02:42 +00008736 default:
8737 return false;
8738 }
8739 }
8740
8741 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8742 ObjCIvarDecl *ivar = ref->getDecl();
8743 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8744 return false;
8745
8746 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008747 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008748 return false;
8749
8750 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8751 owner.Indirect = true;
8752 return true;
8753 }
8754
8755 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8756 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8757 if (!var) return false;
8758 return considerVariable(var, ref, owner);
8759 }
8760
John McCall31168b02011-06-15 23:02:42 +00008761 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8762 if (member->isArrow()) return false;
8763
8764 // Don't count this as an indirect ownership.
8765 e = member->getBase();
8766 continue;
8767 }
8768
John McCallfe96e0b2011-11-06 09:01:30 +00008769 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8770 // Only pay attention to pseudo-objects on property references.
8771 ObjCPropertyRefExpr *pre
8772 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8773 ->IgnoreParens());
8774 if (!pre) return false;
8775 if (pre->isImplicitProperty()) return false;
8776 ObjCPropertyDecl *property = pre->getExplicitProperty();
8777 if (!property->isRetaining() &&
8778 !(property->getPropertyIvarDecl() &&
8779 property->getPropertyIvarDecl()->getType()
8780 .getObjCLifetime() == Qualifiers::OCL_Strong))
8781 return false;
8782
8783 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008784 if (pre->isSuperReceiver()) {
8785 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8786 if (!owner.Variable)
8787 return false;
8788 owner.Loc = pre->getLocation();
8789 owner.Range = pre->getSourceRange();
8790 return true;
8791 }
John McCallfe96e0b2011-11-06 09:01:30 +00008792 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8793 ->getSourceExpr());
8794 continue;
8795 }
8796
John McCall31168b02011-06-15 23:02:42 +00008797 // Array ivars?
8798
8799 return false;
8800 }
8801}
8802
8803namespace {
8804 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8805 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8806 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008807 Context(Context), Variable(variable), Capturer(nullptr),
8808 VarWillBeReased(false) {}
8809 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008810 VarDecl *Variable;
8811 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008812 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008813
8814 void VisitDeclRefExpr(DeclRefExpr *ref) {
8815 if (ref->getDecl() == Variable && !Capturer)
8816 Capturer = ref;
8817 }
8818
John McCall31168b02011-06-15 23:02:42 +00008819 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8820 if (Capturer) return;
8821 Visit(ref->getBase());
8822 if (Capturer && ref->isFreeIvar())
8823 Capturer = ref;
8824 }
8825
8826 void VisitBlockExpr(BlockExpr *block) {
8827 // Look inside nested blocks
8828 if (block->getBlockDecl()->capturesVariable(Variable))
8829 Visit(block->getBlockDecl()->getBody());
8830 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008831
8832 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8833 if (Capturer) return;
8834 if (OVE->getSourceExpr())
8835 Visit(OVE->getSourceExpr());
8836 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008837 void VisitBinaryOperator(BinaryOperator *BinOp) {
8838 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8839 return;
8840 Expr *LHS = BinOp->getLHS();
8841 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8842 if (DRE->getDecl() != Variable)
8843 return;
8844 if (Expr *RHS = BinOp->getRHS()) {
8845 RHS = RHS->IgnoreParenCasts();
8846 llvm::APSInt Value;
8847 VarWillBeReased =
8848 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8849 }
8850 }
8851 }
John McCall31168b02011-06-15 23:02:42 +00008852 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008853}
John McCall31168b02011-06-15 23:02:42 +00008854
8855/// Check whether the given argument is a block which captures a
8856/// variable.
8857static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8858 assert(owner.Variable && owner.Loc.isValid());
8859
8860 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008861
8862 // Look through [^{...} copy] and Block_copy(^{...}).
8863 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8864 Selector Cmd = ME->getSelector();
8865 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8866 e = ME->getInstanceReceiver();
8867 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008868 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008869 e = e->IgnoreParenCasts();
8870 }
8871 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8872 if (CE->getNumArgs() == 1) {
8873 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008874 if (Fn) {
8875 const IdentifierInfo *FnI = Fn->getIdentifier();
8876 if (FnI && FnI->isStr("_Block_copy")) {
8877 e = CE->getArg(0)->IgnoreParenCasts();
8878 }
8879 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008880 }
8881 }
8882
John McCall31168b02011-06-15 23:02:42 +00008883 BlockExpr *block = dyn_cast<BlockExpr>(e);
8884 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008885 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008886
8887 FindCaptureVisitor visitor(S.Context, owner.Variable);
8888 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008889 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008890}
8891
8892static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8893 RetainCycleOwner &owner) {
8894 assert(capturer);
8895 assert(owner.Variable && owner.Loc.isValid());
8896
8897 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8898 << owner.Variable << capturer->getSourceRange();
8899 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8900 << owner.Indirect << owner.Range;
8901}
8902
8903/// Check for a keyword selector that starts with the word 'add' or
8904/// 'set'.
8905static bool isSetterLikeSelector(Selector sel) {
8906 if (sel.isUnarySelector()) return false;
8907
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008908 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008909 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008910 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008911 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008912 else if (str.startswith("add")) {
8913 // Specially whitelist 'addOperationWithBlock:'.
8914 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8915 return false;
8916 str = str.substr(3);
8917 }
John McCall31168b02011-06-15 23:02:42 +00008918 else
8919 return false;
8920
8921 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008922 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008923}
8924
Benjamin Kramer3a743452015-03-09 15:03:32 +00008925static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8926 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008927 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
8928 Message->getReceiverInterface(),
8929 NSAPI::ClassId_NSMutableArray);
8930 if (!IsMutableArray) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008931 return None;
8932 }
8933
8934 Selector Sel = Message->getSelector();
8935
8936 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8937 S.NSAPIObj->getNSArrayMethodKind(Sel);
8938 if (!MKOpt) {
8939 return None;
8940 }
8941
8942 NSAPI::NSArrayMethodKind MK = *MKOpt;
8943
8944 switch (MK) {
8945 case NSAPI::NSMutableArr_addObject:
8946 case NSAPI::NSMutableArr_insertObjectAtIndex:
8947 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8948 return 0;
8949 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8950 return 1;
8951
8952 default:
8953 return None;
8954 }
8955
8956 return None;
8957}
8958
8959static
8960Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8961 ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008962 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
8963 Message->getReceiverInterface(),
8964 NSAPI::ClassId_NSMutableDictionary);
8965 if (!IsMutableDictionary) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008966 return None;
8967 }
8968
8969 Selector Sel = Message->getSelector();
8970
8971 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8972 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8973 if (!MKOpt) {
8974 return None;
8975 }
8976
8977 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8978
8979 switch (MK) {
8980 case NSAPI::NSMutableDict_setObjectForKey:
8981 case NSAPI::NSMutableDict_setValueForKey:
8982 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8983 return 0;
8984
8985 default:
8986 return None;
8987 }
8988
8989 return None;
8990}
8991
8992static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
Alex Denisov5dfac812015-08-06 04:51:14 +00008993 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
8994 Message->getReceiverInterface(),
8995 NSAPI::ClassId_NSMutableSet);
Alex Denisove1d882c2015-03-04 17:55:52 +00008996
Alex Denisov5dfac812015-08-06 04:51:14 +00008997 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
8998 Message->getReceiverInterface(),
8999 NSAPI::ClassId_NSMutableOrderedSet);
9000 if (!IsMutableSet && !IsMutableOrderedSet) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009001 return None;
9002 }
9003
9004 Selector Sel = Message->getSelector();
9005
9006 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9007 if (!MKOpt) {
9008 return None;
9009 }
9010
9011 NSAPI::NSSetMethodKind MK = *MKOpt;
9012
9013 switch (MK) {
9014 case NSAPI::NSMutableSet_addObject:
9015 case NSAPI::NSOrderedSet_setObjectAtIndex:
9016 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9017 case NSAPI::NSOrderedSet_insertObjectAtIndex:
9018 return 0;
9019 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9020 return 1;
9021 }
9022
9023 return None;
9024}
9025
9026void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9027 if (!Message->isInstanceMessage()) {
9028 return;
9029 }
9030
9031 Optional<int> ArgOpt;
9032
9033 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9034 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9035 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9036 return;
9037 }
9038
9039 int ArgIndex = *ArgOpt;
9040
Alex Denisove1d882c2015-03-04 17:55:52 +00009041 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9042 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9043 Arg = OE->getSourceExpr()->IgnoreImpCasts();
9044 }
9045
Alex Denisov5dfac812015-08-06 04:51:14 +00009046 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009047 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
Alex Denisov5dfac812015-08-06 04:51:14 +00009048 if (ArgRE->isObjCSelfExpr()) {
Alex Denisove1d882c2015-03-04 17:55:52 +00009049 Diag(Message->getSourceRange().getBegin(),
9050 diag::warn_objc_circular_container)
Alex Denisov5dfac812015-08-06 04:51:14 +00009051 << ArgRE->getDecl()->getName() << StringRef("super");
Alex Denisove1d882c2015-03-04 17:55:52 +00009052 }
9053 }
Alex Denisov5dfac812015-08-06 04:51:14 +00009054 } else {
9055 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9056
9057 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9058 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9059 }
9060
9061 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9062 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9063 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9064 ValueDecl *Decl = ReceiverRE->getDecl();
9065 Diag(Message->getSourceRange().getBegin(),
9066 diag::warn_objc_circular_container)
9067 << Decl->getName() << Decl->getName();
9068 if (!ArgRE->isObjCSelfExpr()) {
9069 Diag(Decl->getLocation(),
9070 diag::note_objc_circular_container_declared_here)
9071 << Decl->getName();
9072 }
9073 }
9074 }
9075 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9076 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9077 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9078 ObjCIvarDecl *Decl = IvarRE->getDecl();
9079 Diag(Message->getSourceRange().getBegin(),
9080 diag::warn_objc_circular_container)
9081 << Decl->getName() << Decl->getName();
9082 Diag(Decl->getLocation(),
9083 diag::note_objc_circular_container_declared_here)
9084 << Decl->getName();
9085 }
Alex Denisove1d882c2015-03-04 17:55:52 +00009086 }
9087 }
9088 }
9089
9090}
9091
John McCall31168b02011-06-15 23:02:42 +00009092/// Check a message send to see if it's likely to cause a retain cycle.
9093void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9094 // Only check instance methods whose selector looks like a setter.
9095 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9096 return;
9097
9098 // Try to find a variable that the receiver is strongly owned by.
9099 RetainCycleOwner owner;
9100 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009101 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00009102 return;
9103 } else {
9104 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9105 owner.Variable = getCurMethodDecl()->getSelfDecl();
9106 owner.Loc = msg->getSuperLoc();
9107 owner.Range = msg->getSuperLoc();
9108 }
9109
9110 // Check whether the receiver is captured by any of the arguments.
9111 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9112 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9113 return diagnoseRetainCycle(*this, capturer, owner);
9114}
9115
9116/// Check a property assign to see if it's likely to cause a retain cycle.
9117void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9118 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00009119 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00009120 return;
9121
9122 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9123 diagnoseRetainCycle(*this, capturer, owner);
9124}
9125
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009126void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9127 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00009128 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00009129 return;
9130
9131 // Because we don't have an expression for the variable, we have to set the
9132 // location explicitly here.
9133 Owner.Loc = Var->getLocation();
9134 Owner.Range = Var->getSourceRange();
9135
9136 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9137 diagnoseRetainCycle(*this, Capturer, Owner);
9138}
9139
Ted Kremenek9304da92012-12-21 08:04:28 +00009140static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9141 Expr *RHS, bool isProperty) {
9142 // Check if RHS is an Objective-C object literal, which also can get
9143 // immediately zapped in a weak reference. Note that we explicitly
9144 // allow ObjCStringLiterals, since those are designed to never really die.
9145 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009146
Ted Kremenek64873352012-12-21 22:46:35 +00009147 // This enum needs to match with the 'select' in
9148 // warn_objc_arc_literal_assign (off-by-1).
9149 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9150 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9151 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009152
9153 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00009154 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00009155 << (isProperty ? 0 : 1)
9156 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00009157
9158 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00009159}
9160
Ted Kremenekc1f014a2012-12-21 19:45:30 +00009161static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9162 Qualifiers::ObjCLifetime LT,
9163 Expr *RHS, bool isProperty) {
9164 // Strip off any implicit cast added to get to the one ARC-specific.
9165 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9166 if (cast->getCastKind() == CK_ARCConsumeObject) {
9167 S.Diag(Loc, diag::warn_arc_retained_assign)
9168 << (LT == Qualifiers::OCL_ExplicitNone)
9169 << (isProperty ? 0 : 1)
9170 << RHS->getSourceRange();
9171 return true;
9172 }
9173 RHS = cast->getSubExpr();
9174 }
9175
9176 if (LT == Qualifiers::OCL_Weak &&
9177 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9178 return true;
9179
9180 return false;
9181}
9182
Ted Kremenekb36234d2012-12-21 08:04:20 +00009183bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9184 QualType LHS, Expr *RHS) {
9185 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9186
9187 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9188 return false;
9189
9190 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9191 return true;
9192
9193 return false;
9194}
9195
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009196void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9197 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009198 QualType LHSType;
9199 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00009200 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009201 ObjCPropertyRefExpr *PRE
9202 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9203 if (PRE && !PRE->isImplicitProperty()) {
9204 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9205 if (PD)
9206 LHSType = PD->getType();
9207 }
9208
9209 if (LHSType.isNull())
9210 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00009211
9212 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9213
9214 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009215 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00009216 getCurFunction()->markSafeWeakUse(LHS);
9217 }
9218
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009219 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9220 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00009221
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009222 // FIXME. Check for other life times.
9223 if (LT != Qualifiers::OCL_None)
9224 return;
9225
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009226 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009227 if (PRE->isImplicitProperty())
9228 return;
9229 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9230 if (!PD)
9231 return;
9232
Bill Wendling44426052012-12-20 19:22:21 +00009233 unsigned Attributes = PD->getPropertyAttributes();
9234 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009235 // when 'assign' attribute was not explicitly specified
9236 // by user, ignore it and rely on property type itself
9237 // for lifetime info.
9238 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9239 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9240 LHSType->isObjCRetainableType())
9241 return;
9242
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009243 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00009244 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009245 Diag(Loc, diag::warn_arc_retained_property_assign)
9246 << RHS->getSourceRange();
9247 return;
9248 }
9249 RHS = cast->getSubExpr();
9250 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00009251 }
Bill Wendling44426052012-12-20 19:22:21 +00009252 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00009253 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9254 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00009255 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00009256 }
9257}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009258
9259//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9260
9261namespace {
9262bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9263 SourceLocation StmtLoc,
9264 const NullStmt *Body) {
9265 // Do not warn if the body is a macro that expands to nothing, e.g:
9266 //
9267 // #define CALL(x)
9268 // if (condition)
9269 // CALL(0);
9270 //
9271 if (Body->hasLeadingEmptyMacro())
9272 return false;
9273
9274 // Get line numbers of statement and body.
9275 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00009276 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009277 &StmtLineInvalid);
9278 if (StmtLineInvalid)
9279 return false;
9280
9281 bool BodyLineInvalid;
9282 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9283 &BodyLineInvalid);
9284 if (BodyLineInvalid)
9285 return false;
9286
9287 // Warn if null statement and body are on the same line.
9288 if (StmtLine != BodyLine)
9289 return false;
9290
9291 return true;
9292}
9293} // Unnamed namespace
9294
9295void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9296 const Stmt *Body,
9297 unsigned DiagID) {
9298 // Since this is a syntactic check, don't emit diagnostic for template
9299 // instantiations, this just adds noise.
9300 if (CurrentInstantiationScope)
9301 return;
9302
9303 // The body should be a null statement.
9304 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9305 if (!NBody)
9306 return;
9307
9308 // Do the usual checks.
9309 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9310 return;
9311
9312 Diag(NBody->getSemiLoc(), DiagID);
9313 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9314}
9315
9316void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9317 const Stmt *PossibleBody) {
9318 assert(!CurrentInstantiationScope); // Ensured by caller
9319
9320 SourceLocation StmtLoc;
9321 const Stmt *Body;
9322 unsigned DiagID;
9323 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9324 StmtLoc = FS->getRParenLoc();
9325 Body = FS->getBody();
9326 DiagID = diag::warn_empty_for_body;
9327 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9328 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9329 Body = WS->getBody();
9330 DiagID = diag::warn_empty_while_body;
9331 } else
9332 return; // Neither `for' nor `while'.
9333
9334 // The body should be a null statement.
9335 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9336 if (!NBody)
9337 return;
9338
9339 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009340 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009341 return;
9342
9343 // Do the usual checks.
9344 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9345 return;
9346
9347 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9348 // noise level low, emit diagnostics only if for/while is followed by a
9349 // CompoundStmt, e.g.:
9350 // for (int i = 0; i < n; i++);
9351 // {
9352 // a(i);
9353 // }
9354 // or if for/while is followed by a statement with more indentation
9355 // than for/while itself:
9356 // for (int i = 0; i < n; i++);
9357 // a(i);
9358 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9359 if (!ProbableTypo) {
9360 bool BodyColInvalid;
9361 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9362 PossibleBody->getLocStart(),
9363 &BodyColInvalid);
9364 if (BodyColInvalid)
9365 return;
9366
9367 bool StmtColInvalid;
9368 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9369 S->getLocStart(),
9370 &StmtColInvalid);
9371 if (StmtColInvalid)
9372 return;
9373
9374 if (BodyCol > StmtCol)
9375 ProbableTypo = true;
9376 }
9377
9378 if (ProbableTypo) {
9379 Diag(NBody->getSemiLoc(), DiagID);
9380 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9381 }
9382}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009383
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009384//===--- CHECK: Warn on self move with std::move. -------------------------===//
9385
9386/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9387void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9388 SourceLocation OpLoc) {
9389
9390 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9391 return;
9392
9393 if (!ActiveTemplateInstantiations.empty())
9394 return;
9395
9396 // Strip parens and casts away.
9397 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9398 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9399
9400 // Check for a call expression
9401 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9402 if (!CE || CE->getNumArgs() != 1)
9403 return;
9404
9405 // Check for a call to std::move
9406 const FunctionDecl *FD = CE->getDirectCallee();
9407 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9408 !FD->getIdentifier()->isStr("move"))
9409 return;
9410
9411 // Get argument from std::move
9412 RHSExpr = CE->getArg(0);
9413
9414 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9415 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9416
9417 // Two DeclRefExpr's, check that the decls are the same.
9418 if (LHSDeclRef && RHSDeclRef) {
9419 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9420 return;
9421 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9422 RHSDeclRef->getDecl()->getCanonicalDecl())
9423 return;
9424
9425 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9426 << LHSExpr->getSourceRange()
9427 << RHSExpr->getSourceRange();
9428 return;
9429 }
9430
9431 // Member variables require a different approach to check for self moves.
9432 // MemberExpr's are the same if every nested MemberExpr refers to the same
9433 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9434 // the base Expr's are CXXThisExpr's.
9435 const Expr *LHSBase = LHSExpr;
9436 const Expr *RHSBase = RHSExpr;
9437 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9438 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9439 if (!LHSME || !RHSME)
9440 return;
9441
9442 while (LHSME && RHSME) {
9443 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9444 RHSME->getMemberDecl()->getCanonicalDecl())
9445 return;
9446
9447 LHSBase = LHSME->getBase();
9448 RHSBase = RHSME->getBase();
9449 LHSME = dyn_cast<MemberExpr>(LHSBase);
9450 RHSME = dyn_cast<MemberExpr>(RHSBase);
9451 }
9452
9453 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9454 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9455 if (LHSDeclRef && RHSDeclRef) {
9456 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9457 return;
9458 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9459 RHSDeclRef->getDecl()->getCanonicalDecl())
9460 return;
9461
9462 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9463 << LHSExpr->getSourceRange()
9464 << RHSExpr->getSourceRange();
9465 return;
9466 }
9467
9468 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9469 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9470 << LHSExpr->getSourceRange()
9471 << RHSExpr->getSourceRange();
9472}
9473
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009474//===--- Layout compatibility ----------------------------------------------//
9475
9476namespace {
9477
9478bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9479
9480/// \brief Check if two enumeration types are layout-compatible.
9481bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9482 // C++11 [dcl.enum] p8:
9483 // Two enumeration types are layout-compatible if they have the same
9484 // underlying type.
9485 return ED1->isComplete() && ED2->isComplete() &&
9486 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9487}
9488
9489/// \brief Check if two fields are layout-compatible.
9490bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9491 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9492 return false;
9493
9494 if (Field1->isBitField() != Field2->isBitField())
9495 return false;
9496
9497 if (Field1->isBitField()) {
9498 // Make sure that the bit-fields are the same length.
9499 unsigned Bits1 = Field1->getBitWidthValue(C);
9500 unsigned Bits2 = Field2->getBitWidthValue(C);
9501
9502 if (Bits1 != Bits2)
9503 return false;
9504 }
9505
9506 return true;
9507}
9508
9509/// \brief Check if two standard-layout structs are layout-compatible.
9510/// (C++11 [class.mem] p17)
9511bool isLayoutCompatibleStruct(ASTContext &C,
9512 RecordDecl *RD1,
9513 RecordDecl *RD2) {
9514 // If both records are C++ classes, check that base classes match.
9515 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9516 // If one of records is a CXXRecordDecl we are in C++ mode,
9517 // thus the other one is a CXXRecordDecl, too.
9518 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9519 // Check number of base classes.
9520 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9521 return false;
9522
9523 // Check the base classes.
9524 for (CXXRecordDecl::base_class_const_iterator
9525 Base1 = D1CXX->bases_begin(),
9526 BaseEnd1 = D1CXX->bases_end(),
9527 Base2 = D2CXX->bases_begin();
9528 Base1 != BaseEnd1;
9529 ++Base1, ++Base2) {
9530 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9531 return false;
9532 }
9533 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9534 // If only RD2 is a C++ class, it should have zero base classes.
9535 if (D2CXX->getNumBases() > 0)
9536 return false;
9537 }
9538
9539 // Check the fields.
9540 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9541 Field2End = RD2->field_end(),
9542 Field1 = RD1->field_begin(),
9543 Field1End = RD1->field_end();
9544 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9545 if (!isLayoutCompatible(C, *Field1, *Field2))
9546 return false;
9547 }
9548 if (Field1 != Field1End || Field2 != Field2End)
9549 return false;
9550
9551 return true;
9552}
9553
9554/// \brief Check if two standard-layout unions are layout-compatible.
9555/// (C++11 [class.mem] p18)
9556bool isLayoutCompatibleUnion(ASTContext &C,
9557 RecordDecl *RD1,
9558 RecordDecl *RD2) {
9559 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009560 for (auto *Field2 : RD2->fields())
9561 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009562
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009563 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009564 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9565 I = UnmatchedFields.begin(),
9566 E = UnmatchedFields.end();
9567
9568 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009569 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009570 bool Result = UnmatchedFields.erase(*I);
9571 (void) Result;
9572 assert(Result);
9573 break;
9574 }
9575 }
9576 if (I == E)
9577 return false;
9578 }
9579
9580 return UnmatchedFields.empty();
9581}
9582
9583bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9584 if (RD1->isUnion() != RD2->isUnion())
9585 return false;
9586
9587 if (RD1->isUnion())
9588 return isLayoutCompatibleUnion(C, RD1, RD2);
9589 else
9590 return isLayoutCompatibleStruct(C, RD1, RD2);
9591}
9592
9593/// \brief Check if two types are layout-compatible in C++11 sense.
9594bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9595 if (T1.isNull() || T2.isNull())
9596 return false;
9597
9598 // C++11 [basic.types] p11:
9599 // If two types T1 and T2 are the same type, then T1 and T2 are
9600 // layout-compatible types.
9601 if (C.hasSameType(T1, T2))
9602 return true;
9603
9604 T1 = T1.getCanonicalType().getUnqualifiedType();
9605 T2 = T2.getCanonicalType().getUnqualifiedType();
9606
9607 const Type::TypeClass TC1 = T1->getTypeClass();
9608 const Type::TypeClass TC2 = T2->getTypeClass();
9609
9610 if (TC1 != TC2)
9611 return false;
9612
9613 if (TC1 == Type::Enum) {
9614 return isLayoutCompatible(C,
9615 cast<EnumType>(T1)->getDecl(),
9616 cast<EnumType>(T2)->getDecl());
9617 } else if (TC1 == Type::Record) {
9618 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9619 return false;
9620
9621 return isLayoutCompatible(C,
9622 cast<RecordType>(T1)->getDecl(),
9623 cast<RecordType>(T2)->getDecl());
9624 }
9625
9626 return false;
9627}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009628}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009629
9630//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9631
9632namespace {
9633/// \brief Given a type tag expression find the type tag itself.
9634///
9635/// \param TypeExpr Type tag expression, as it appears in user's code.
9636///
9637/// \param VD Declaration of an identifier that appears in a type tag.
9638///
9639/// \param MagicValue Type tag magic value.
9640bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9641 const ValueDecl **VD, uint64_t *MagicValue) {
9642 while(true) {
9643 if (!TypeExpr)
9644 return false;
9645
9646 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9647
9648 switch (TypeExpr->getStmtClass()) {
9649 case Stmt::UnaryOperatorClass: {
9650 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9651 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9652 TypeExpr = UO->getSubExpr();
9653 continue;
9654 }
9655 return false;
9656 }
9657
9658 case Stmt::DeclRefExprClass: {
9659 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9660 *VD = DRE->getDecl();
9661 return true;
9662 }
9663
9664 case Stmt::IntegerLiteralClass: {
9665 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9666 llvm::APInt MagicValueAPInt = IL->getValue();
9667 if (MagicValueAPInt.getActiveBits() <= 64) {
9668 *MagicValue = MagicValueAPInt.getZExtValue();
9669 return true;
9670 } else
9671 return false;
9672 }
9673
9674 case Stmt::BinaryConditionalOperatorClass:
9675 case Stmt::ConditionalOperatorClass: {
9676 const AbstractConditionalOperator *ACO =
9677 cast<AbstractConditionalOperator>(TypeExpr);
9678 bool Result;
9679 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9680 if (Result)
9681 TypeExpr = ACO->getTrueExpr();
9682 else
9683 TypeExpr = ACO->getFalseExpr();
9684 continue;
9685 }
9686 return false;
9687 }
9688
9689 case Stmt::BinaryOperatorClass: {
9690 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9691 if (BO->getOpcode() == BO_Comma) {
9692 TypeExpr = BO->getRHS();
9693 continue;
9694 }
9695 return false;
9696 }
9697
9698 default:
9699 return false;
9700 }
9701 }
9702}
9703
9704/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9705///
9706/// \param TypeExpr Expression that specifies a type tag.
9707///
9708/// \param MagicValues Registered magic values.
9709///
9710/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9711/// kind.
9712///
9713/// \param TypeInfo Information about the corresponding C type.
9714///
9715/// \returns true if the corresponding C type was found.
9716bool GetMatchingCType(
9717 const IdentifierInfo *ArgumentKind,
9718 const Expr *TypeExpr, const ASTContext &Ctx,
9719 const llvm::DenseMap<Sema::TypeTagMagicValue,
9720 Sema::TypeTagData> *MagicValues,
9721 bool &FoundWrongKind,
9722 Sema::TypeTagData &TypeInfo) {
9723 FoundWrongKind = false;
9724
9725 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009726 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009727
9728 uint64_t MagicValue;
9729
9730 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9731 return false;
9732
9733 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009734 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009735 if (I->getArgumentKind() != ArgumentKind) {
9736 FoundWrongKind = true;
9737 return false;
9738 }
9739 TypeInfo.Type = I->getMatchingCType();
9740 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9741 TypeInfo.MustBeNull = I->getMustBeNull();
9742 return true;
9743 }
9744 return false;
9745 }
9746
9747 if (!MagicValues)
9748 return false;
9749
9750 llvm::DenseMap<Sema::TypeTagMagicValue,
9751 Sema::TypeTagData>::const_iterator I =
9752 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9753 if (I == MagicValues->end())
9754 return false;
9755
9756 TypeInfo = I->second;
9757 return true;
9758}
9759} // unnamed namespace
9760
9761void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9762 uint64_t MagicValue, QualType Type,
9763 bool LayoutCompatible,
9764 bool MustBeNull) {
9765 if (!TypeTagForDatatypeMagicValues)
9766 TypeTagForDatatypeMagicValues.reset(
9767 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9768
9769 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9770 (*TypeTagForDatatypeMagicValues)[Magic] =
9771 TypeTagData(Type, LayoutCompatible, MustBeNull);
9772}
9773
9774namespace {
9775bool IsSameCharType(QualType T1, QualType T2) {
9776 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9777 if (!BT1)
9778 return false;
9779
9780 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9781 if (!BT2)
9782 return false;
9783
9784 BuiltinType::Kind T1Kind = BT1->getKind();
9785 BuiltinType::Kind T2Kind = BT2->getKind();
9786
9787 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9788 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9789 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9790 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9791}
9792} // unnamed namespace
9793
9794void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9795 const Expr * const *ExprArgs) {
9796 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9797 bool IsPointerAttr = Attr->getIsPointer();
9798
9799 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9800 bool FoundWrongKind;
9801 TypeTagData TypeInfo;
9802 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9803 TypeTagForDatatypeMagicValues.get(),
9804 FoundWrongKind, TypeInfo)) {
9805 if (FoundWrongKind)
9806 Diag(TypeTagExpr->getExprLoc(),
9807 diag::warn_type_tag_for_datatype_wrong_kind)
9808 << TypeTagExpr->getSourceRange();
9809 return;
9810 }
9811
9812 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9813 if (IsPointerAttr) {
9814 // Skip implicit cast of pointer to `void *' (as a function argument).
9815 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009816 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009817 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009818 ArgumentExpr = ICE->getSubExpr();
9819 }
9820 QualType ArgumentType = ArgumentExpr->getType();
9821
9822 // Passing a `void*' pointer shouldn't trigger a warning.
9823 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9824 return;
9825
9826 if (TypeInfo.MustBeNull) {
9827 // Type tag with matching void type requires a null pointer.
9828 if (!ArgumentExpr->isNullPointerConstant(Context,
9829 Expr::NPC_ValueDependentIsNotNull)) {
9830 Diag(ArgumentExpr->getExprLoc(),
9831 diag::warn_type_safety_null_pointer_required)
9832 << ArgumentKind->getName()
9833 << ArgumentExpr->getSourceRange()
9834 << TypeTagExpr->getSourceRange();
9835 }
9836 return;
9837 }
9838
9839 QualType RequiredType = TypeInfo.Type;
9840 if (IsPointerAttr)
9841 RequiredType = Context.getPointerType(RequiredType);
9842
9843 bool mismatch = false;
9844 if (!TypeInfo.LayoutCompatible) {
9845 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9846
9847 // C++11 [basic.fundamental] p1:
9848 // Plain char, signed char, and unsigned char are three distinct types.
9849 //
9850 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9851 // char' depending on the current char signedness mode.
9852 if (mismatch)
9853 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9854 RequiredType->getPointeeType())) ||
9855 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9856 mismatch = false;
9857 } else
9858 if (IsPointerAttr)
9859 mismatch = !isLayoutCompatible(Context,
9860 ArgumentType->getPointeeType(),
9861 RequiredType->getPointeeType());
9862 else
9863 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9864
9865 if (mismatch)
9866 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009867 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009868 << TypeInfo.LayoutCompatible << RequiredType
9869 << ArgumentExpr->getSourceRange()
9870 << TypeTagExpr->getSourceRange();
9871}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009872