blob: 48c276eb09b9e5b7d0fddd9ca44170c53912d71c [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
David Majnemerced8bdf2015-02-25 17:36:15 +0000187 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
324 return ExprError();
325 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
329 return true;
330 break;
John McCallbebede42011-02-26 05:39:39 +0000331
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
335 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000336 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000339 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000340 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000346 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000352 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000358 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000364 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000376 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000382 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000388 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000394 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000400 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000418 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000424 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000430 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000436 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000442 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000443#define BUILTIN(ID, TYPE, ATTRS)
444#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000448 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000449 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000450 return ExprError();
451 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
454 return ExprError();
455 break;
Richard Smith760520b2014-06-03 23:27:44 +0000456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
463 << "C++";
464 return ExprError();
465 }
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
469 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000470
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
482 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
485 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
489 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000490
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
493 return ExprError();
494 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000495
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
500 return ExprError();
501 break;
502 }
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
507 return ExprError();
508 break;
509 }
510
David Majnemerba3e5ec2015-03-13 18:26:17 +0000511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
513 return ExprError();
514
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
518 TheCall))
519 return ExprError();
520
521 TheCall->setType(Context.VoidPtrTy);
522 break;
523
Nate Begeman4904e322010-06-08 02:47:44 +0000524 }
Richard Smith760520b2014-06-03 23:27:44 +0000525
Nate Begeman4904e322010-06-08 02:47:44 +0000526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000529 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000530 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000531 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000532 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000533 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
535 return ExprError();
536 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000540 return ExprError();
541 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
556 return ExprError();
557 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
562 return ExprError();
563 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000564 default:
565 break;
566 }
567 }
568
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000569 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000570}
571
Nate Begeman91e1fea2010-06-14 05:21:25 +0000572// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000573static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000574 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000575 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000586 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000587 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000599 }
David Blaikie8a40f702012-01-17 06:56:22 +0000600 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000601}
602
Bob Wilsone4d77232011-11-08 05:04:11 +0000603/// getNeonEltType - Return the QualType corresponding to the elements of
604/// the vector type specified by the NeonTypeFlags. This is used to check
605/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000606static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000607 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000616 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
618 else
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000621 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000623 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000625 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000626 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000627 case NeonTypeFlags::Poly128:
628 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000629 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000630 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000631 case NeonTypeFlags::Float32:
632 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000633 case NeonTypeFlags::Float64:
634 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000635 }
David Blaikie8a40f702012-01-17 06:56:22 +0000636 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000637}
638
Tim Northover12670412014-02-19 10:37:05 +0000639bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000640 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000641 uint64_t mask = 0;
642 unsigned TV = 0;
643 int PtrArgNum = -1;
644 bool HasConstPtr = false;
645 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000646#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000647#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000648#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000649 }
650
651 // For NEON intrinsics which are overloaded on vector element type, validate
652 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000653 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000654 if (mask) {
655 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
656 return true;
657
658 TV = Result.getLimitedValue(64);
659 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
660 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000661 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000662 }
663
664 if (PtrArgNum >= 0) {
665 // Check that pointer arguments have the specified type.
666 Expr *Arg = TheCall->getArg(PtrArgNum);
667 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
668 Arg = ICE->getSubExpr();
669 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
670 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000671
Tim Northovera2ee4332014-03-29 15:09:45 +0000672 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000673 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000674 bool IsInt64Long =
675 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
676 QualType EltTy =
677 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000678 if (HasConstPtr)
679 EltTy = EltTy.withConst();
680 QualType LHSTy = Context.getPointerType(EltTy);
681 AssignConvertType ConvTy;
682 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
683 if (RHS.isInvalid())
684 return true;
685 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
686 RHS.get(), AA_Assigning))
687 return true;
688 }
689
690 // For NEON intrinsics which take an immediate value as part of the
691 // instruction, range check them here.
692 unsigned i = 0, l = 0, u = 0;
693 switch (BuiltinID) {
694 default:
695 return false;
Tim Northover12670412014-02-19 10:37:05 +0000696#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000697#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000698#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000699 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000700
Richard Sandiford28940af2014-04-16 08:47:51 +0000701 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000702}
703
Tim Northovera2ee4332014-03-29 15:09:45 +0000704bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
705 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000706 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000707 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000708 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000709 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000710 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000711 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
712 BuiltinID == AArch64::BI__builtin_arm_strex ||
713 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000714 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000715 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000716 BuiltinID == ARM::BI__builtin_arm_ldaex ||
717 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
718 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000719
720 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
721
722 // Ensure that we have the proper number of arguments.
723 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
724 return true;
725
726 // Inspect the pointer argument of the atomic builtin. This should always be
727 // a pointer type, whose element is an integral scalar or pointer type.
728 // Because it is a pointer type, we don't have to worry about any implicit
729 // casts here.
730 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
731 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
732 if (PointerArgRes.isInvalid())
733 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000734 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000735
736 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
737 if (!pointerType) {
738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
739 << PointerArg->getType() << PointerArg->getSourceRange();
740 return true;
741 }
742
743 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
744 // task is to insert the appropriate casts into the AST. First work out just
745 // what the appropriate type is.
746 QualType ValType = pointerType->getPointeeType();
747 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
748 if (IsLdrex)
749 AddrType.addConst();
750
751 // Issue a warning if the cast is dodgy.
752 CastKind CastNeeded = CK_NoOp;
753 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
754 CastNeeded = CK_BitCast;
755 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
756 << PointerArg->getType()
757 << Context.getPointerType(AddrType)
758 << AA_Passing << PointerArg->getSourceRange();
759 }
760
761 // Finally, do the cast and replace the argument with the corrected version.
762 AddrType = Context.getPointerType(AddrType);
763 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
764 if (PointerArgRes.isInvalid())
765 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000766 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000767
768 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
769
770 // In general, we allow ints, floats and pointers to be loaded and stored.
771 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
772 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
773 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
774 << PointerArg->getType() << PointerArg->getSourceRange();
775 return true;
776 }
777
778 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000779 if (Context.getTypeSize(ValType) > MaxWidth) {
780 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000781 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
782 << PointerArg->getType() << PointerArg->getSourceRange();
783 return true;
784 }
785
786 switch (ValType.getObjCLifetime()) {
787 case Qualifiers::OCL_None:
788 case Qualifiers::OCL_ExplicitNone:
789 // okay
790 break;
791
792 case Qualifiers::OCL_Weak:
793 case Qualifiers::OCL_Strong:
794 case Qualifiers::OCL_Autoreleasing:
795 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
796 << ValType << PointerArg->getSourceRange();
797 return true;
798 }
799
800
801 if (IsLdrex) {
802 TheCall->setType(ValType);
803 return false;
804 }
805
806 // Initialize the argument to be stored.
807 ExprResult ValArg = TheCall->getArg(0);
808 InitializedEntity Entity = InitializedEntity::InitializeParameter(
809 Context, ValType, /*consume*/ false);
810 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
811 if (ValArg.isInvalid())
812 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000813 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000814
815 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
816 // but the custom checker bypasses all default analysis.
817 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000818 return false;
819}
820
Nate Begeman4904e322010-06-08 02:47:44 +0000821bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000822 llvm::APSInt Result;
823
Tim Northover6aacd492013-07-16 09:47:53 +0000824 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000825 BuiltinID == ARM::BI__builtin_arm_ldaex ||
826 BuiltinID == ARM::BI__builtin_arm_strex ||
827 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000828 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000829 }
830
Yi Kong26d104a2014-08-13 19:18:14 +0000831 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
832 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
833 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
834 }
835
Tim Northover12670412014-02-19 10:37:05 +0000836 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
837 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000838
Yi Kong4efadfb2014-07-03 16:01:25 +0000839 // For intrinsics which take an immediate value as part of the instruction,
840 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000841 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000842 switch (BuiltinID) {
843 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000844 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
845 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000846 case ARM::BI__builtin_arm_vcvtr_f:
847 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000848 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000849 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000850 case ARM::BI__builtin_arm_isb:
851 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000852 }
Nate Begemand773fe62010-06-13 04:47:52 +0000853
Nate Begemanf568b072010-08-03 21:32:34 +0000854 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000855 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000856}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000857
Tim Northover573cbee2014-05-24 12:52:07 +0000858bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000859 CallExpr *TheCall) {
860 llvm::APSInt Result;
861
Tim Northover573cbee2014-05-24 12:52:07 +0000862 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000863 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
864 BuiltinID == AArch64::BI__builtin_arm_strex ||
865 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000866 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
867 }
868
Yi Konga5548432014-08-13 19:18:20 +0000869 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
870 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
871 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
872 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
873 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
874 }
875
Tim Northovera2ee4332014-03-29 15:09:45 +0000876 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
877 return true;
878
Yi Kong19a29ac2014-07-17 10:52:06 +0000879 // For intrinsics which take an immediate value as part of the instruction,
880 // range check them here.
881 unsigned i = 0, l = 0, u = 0;
882 switch (BuiltinID) {
883 default: return false;
884 case AArch64::BI__builtin_arm_dmb:
885 case AArch64::BI__builtin_arm_dsb:
886 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
887 }
888
Yi Kong19a29ac2014-07-17 10:52:06 +0000889 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000890}
891
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000892bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
893 unsigned i = 0, l = 0, u = 0;
894 switch (BuiltinID) {
895 default: return false;
896 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
897 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000898 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
899 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
900 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
901 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
902 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000903 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000904
Richard Sandiford28940af2014-04-16 08:47:51 +0000905 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000906}
907
Kit Bartone50adcb2015-03-30 19:40:59 +0000908bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
909 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000910 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
911 BuiltinID == PPC::BI__builtin_divdeu ||
912 BuiltinID == PPC::BI__builtin_bpermd;
913 bool IsTarget64Bit = Context.getTargetInfo()
914 .getTypeWidth(Context
915 .getTargetInfo()
916 .getIntPtrType()) == 64;
917 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
918 BuiltinID == PPC::BI__builtin_divweu ||
919 BuiltinID == PPC::BI__builtin_divde ||
920 BuiltinID == PPC::BI__builtin_divdeu;
921
922 if (Is64BitBltin && !IsTarget64Bit)
923 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
924 << TheCall->getSourceRange();
925
926 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
927 (BuiltinID == PPC::BI__builtin_bpermd &&
928 !Context.getTargetInfo().hasFeature("bpermd")))
929 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
930 << TheCall->getSourceRange();
931
Kit Bartone50adcb2015-03-30 19:40:59 +0000932 switch (BuiltinID) {
933 default: return false;
934 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
935 case PPC::BI__builtin_altivec_crypto_vshasigmad:
936 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
937 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
938 case PPC::BI__builtin_tbegin:
939 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
940 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
941 case PPC::BI__builtin_tabortwc:
942 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
943 case PPC::BI__builtin_tabortwci:
944 case PPC::BI__builtin_tabortdci:
945 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
946 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
947 }
948 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
949}
950
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000951bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
952 CallExpr *TheCall) {
953 if (BuiltinID == SystemZ::BI__builtin_tabort) {
954 Expr *Arg = TheCall->getArg(0);
955 llvm::APSInt AbortCode(32);
956 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
957 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
958 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
959 << Arg->getSourceRange();
960 }
961
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000962 // For intrinsics which take an immediate value as part of the instruction,
963 // range check them here.
964 unsigned i = 0, l = 0, u = 0;
965 switch (BuiltinID) {
966 default: return false;
967 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
968 case SystemZ::BI__builtin_s390_verimb:
969 case SystemZ::BI__builtin_s390_verimh:
970 case SystemZ::BI__builtin_s390_verimf:
971 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
972 case SystemZ::BI__builtin_s390_vfaeb:
973 case SystemZ::BI__builtin_s390_vfaeh:
974 case SystemZ::BI__builtin_s390_vfaef:
975 case SystemZ::BI__builtin_s390_vfaebs:
976 case SystemZ::BI__builtin_s390_vfaehs:
977 case SystemZ::BI__builtin_s390_vfaefs:
978 case SystemZ::BI__builtin_s390_vfaezb:
979 case SystemZ::BI__builtin_s390_vfaezh:
980 case SystemZ::BI__builtin_s390_vfaezf:
981 case SystemZ::BI__builtin_s390_vfaezbs:
982 case SystemZ::BI__builtin_s390_vfaezhs:
983 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
984 case SystemZ::BI__builtin_s390_vfidb:
985 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
986 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
987 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
988 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
989 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
990 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
991 case SystemZ::BI__builtin_s390_vstrcb:
992 case SystemZ::BI__builtin_s390_vstrch:
993 case SystemZ::BI__builtin_s390_vstrcf:
994 case SystemZ::BI__builtin_s390_vstrczb:
995 case SystemZ::BI__builtin_s390_vstrczh:
996 case SystemZ::BI__builtin_s390_vstrczf:
997 case SystemZ::BI__builtin_s390_vstrcbs:
998 case SystemZ::BI__builtin_s390_vstrchs:
999 case SystemZ::BI__builtin_s390_vstrcfs:
1000 case SystemZ::BI__builtin_s390_vstrczbs:
1001 case SystemZ::BI__builtin_s390_vstrczhs:
1002 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1003 }
1004 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001005}
1006
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001007bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001008 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001009 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001010 default: return false;
1011 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001012 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001013 case X86::BI__builtin_ia32_vpermil2pd:
1014 case X86::BI__builtin_ia32_vpermil2pd256:
1015 case X86::BI__builtin_ia32_vpermil2ps:
1016 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001017 case X86::BI__builtin_ia32_cmpb128_mask:
1018 case X86::BI__builtin_ia32_cmpw128_mask:
1019 case X86::BI__builtin_ia32_cmpd128_mask:
1020 case X86::BI__builtin_ia32_cmpq128_mask:
1021 case X86::BI__builtin_ia32_cmpb256_mask:
1022 case X86::BI__builtin_ia32_cmpw256_mask:
1023 case X86::BI__builtin_ia32_cmpd256_mask:
1024 case X86::BI__builtin_ia32_cmpq256_mask:
1025 case X86::BI__builtin_ia32_cmpb512_mask:
1026 case X86::BI__builtin_ia32_cmpw512_mask:
1027 case X86::BI__builtin_ia32_cmpd512_mask:
1028 case X86::BI__builtin_ia32_cmpq512_mask:
1029 case X86::BI__builtin_ia32_ucmpb128_mask:
1030 case X86::BI__builtin_ia32_ucmpw128_mask:
1031 case X86::BI__builtin_ia32_ucmpd128_mask:
1032 case X86::BI__builtin_ia32_ucmpq128_mask:
1033 case X86::BI__builtin_ia32_ucmpb256_mask:
1034 case X86::BI__builtin_ia32_ucmpw256_mask:
1035 case X86::BI__builtin_ia32_ucmpd256_mask:
1036 case X86::BI__builtin_ia32_ucmpq256_mask:
1037 case X86::BI__builtin_ia32_ucmpb512_mask:
1038 case X86::BI__builtin_ia32_ucmpw512_mask:
1039 case X86::BI__builtin_ia32_ucmpd512_mask:
1040 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001041 case X86::BI__builtin_ia32_roundps:
1042 case X86::BI__builtin_ia32_roundpd:
1043 case X86::BI__builtin_ia32_roundps256:
1044 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1045 case X86::BI__builtin_ia32_roundss:
1046 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1047 case X86::BI__builtin_ia32_cmpps:
1048 case X86::BI__builtin_ia32_cmpss:
1049 case X86::BI__builtin_ia32_cmppd:
1050 case X86::BI__builtin_ia32_cmpsd:
1051 case X86::BI__builtin_ia32_cmpps256:
1052 case X86::BI__builtin_ia32_cmppd256:
1053 case X86::BI__builtin_ia32_cmpps512_mask:
1054 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001055 case X86::BI__builtin_ia32_vpcomub:
1056 case X86::BI__builtin_ia32_vpcomuw:
1057 case X86::BI__builtin_ia32_vpcomud:
1058 case X86::BI__builtin_ia32_vpcomuq:
1059 case X86::BI__builtin_ia32_vpcomb:
1060 case X86::BI__builtin_ia32_vpcomw:
1061 case X86::BI__builtin_ia32_vpcomd:
1062 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001063 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001064 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001065}
1066
Richard Smith55ce3522012-06-25 20:30:08 +00001067/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1068/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1069/// Returns true when the format fits the function and the FormatStringInfo has
1070/// been populated.
1071bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1072 FormatStringInfo *FSI) {
1073 FSI->HasVAListArg = Format->getFirstArg() == 0;
1074 FSI->FormatIdx = Format->getFormatIdx() - 1;
1075 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001076
Richard Smith55ce3522012-06-25 20:30:08 +00001077 // The way the format attribute works in GCC, the implicit this argument
1078 // of member functions is counted. However, it doesn't appear in our own
1079 // lists, so decrement format_idx in that case.
1080 if (IsCXXMember) {
1081 if(FSI->FormatIdx == 0)
1082 return false;
1083 --FSI->FormatIdx;
1084 if (FSI->FirstDataArg != 0)
1085 --FSI->FirstDataArg;
1086 }
1087 return true;
1088}
Mike Stump11289f42009-09-09 15:08:12 +00001089
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001090/// Checks if a the given expression evaluates to null.
1091///
1092/// \brief Returns true if the value evaluates to null.
1093static bool CheckNonNullExpr(Sema &S,
1094 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001095 // As a special case, transparent unions initialized with zero are
1096 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001097 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001098 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1099 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001100 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001101 if (const InitListExpr *ILE =
1102 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001103 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001104 }
1105
1106 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001107 return (!Expr->isValueDependent() &&
1108 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1109 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001110}
1111
1112static void CheckNonNullArgument(Sema &S,
1113 const Expr *ArgExpr,
1114 SourceLocation CallSiteLoc) {
1115 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001116 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1117}
1118
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001119bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1120 FormatStringInfo FSI;
1121 if ((GetFormatStringType(Format) == FST_NSString) &&
1122 getFormatStringInfo(Format, false, &FSI)) {
1123 Idx = FSI.FormatIdx;
1124 return true;
1125 }
1126 return false;
1127}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001128/// \brief Diagnose use of %s directive in an NSString which is being passed
1129/// as formatting string to formatting method.
1130static void
1131DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1132 const NamedDecl *FDecl,
1133 Expr **Args,
1134 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001135 unsigned Idx = 0;
1136 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001137 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1138 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001139 Idx = 2;
1140 Format = true;
1141 }
1142 else
1143 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1144 if (S.GetFormatNSStringIdx(I, Idx)) {
1145 Format = true;
1146 break;
1147 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001148 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001149 if (!Format || NumArgs <= Idx)
1150 return;
1151 const Expr *FormatExpr = Args[Idx];
1152 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1153 FormatExpr = CSCE->getSubExpr();
1154 const StringLiteral *FormatString;
1155 if (const ObjCStringLiteral *OSL =
1156 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1157 FormatString = OSL->getString();
1158 else
1159 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1160 if (!FormatString)
1161 return;
1162 if (S.FormatStringHasSArg(FormatString)) {
1163 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1164 << "%s" << 1 << 1;
1165 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1166 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001167 }
1168}
1169
Ted Kremenek2bc73332014-01-17 06:24:43 +00001170static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001171 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001172 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001173 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001174 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001175 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001176 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001177 if (!NonNull->args_size()) {
1178 // Easy case: all pointer arguments are nonnull.
1179 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001180 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001181 CheckNonNullArgument(S, Arg, CallSiteLoc);
1182 return;
1183 }
1184
1185 for (unsigned Val : NonNull->args()) {
1186 if (Val >= Args.size())
1187 continue;
1188 if (NonNullArgs.empty())
1189 NonNullArgs.resize(Args.size());
1190 NonNullArgs.set(Val);
1191 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001192 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001193
1194 // Check the attributes on the parameters.
1195 ArrayRef<ParmVarDecl*> parms;
1196 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1197 parms = FD->parameters();
1198 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1199 parms = MD->parameters();
1200
Richard Smith588bd9b2014-08-27 04:59:42 +00001201 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001202 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001203 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001204 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001205 if (PVD->hasAttr<NonNullAttr>() ||
1206 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1207 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001208 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001209
1210 // In case this is a variadic call, check any remaining arguments.
1211 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1212 if (NonNullArgs[ArgIndex])
1213 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001214}
1215
Richard Smith55ce3522012-06-25 20:30:08 +00001216/// Handles the checks for format strings, non-POD arguments to vararg
1217/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001218void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1219 unsigned NumParams, bool IsMemberFunction,
1220 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001221 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001222 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001223 if (CurContext->isDependentContext())
1224 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001225
Ted Kremenekb8176da2010-09-09 04:33:05 +00001226 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001227 llvm::SmallBitVector CheckedVarArgs;
1228 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001229 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001230 // Only create vector if there are format attributes.
1231 CheckedVarArgs.resize(Args.size());
1232
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001233 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001234 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001235 }
Richard Smithd7293d72013-08-05 18:49:43 +00001236 }
Richard Smith55ce3522012-06-25 20:30:08 +00001237
1238 // Refuse POD arguments that weren't caught by the format string
1239 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001240 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001241 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001242 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001243 if (const Expr *Arg = Args[ArgIdx]) {
1244 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1245 checkVariadicArgument(Arg, CallType);
1246 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001247 }
Richard Smithd7293d72013-08-05 18:49:43 +00001248 }
Mike Stump11289f42009-09-09 15:08:12 +00001249
Richard Trieu41bc0992013-06-22 00:20:41 +00001250 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001251 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001252
Richard Trieu41bc0992013-06-22 00:20:41 +00001253 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001254 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1255 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001256 }
Richard Smith55ce3522012-06-25 20:30:08 +00001257}
1258
1259/// CheckConstructorCall - Check a constructor call for correctness and safety
1260/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001261void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1262 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001263 const FunctionProtoType *Proto,
1264 SourceLocation Loc) {
1265 VariadicCallType CallType =
1266 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001267 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001268 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1269}
1270
1271/// CheckFunctionCall - Check a direct function call for various correctness
1272/// and safety properties not strictly enforced by the C type system.
1273bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1274 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001275 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1276 isa<CXXMethodDecl>(FDecl);
1277 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1278 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001279 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1280 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001281 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001282 Expr** Args = TheCall->getArgs();
1283 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001284 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001285 // If this is a call to a member operator, hide the first argument
1286 // from checkCall.
1287 // FIXME: Our choice of AST representation here is less than ideal.
1288 ++Args;
1289 --NumArgs;
1290 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001291 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001292 IsMemberFunction, TheCall->getRParenLoc(),
1293 TheCall->getCallee()->getSourceRange(), CallType);
1294
1295 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1296 // None of the checks below are needed for functions that don't have
1297 // simple names (e.g., C++ conversion functions).
1298 if (!FnInfo)
1299 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001300
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001301 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001302 if (getLangOpts().ObjC1)
1303 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001304
Anna Zaks22122702012-01-17 00:37:07 +00001305 unsigned CMId = FDecl->getMemoryFunctionKind();
1306 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001307 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001308
Anna Zaks201d4892012-01-13 21:52:01 +00001309 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001310 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001311 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001312 else if (CMId == Builtin::BIstrncat)
1313 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001314 else
Anna Zaks22122702012-01-17 00:37:07 +00001315 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001316
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001317 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001318}
1319
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001320bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001321 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001322 VariadicCallType CallType =
1323 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001324
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001325 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001326 /*IsMemberFunction=*/false,
1327 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001328
1329 return false;
1330}
1331
Richard Trieu664c4c62013-06-20 21:03:13 +00001332bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1333 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001334 QualType Ty;
1335 if (const auto *V = dyn_cast<VarDecl>(NDecl))
1336 Ty = V->getType();
1337 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1338 Ty = F->getType();
1339 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001340 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001341
Richard Trieu664c4c62013-06-20 21:03:13 +00001342 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001343 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001344
Richard Trieu664c4c62013-06-20 21:03:13 +00001345 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001346 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001347 CallType = VariadicDoesNotApply;
1348 } else if (Ty->isBlockPointerType()) {
1349 CallType = VariadicBlock;
1350 } else { // Ty->isFunctionPointerType()
1351 CallType = VariadicFunction;
1352 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001353 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001354
Craig Topper8c2a2a02014-08-30 16:55:39 +00001355 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1356 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001357 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001358 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001359
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001360 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001361}
1362
Richard Trieu41bc0992013-06-22 00:20:41 +00001363/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1364/// such as function pointers returned from functions.
1365bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001366 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001367 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001368 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001369
Craig Topperc3ec1492014-05-26 06:22:03 +00001370 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001371 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001372 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001373 TheCall->getCallee()->getSourceRange(), CallType);
1374
1375 return false;
1376}
1377
Tim Northovere94a34c2014-03-11 10:49:14 +00001378static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1379 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1380 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1381 return false;
1382
1383 switch (Op) {
1384 case AtomicExpr::AO__c11_atomic_init:
1385 llvm_unreachable("There is no ordering argument for an init");
1386
1387 case AtomicExpr::AO__c11_atomic_load:
1388 case AtomicExpr::AO__atomic_load_n:
1389 case AtomicExpr::AO__atomic_load:
1390 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1391 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1392
1393 case AtomicExpr::AO__c11_atomic_store:
1394 case AtomicExpr::AO__atomic_store:
1395 case AtomicExpr::AO__atomic_store_n:
1396 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1397 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1398 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1399
1400 default:
1401 return true;
1402 }
1403}
1404
Richard Smithfeea8832012-04-12 05:08:17 +00001405ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1406 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001407 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1408 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001409
Richard Smithfeea8832012-04-12 05:08:17 +00001410 // All these operations take one of the following forms:
1411 enum {
1412 // C __c11_atomic_init(A *, C)
1413 Init,
1414 // C __c11_atomic_load(A *, int)
1415 Load,
1416 // void __atomic_load(A *, CP, int)
1417 Copy,
1418 // C __c11_atomic_add(A *, M, int)
1419 Arithmetic,
1420 // C __atomic_exchange_n(A *, CP, int)
1421 Xchg,
1422 // void __atomic_exchange(A *, C *, CP, int)
1423 GNUXchg,
1424 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1425 C11CmpXchg,
1426 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1427 GNUCmpXchg
1428 } Form = Init;
1429 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1430 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1431 // where:
1432 // C is an appropriate type,
1433 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1434 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1435 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1436 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001437
Gabor Horvath98bd0982015-03-16 09:59:54 +00001438 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1439 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1440 AtomicExpr::AO__atomic_load,
1441 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001442 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1443 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1444 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1445 Op == AtomicExpr::AO__atomic_store_n ||
1446 Op == AtomicExpr::AO__atomic_exchange_n ||
1447 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1448 bool IsAddSub = false;
1449
1450 switch (Op) {
1451 case AtomicExpr::AO__c11_atomic_init:
1452 Form = Init;
1453 break;
1454
1455 case AtomicExpr::AO__c11_atomic_load:
1456 case AtomicExpr::AO__atomic_load_n:
1457 Form = Load;
1458 break;
1459
1460 case AtomicExpr::AO__c11_atomic_store:
1461 case AtomicExpr::AO__atomic_load:
1462 case AtomicExpr::AO__atomic_store:
1463 case AtomicExpr::AO__atomic_store_n:
1464 Form = Copy;
1465 break;
1466
1467 case AtomicExpr::AO__c11_atomic_fetch_add:
1468 case AtomicExpr::AO__c11_atomic_fetch_sub:
1469 case AtomicExpr::AO__atomic_fetch_add:
1470 case AtomicExpr::AO__atomic_fetch_sub:
1471 case AtomicExpr::AO__atomic_add_fetch:
1472 case AtomicExpr::AO__atomic_sub_fetch:
1473 IsAddSub = true;
1474 // Fall through.
1475 case AtomicExpr::AO__c11_atomic_fetch_and:
1476 case AtomicExpr::AO__c11_atomic_fetch_or:
1477 case AtomicExpr::AO__c11_atomic_fetch_xor:
1478 case AtomicExpr::AO__atomic_fetch_and:
1479 case AtomicExpr::AO__atomic_fetch_or:
1480 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001481 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001482 case AtomicExpr::AO__atomic_and_fetch:
1483 case AtomicExpr::AO__atomic_or_fetch:
1484 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001485 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001486 Form = Arithmetic;
1487 break;
1488
1489 case AtomicExpr::AO__c11_atomic_exchange:
1490 case AtomicExpr::AO__atomic_exchange_n:
1491 Form = Xchg;
1492 break;
1493
1494 case AtomicExpr::AO__atomic_exchange:
1495 Form = GNUXchg;
1496 break;
1497
1498 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1499 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1500 Form = C11CmpXchg;
1501 break;
1502
1503 case AtomicExpr::AO__atomic_compare_exchange:
1504 case AtomicExpr::AO__atomic_compare_exchange_n:
1505 Form = GNUCmpXchg;
1506 break;
1507 }
1508
1509 // Check we have the right number of arguments.
1510 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001511 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001512 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001513 << TheCall->getCallee()->getSourceRange();
1514 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001515 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1516 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001517 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001518 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001519 << TheCall->getCallee()->getSourceRange();
1520 return ExprError();
1521 }
1522
Richard Smithfeea8832012-04-12 05:08:17 +00001523 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001524 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001525 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1526 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1527 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001528 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001529 << Ptr->getType() << Ptr->getSourceRange();
1530 return ExprError();
1531 }
1532
Richard Smithfeea8832012-04-12 05:08:17 +00001533 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1534 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1535 QualType ValType = AtomTy; // 'C'
1536 if (IsC11) {
1537 if (!AtomTy->isAtomicType()) {
1538 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1539 << Ptr->getType() << Ptr->getSourceRange();
1540 return ExprError();
1541 }
Richard Smithe00921a2012-09-15 06:09:58 +00001542 if (AtomTy.isConstQualified()) {
1543 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1544 << Ptr->getType() << Ptr->getSourceRange();
1545 return ExprError();
1546 }
Richard Smithfeea8832012-04-12 05:08:17 +00001547 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001548 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001549
Richard Smithfeea8832012-04-12 05:08:17 +00001550 // For an arithmetic operation, the implied arithmetic must be well-formed.
1551 if (Form == Arithmetic) {
1552 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1553 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1554 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1555 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1556 return ExprError();
1557 }
1558 if (!IsAddSub && !ValType->isIntegerType()) {
1559 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1560 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1561 return ExprError();
1562 }
David Majnemere85cff82015-01-28 05:48:06 +00001563 if (IsC11 && ValType->isPointerType() &&
1564 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1565 diag::err_incomplete_type)) {
1566 return ExprError();
1567 }
Richard Smithfeea8832012-04-12 05:08:17 +00001568 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1569 // For __atomic_*_n operations, the value type must be a scalar integral or
1570 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001571 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001572 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1573 return ExprError();
1574 }
1575
Eli Friedmanaa769812013-09-11 03:49:34 +00001576 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1577 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001578 // For GNU atomics, require a trivially-copyable type. This is not part of
1579 // the GNU atomics specification, but we enforce it for sanity.
1580 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001581 << Ptr->getType() << Ptr->getSourceRange();
1582 return ExprError();
1583 }
1584
Richard Smithfeea8832012-04-12 05:08:17 +00001585 // FIXME: For any builtin other than a load, the ValType must not be
1586 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001587
1588 switch (ValType.getObjCLifetime()) {
1589 case Qualifiers::OCL_None:
1590 case Qualifiers::OCL_ExplicitNone:
1591 // okay
1592 break;
1593
1594 case Qualifiers::OCL_Weak:
1595 case Qualifiers::OCL_Strong:
1596 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001597 // FIXME: Can this happen? By this point, ValType should be known
1598 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001599 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1600 << ValType << Ptr->getSourceRange();
1601 return ExprError();
1602 }
1603
1604 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001605 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001606 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001607 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001608 ResultType = Context.BoolTy;
1609
Richard Smithfeea8832012-04-12 05:08:17 +00001610 // The type of a parameter passed 'by value'. In the GNU atomics, such
1611 // arguments are actually passed as pointers.
1612 QualType ByValType = ValType; // 'CP'
1613 if (!IsC11 && !IsN)
1614 ByValType = Ptr->getType();
1615
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001616 // The first argument --- the pointer --- has a fixed type; we
1617 // deduce the types of the rest of the arguments accordingly. Walk
1618 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001619 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001620 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001621 if (i < NumVals[Form] + 1) {
1622 switch (i) {
1623 case 1:
1624 // The second argument is the non-atomic operand. For arithmetic, this
1625 // is always passed by value, and for a compare_exchange it is always
1626 // passed by address. For the rest, GNU uses by-address and C11 uses
1627 // by-value.
1628 assert(Form != Load);
1629 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1630 Ty = ValType;
1631 else if (Form == Copy || Form == Xchg)
1632 Ty = ByValType;
1633 else if (Form == Arithmetic)
1634 Ty = Context.getPointerDiffType();
1635 else
1636 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1637 break;
1638 case 2:
1639 // The third argument to compare_exchange / GNU exchange is a
1640 // (pointer to a) desired value.
1641 Ty = ByValType;
1642 break;
1643 case 3:
1644 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1645 Ty = Context.BoolTy;
1646 break;
1647 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001648 } else {
1649 // The order(s) are always converted to int.
1650 Ty = Context.IntTy;
1651 }
Richard Smithfeea8832012-04-12 05:08:17 +00001652
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001653 InitializedEntity Entity =
1654 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001655 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001656 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1657 if (Arg.isInvalid())
1658 return true;
1659 TheCall->setArg(i, Arg.get());
1660 }
1661
Richard Smithfeea8832012-04-12 05:08:17 +00001662 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001663 SmallVector<Expr*, 5> SubExprs;
1664 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001665 switch (Form) {
1666 case Init:
1667 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001668 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001669 break;
1670 case Load:
1671 SubExprs.push_back(TheCall->getArg(1)); // Order
1672 break;
1673 case Copy:
1674 case Arithmetic:
1675 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001676 SubExprs.push_back(TheCall->getArg(2)); // Order
1677 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001678 break;
1679 case GNUXchg:
1680 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1681 SubExprs.push_back(TheCall->getArg(3)); // Order
1682 SubExprs.push_back(TheCall->getArg(1)); // Val1
1683 SubExprs.push_back(TheCall->getArg(2)); // Val2
1684 break;
1685 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001686 SubExprs.push_back(TheCall->getArg(3)); // Order
1687 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001688 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001689 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001690 break;
1691 case GNUCmpXchg:
1692 SubExprs.push_back(TheCall->getArg(4)); // Order
1693 SubExprs.push_back(TheCall->getArg(1)); // Val1
1694 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1695 SubExprs.push_back(TheCall->getArg(2)); // Val2
1696 SubExprs.push_back(TheCall->getArg(3)); // Weak
1697 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001698 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001699
1700 if (SubExprs.size() >= 2 && Form != Init) {
1701 llvm::APSInt Result(32);
1702 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1703 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001704 Diag(SubExprs[1]->getLocStart(),
1705 diag::warn_atomic_op_has_invalid_memory_order)
1706 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001707 }
1708
Fariborz Jahanian615de762013-05-28 17:37:39 +00001709 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1710 SubExprs, ResultType, Op,
1711 TheCall->getRParenLoc());
1712
1713 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1714 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1715 Context.AtomicUsesUnsupportedLibcall(AE))
1716 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1717 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001718
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001719 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001720}
1721
1722
John McCall29ad95b2011-08-27 01:09:30 +00001723/// checkBuiltinArgument - Given a call to a builtin function, perform
1724/// normal type-checking on the given argument, updating the call in
1725/// place. This is useful when a builtin function requires custom
1726/// type-checking for some of its arguments but not necessarily all of
1727/// them.
1728///
1729/// Returns true on error.
1730static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1731 FunctionDecl *Fn = E->getDirectCallee();
1732 assert(Fn && "builtin call without direct callee!");
1733
1734 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1735 InitializedEntity Entity =
1736 InitializedEntity::InitializeParameter(S.Context, Param);
1737
1738 ExprResult Arg = E->getArg(0);
1739 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1740 if (Arg.isInvalid())
1741 return true;
1742
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001743 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001744 return false;
1745}
1746
Chris Lattnerdc046542009-05-08 06:58:22 +00001747/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1748/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1749/// type of its first argument. The main ActOnCallExpr routines have already
1750/// promoted the types of arguments because all of these calls are prototyped as
1751/// void(...).
1752///
1753/// This function goes through and does final semantic checking for these
1754/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001755ExprResult
1756Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001757 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001758 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1759 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1760
1761 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001762 if (TheCall->getNumArgs() < 1) {
1763 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1764 << 0 << 1 << TheCall->getNumArgs()
1765 << TheCall->getCallee()->getSourceRange();
1766 return ExprError();
1767 }
Mike Stump11289f42009-09-09 15:08:12 +00001768
Chris Lattnerdc046542009-05-08 06:58:22 +00001769 // Inspect the first argument of the atomic builtin. This should always be
1770 // a pointer type, whose element is an integral scalar or pointer type.
1771 // Because it is a pointer type, we don't have to worry about any implicit
1772 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001773 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001774 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001775 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1776 if (FirstArgResult.isInvalid())
1777 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001778 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001779 TheCall->setArg(0, FirstArg);
1780
John McCall31168b02011-06-15 23:02:42 +00001781 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1782 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001783 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1784 << FirstArg->getType() << FirstArg->getSourceRange();
1785 return ExprError();
1786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787
John McCall31168b02011-06-15 23:02:42 +00001788 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001789 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001790 !ValType->isBlockPointerType()) {
1791 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1792 << FirstArg->getType() << FirstArg->getSourceRange();
1793 return ExprError();
1794 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001795
John McCall31168b02011-06-15 23:02:42 +00001796 switch (ValType.getObjCLifetime()) {
1797 case Qualifiers::OCL_None:
1798 case Qualifiers::OCL_ExplicitNone:
1799 // okay
1800 break;
1801
1802 case Qualifiers::OCL_Weak:
1803 case Qualifiers::OCL_Strong:
1804 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001805 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001806 << ValType << FirstArg->getSourceRange();
1807 return ExprError();
1808 }
1809
John McCallb50451a2011-10-05 07:41:44 +00001810 // Strip any qualifiers off ValType.
1811 ValType = ValType.getUnqualifiedType();
1812
Chandler Carruth3973af72010-07-18 20:54:12 +00001813 // The majority of builtins return a value, but a few have special return
1814 // types, so allow them to override appropriately below.
1815 QualType ResultType = ValType;
1816
Chris Lattnerdc046542009-05-08 06:58:22 +00001817 // We need to figure out which concrete builtin this maps onto. For example,
1818 // __sync_fetch_and_add with a 2 byte object turns into
1819 // __sync_fetch_and_add_2.
1820#define BUILTIN_ROW(x) \
1821 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1822 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001823
Chris Lattnerdc046542009-05-08 06:58:22 +00001824 static const unsigned BuiltinIndices[][5] = {
1825 BUILTIN_ROW(__sync_fetch_and_add),
1826 BUILTIN_ROW(__sync_fetch_and_sub),
1827 BUILTIN_ROW(__sync_fetch_and_or),
1828 BUILTIN_ROW(__sync_fetch_and_and),
1829 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001830 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001831
Chris Lattnerdc046542009-05-08 06:58:22 +00001832 BUILTIN_ROW(__sync_add_and_fetch),
1833 BUILTIN_ROW(__sync_sub_and_fetch),
1834 BUILTIN_ROW(__sync_and_and_fetch),
1835 BUILTIN_ROW(__sync_or_and_fetch),
1836 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001837 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001838
Chris Lattnerdc046542009-05-08 06:58:22 +00001839 BUILTIN_ROW(__sync_val_compare_and_swap),
1840 BUILTIN_ROW(__sync_bool_compare_and_swap),
1841 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001842 BUILTIN_ROW(__sync_lock_release),
1843 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001844 };
Mike Stump11289f42009-09-09 15:08:12 +00001845#undef BUILTIN_ROW
1846
Chris Lattnerdc046542009-05-08 06:58:22 +00001847 // Determine the index of the size.
1848 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001849 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001850 case 1: SizeIndex = 0; break;
1851 case 2: SizeIndex = 1; break;
1852 case 4: SizeIndex = 2; break;
1853 case 8: SizeIndex = 3; break;
1854 case 16: SizeIndex = 4; break;
1855 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001856 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1857 << FirstArg->getType() << FirstArg->getSourceRange();
1858 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001859 }
Mike Stump11289f42009-09-09 15:08:12 +00001860
Chris Lattnerdc046542009-05-08 06:58:22 +00001861 // Each of these builtins has one pointer argument, followed by some number of
1862 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1863 // that we ignore. Find out which row of BuiltinIndices to read from as well
1864 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001865 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001866 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001867 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001868 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001869 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001870 case Builtin::BI__sync_fetch_and_add:
1871 case Builtin::BI__sync_fetch_and_add_1:
1872 case Builtin::BI__sync_fetch_and_add_2:
1873 case Builtin::BI__sync_fetch_and_add_4:
1874 case Builtin::BI__sync_fetch_and_add_8:
1875 case Builtin::BI__sync_fetch_and_add_16:
1876 BuiltinIndex = 0;
1877 break;
1878
1879 case Builtin::BI__sync_fetch_and_sub:
1880 case Builtin::BI__sync_fetch_and_sub_1:
1881 case Builtin::BI__sync_fetch_and_sub_2:
1882 case Builtin::BI__sync_fetch_and_sub_4:
1883 case Builtin::BI__sync_fetch_and_sub_8:
1884 case Builtin::BI__sync_fetch_and_sub_16:
1885 BuiltinIndex = 1;
1886 break;
1887
1888 case Builtin::BI__sync_fetch_and_or:
1889 case Builtin::BI__sync_fetch_and_or_1:
1890 case Builtin::BI__sync_fetch_and_or_2:
1891 case Builtin::BI__sync_fetch_and_or_4:
1892 case Builtin::BI__sync_fetch_and_or_8:
1893 case Builtin::BI__sync_fetch_and_or_16:
1894 BuiltinIndex = 2;
1895 break;
1896
1897 case Builtin::BI__sync_fetch_and_and:
1898 case Builtin::BI__sync_fetch_and_and_1:
1899 case Builtin::BI__sync_fetch_and_and_2:
1900 case Builtin::BI__sync_fetch_and_and_4:
1901 case Builtin::BI__sync_fetch_and_and_8:
1902 case Builtin::BI__sync_fetch_and_and_16:
1903 BuiltinIndex = 3;
1904 break;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregor73722482011-11-28 16:30:08 +00001906 case Builtin::BI__sync_fetch_and_xor:
1907 case Builtin::BI__sync_fetch_and_xor_1:
1908 case Builtin::BI__sync_fetch_and_xor_2:
1909 case Builtin::BI__sync_fetch_and_xor_4:
1910 case Builtin::BI__sync_fetch_and_xor_8:
1911 case Builtin::BI__sync_fetch_and_xor_16:
1912 BuiltinIndex = 4;
1913 break;
1914
Hal Finkeld2208b52014-10-02 20:53:50 +00001915 case Builtin::BI__sync_fetch_and_nand:
1916 case Builtin::BI__sync_fetch_and_nand_1:
1917 case Builtin::BI__sync_fetch_and_nand_2:
1918 case Builtin::BI__sync_fetch_and_nand_4:
1919 case Builtin::BI__sync_fetch_and_nand_8:
1920 case Builtin::BI__sync_fetch_and_nand_16:
1921 BuiltinIndex = 5;
1922 WarnAboutSemanticsChange = true;
1923 break;
1924
Douglas Gregor73722482011-11-28 16:30:08 +00001925 case Builtin::BI__sync_add_and_fetch:
1926 case Builtin::BI__sync_add_and_fetch_1:
1927 case Builtin::BI__sync_add_and_fetch_2:
1928 case Builtin::BI__sync_add_and_fetch_4:
1929 case Builtin::BI__sync_add_and_fetch_8:
1930 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001931 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001932 break;
1933
1934 case Builtin::BI__sync_sub_and_fetch:
1935 case Builtin::BI__sync_sub_and_fetch_1:
1936 case Builtin::BI__sync_sub_and_fetch_2:
1937 case Builtin::BI__sync_sub_and_fetch_4:
1938 case Builtin::BI__sync_sub_and_fetch_8:
1939 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001940 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001941 break;
1942
1943 case Builtin::BI__sync_and_and_fetch:
1944 case Builtin::BI__sync_and_and_fetch_1:
1945 case Builtin::BI__sync_and_and_fetch_2:
1946 case Builtin::BI__sync_and_and_fetch_4:
1947 case Builtin::BI__sync_and_and_fetch_8:
1948 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001949 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001950 break;
1951
1952 case Builtin::BI__sync_or_and_fetch:
1953 case Builtin::BI__sync_or_and_fetch_1:
1954 case Builtin::BI__sync_or_and_fetch_2:
1955 case Builtin::BI__sync_or_and_fetch_4:
1956 case Builtin::BI__sync_or_and_fetch_8:
1957 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001958 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001959 break;
1960
1961 case Builtin::BI__sync_xor_and_fetch:
1962 case Builtin::BI__sync_xor_and_fetch_1:
1963 case Builtin::BI__sync_xor_and_fetch_2:
1964 case Builtin::BI__sync_xor_and_fetch_4:
1965 case Builtin::BI__sync_xor_and_fetch_8:
1966 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001967 BuiltinIndex = 10;
1968 break;
1969
1970 case Builtin::BI__sync_nand_and_fetch:
1971 case Builtin::BI__sync_nand_and_fetch_1:
1972 case Builtin::BI__sync_nand_and_fetch_2:
1973 case Builtin::BI__sync_nand_and_fetch_4:
1974 case Builtin::BI__sync_nand_and_fetch_8:
1975 case Builtin::BI__sync_nand_and_fetch_16:
1976 BuiltinIndex = 11;
1977 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001978 break;
Mike Stump11289f42009-09-09 15:08:12 +00001979
Chris Lattnerdc046542009-05-08 06:58:22 +00001980 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001981 case Builtin::BI__sync_val_compare_and_swap_1:
1982 case Builtin::BI__sync_val_compare_and_swap_2:
1983 case Builtin::BI__sync_val_compare_and_swap_4:
1984 case Builtin::BI__sync_val_compare_and_swap_8:
1985 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001986 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001987 NumFixed = 2;
1988 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001989
Chris Lattnerdc046542009-05-08 06:58:22 +00001990 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001991 case Builtin::BI__sync_bool_compare_and_swap_1:
1992 case Builtin::BI__sync_bool_compare_and_swap_2:
1993 case Builtin::BI__sync_bool_compare_and_swap_4:
1994 case Builtin::BI__sync_bool_compare_and_swap_8:
1995 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001996 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001997 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001998 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001999 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002000
2001 case Builtin::BI__sync_lock_test_and_set:
2002 case Builtin::BI__sync_lock_test_and_set_1:
2003 case Builtin::BI__sync_lock_test_and_set_2:
2004 case Builtin::BI__sync_lock_test_and_set_4:
2005 case Builtin::BI__sync_lock_test_and_set_8:
2006 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002007 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002008 break;
2009
Chris Lattnerdc046542009-05-08 06:58:22 +00002010 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002011 case Builtin::BI__sync_lock_release_1:
2012 case Builtin::BI__sync_lock_release_2:
2013 case Builtin::BI__sync_lock_release_4:
2014 case Builtin::BI__sync_lock_release_8:
2015 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002016 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002017 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002018 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002019 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002020
2021 case Builtin::BI__sync_swap:
2022 case Builtin::BI__sync_swap_1:
2023 case Builtin::BI__sync_swap_2:
2024 case Builtin::BI__sync_swap_4:
2025 case Builtin::BI__sync_swap_8:
2026 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002027 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002028 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Chris Lattnerdc046542009-05-08 06:58:22 +00002031 // Now that we know how many fixed arguments we expect, first check that we
2032 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002033 if (TheCall->getNumArgs() < 1+NumFixed) {
2034 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2035 << 0 << 1+NumFixed << TheCall->getNumArgs()
2036 << TheCall->getCallee()->getSourceRange();
2037 return ExprError();
2038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
Hal Finkeld2208b52014-10-02 20:53:50 +00002040 if (WarnAboutSemanticsChange) {
2041 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2042 << TheCall->getCallee()->getSourceRange();
2043 }
2044
Chris Lattner5b9241b2009-05-08 15:36:58 +00002045 // Get the decl for the concrete builtin from this, we can tell what the
2046 // concrete integer type we should convert to is.
2047 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2048 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002049 FunctionDecl *NewBuiltinDecl;
2050 if (NewBuiltinID == BuiltinID)
2051 NewBuiltinDecl = FDecl;
2052 else {
2053 // Perform builtin lookup to avoid redeclaring it.
2054 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2055 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2056 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2057 assert(Res.getFoundDecl());
2058 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002059 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002060 return ExprError();
2061 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002062
John McCallcf142162010-08-07 06:22:56 +00002063 // The first argument --- the pointer --- has a fixed type; we
2064 // deduce the types of the rest of the arguments accordingly. Walk
2065 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002066 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002067 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002068
Chris Lattnerdc046542009-05-08 06:58:22 +00002069 // GCC does an implicit conversion to the pointer or integer ValType. This
2070 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002071 // Initialize the argument.
2072 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2073 ValType, /*consume*/ false);
2074 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002075 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002076 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002077
Chris Lattnerdc046542009-05-08 06:58:22 +00002078 // Okay, we have something that *can* be converted to the right type. Check
2079 // to see if there is a potentially weird extension going on here. This can
2080 // happen when you do an atomic operation on something like an char* and
2081 // pass in 42. The 42 gets converted to char. This is even more strange
2082 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002083 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002084 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002087 ASTContext& Context = this->getASTContext();
2088
2089 // Create a new DeclRefExpr to refer to the new decl.
2090 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2091 Context,
2092 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002093 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002094 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002095 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002096 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002097 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002098 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002099
Chris Lattnerdc046542009-05-08 06:58:22 +00002100 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002101 // FIXME: This loses syntactic information.
2102 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2103 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2104 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002105 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002106
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002107 // Change the result type of the call to match the original value type. This
2108 // is arbitrary, but the codegen for these builtins ins design to handle it
2109 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002110 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002111
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002112 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002113}
2114
Chris Lattner6436fb62009-02-18 06:01:06 +00002115/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002116/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002117/// Note: It might also make sense to do the UTF-16 conversion here (would
2118/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002119bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002120 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002121 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2122
Douglas Gregorfb65e592011-07-27 05:40:30 +00002123 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002124 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2125 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002126 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002127 }
Mike Stump11289f42009-09-09 15:08:12 +00002128
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002129 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002130 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002131 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002132 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002133 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002134 UTF16 *ToPtr = &ToBuf[0];
2135
2136 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2137 &ToPtr, ToPtr + NumBytes,
2138 strictConversion);
2139 // Check for conversion failure.
2140 if (Result != conversionOK)
2141 Diag(Arg->getLocStart(),
2142 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2143 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002144 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002145}
2146
Chris Lattnere202e6a2007-12-20 00:05:45 +00002147/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2148/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002149bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2150 Expr *Fn = TheCall->getCallee();
2151 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002152 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002153 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002154 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2155 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002156 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002157 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002158 return true;
2159 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002160
2161 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002162 return Diag(TheCall->getLocEnd(),
2163 diag::err_typecheck_call_too_few_args_at_least)
2164 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002165 }
2166
John McCall29ad95b2011-08-27 01:09:30 +00002167 // Type-check the first argument normally.
2168 if (checkBuiltinArgument(*this, TheCall, 0))
2169 return true;
2170
Chris Lattnere202e6a2007-12-20 00:05:45 +00002171 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002172 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002173 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002174 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002175 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002176 else if (FunctionDecl *FD = getCurFunctionDecl())
2177 isVariadic = FD->isVariadic();
2178 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002179 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002180
Chris Lattnere202e6a2007-12-20 00:05:45 +00002181 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002182 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2183 return true;
2184 }
Mike Stump11289f42009-09-09 15:08:12 +00002185
Chris Lattner43be2e62007-12-19 23:59:04 +00002186 // Verify that the second argument to the builtin is the last argument of the
2187 // current function or method.
2188 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002189 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002190
Nico Weber9eea7642013-05-24 23:31:57 +00002191 // These are valid if SecondArgIsLastNamedArgument is false after the next
2192 // block.
2193 QualType Type;
2194 SourceLocation ParamLoc;
2195
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002196 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2197 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002198 // FIXME: This isn't correct for methods (results in bogus warning).
2199 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002200 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002201 if (CurBlock)
2202 LastArg = *(CurBlock->TheDecl->param_end()-1);
2203 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002204 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002205 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002206 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002207 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002208
2209 Type = PV->getType();
2210 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002211 }
2212 }
Mike Stump11289f42009-09-09 15:08:12 +00002213
Chris Lattner43be2e62007-12-19 23:59:04 +00002214 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002215 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002216 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002217 else if (Type->isReferenceType()) {
2218 Diag(Arg->getLocStart(),
2219 diag::warn_va_start_of_reference_type_is_undefined);
2220 Diag(ParamLoc, diag::note_parameter_type) << Type;
2221 }
2222
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002223 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002224 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002225}
Chris Lattner43be2e62007-12-19 23:59:04 +00002226
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002227bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2228 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2229 // const char *named_addr);
2230
2231 Expr *Func = Call->getCallee();
2232
2233 if (Call->getNumArgs() < 3)
2234 return Diag(Call->getLocEnd(),
2235 diag::err_typecheck_call_too_few_args_at_least)
2236 << 0 /*function call*/ << 3 << Call->getNumArgs();
2237
2238 // Determine whether the current function is variadic or not.
2239 bool IsVariadic;
2240 if (BlockScopeInfo *CurBlock = getCurBlock())
2241 IsVariadic = CurBlock->TheDecl->isVariadic();
2242 else if (FunctionDecl *FD = getCurFunctionDecl())
2243 IsVariadic = FD->isVariadic();
2244 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2245 IsVariadic = MD->isVariadic();
2246 else
2247 llvm_unreachable("unexpected statement type");
2248
2249 if (!IsVariadic) {
2250 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2251 return true;
2252 }
2253
2254 // Type-check the first argument normally.
2255 if (checkBuiltinArgument(*this, Call, 0))
2256 return true;
2257
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002258 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002259 unsigned ArgNo;
2260 QualType Type;
2261 } ArgumentTypes[] = {
2262 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2263 { 2, Context.getSizeType() },
2264 };
2265
2266 for (const auto &AT : ArgumentTypes) {
2267 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2268 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2269 continue;
2270 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2271 << Arg->getType() << AT.Type << 1 /* different class */
2272 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2273 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2274 }
2275
2276 return false;
2277}
2278
Chris Lattner2da14fb2007-12-20 00:26:33 +00002279/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2280/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002281bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2282 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002283 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002284 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002285 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002286 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002287 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002288 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002289 << SourceRange(TheCall->getArg(2)->getLocStart(),
2290 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002291
John Wiegley01296292011-04-08 18:41:53 +00002292 ExprResult OrigArg0 = TheCall->getArg(0);
2293 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002294
Chris Lattner2da14fb2007-12-20 00:26:33 +00002295 // Do standard promotions between the two arguments, returning their common
2296 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002297 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002298 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2299 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002300
2301 // Make sure any conversions are pushed back into the call; this is
2302 // type safe since unordered compare builtins are declared as "_Bool
2303 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002304 TheCall->setArg(0, OrigArg0.get());
2305 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002306
John Wiegley01296292011-04-08 18:41:53 +00002307 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002308 return false;
2309
Chris Lattner2da14fb2007-12-20 00:26:33 +00002310 // If the common type isn't a real floating type, then the arguments were
2311 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002312 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002313 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002314 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002315 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2316 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002317
Chris Lattner2da14fb2007-12-20 00:26:33 +00002318 return false;
2319}
2320
Benjamin Kramer634fc102010-02-15 22:42:31 +00002321/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2322/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002323/// to check everything. We expect the last argument to be a floating point
2324/// value.
2325bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2326 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002327 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002328 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002329 if (TheCall->getNumArgs() > NumArgs)
2330 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002331 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002332 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002333 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002334 (*(TheCall->arg_end()-1))->getLocEnd());
2335
Benjamin Kramer64aae502010-02-16 10:07:31 +00002336 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002337
Eli Friedman7e4faac2009-08-31 20:06:00 +00002338 if (OrigArg->isTypeDependent())
2339 return false;
2340
Chris Lattner68784ef2010-05-06 05:50:07 +00002341 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002342 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002343 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002344 diag::err_typecheck_call_invalid_unary_fp)
2345 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002346
Chris Lattner68784ef2010-05-06 05:50:07 +00002347 // If this is an implicit conversion from float -> double, remove it.
2348 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2349 Expr *CastArg = Cast->getSubExpr();
2350 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2351 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2352 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002353 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002354 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002355 }
2356 }
2357
Eli Friedman7e4faac2009-08-31 20:06:00 +00002358 return false;
2359}
2360
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002361/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2362// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002363ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002364 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002365 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002366 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002367 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2368 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002369
Nate Begemana0110022010-06-08 00:16:34 +00002370 // Determine which of the following types of shufflevector we're checking:
2371 // 1) unary, vector mask: (lhs, mask)
2372 // 2) binary, vector mask: (lhs, rhs, mask)
2373 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2374 QualType resType = TheCall->getArg(0)->getType();
2375 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002376
Douglas Gregorc25f7662009-05-19 22:10:17 +00002377 if (!TheCall->getArg(0)->isTypeDependent() &&
2378 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002379 QualType LHSType = TheCall->getArg(0)->getType();
2380 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002381
Craig Topperbaca3892013-07-29 06:47:04 +00002382 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2383 return ExprError(Diag(TheCall->getLocStart(),
2384 diag::err_shufflevector_non_vector)
2385 << SourceRange(TheCall->getArg(0)->getLocStart(),
2386 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002387
Nate Begemana0110022010-06-08 00:16:34 +00002388 numElements = LHSType->getAs<VectorType>()->getNumElements();
2389 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Nate Begemana0110022010-06-08 00:16:34 +00002391 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2392 // with mask. If so, verify that RHS is an integer vector type with the
2393 // same number of elts as lhs.
2394 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002395 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002396 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002397 return ExprError(Diag(TheCall->getLocStart(),
2398 diag::err_shufflevector_incompatible_vector)
2399 << SourceRange(TheCall->getArg(1)->getLocStart(),
2400 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002401 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002402 return ExprError(Diag(TheCall->getLocStart(),
2403 diag::err_shufflevector_incompatible_vector)
2404 << SourceRange(TheCall->getArg(0)->getLocStart(),
2405 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002406 } else if (numElements != numResElements) {
2407 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002408 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002409 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002410 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002411 }
2412
2413 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002414 if (TheCall->getArg(i)->isTypeDependent() ||
2415 TheCall->getArg(i)->isValueDependent())
2416 continue;
2417
Nate Begemana0110022010-06-08 00:16:34 +00002418 llvm::APSInt Result(32);
2419 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2420 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002421 diag::err_shufflevector_nonconstant_argument)
2422 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002423
Craig Topper50ad5b72013-08-03 17:40:38 +00002424 // Allow -1 which will be translated to undef in the IR.
2425 if (Result.isSigned() && Result.isAllOnesValue())
2426 continue;
2427
Chris Lattner7ab824e2008-08-10 02:05:13 +00002428 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002429 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002430 diag::err_shufflevector_argument_too_large)
2431 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002432 }
2433
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002434 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002435
Chris Lattner7ab824e2008-08-10 02:05:13 +00002436 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002437 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002438 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002439 }
2440
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002441 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2442 TheCall->getCallee()->getLocStart(),
2443 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002444}
Chris Lattner43be2e62007-12-19 23:59:04 +00002445
Hal Finkelc4d7c822013-09-18 03:29:45 +00002446/// SemaConvertVectorExpr - Handle __builtin_convertvector
2447ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2448 SourceLocation BuiltinLoc,
2449 SourceLocation RParenLoc) {
2450 ExprValueKind VK = VK_RValue;
2451 ExprObjectKind OK = OK_Ordinary;
2452 QualType DstTy = TInfo->getType();
2453 QualType SrcTy = E->getType();
2454
2455 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2456 return ExprError(Diag(BuiltinLoc,
2457 diag::err_convertvector_non_vector)
2458 << E->getSourceRange());
2459 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2460 return ExprError(Diag(BuiltinLoc,
2461 diag::err_convertvector_non_vector_type));
2462
2463 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2464 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2465 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2466 if (SrcElts != DstElts)
2467 return ExprError(Diag(BuiltinLoc,
2468 diag::err_convertvector_incompatible_vector)
2469 << E->getSourceRange());
2470 }
2471
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002472 return new (Context)
2473 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002474}
2475
Daniel Dunbarb7257262008-07-21 22:59:13 +00002476/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2477// This is declared to take (const void*, ...) and can take two
2478// optional constant int args.
2479bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002480 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002481
Chris Lattner3b054132008-11-19 05:08:23 +00002482 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002483 return Diag(TheCall->getLocEnd(),
2484 diag::err_typecheck_call_too_many_args_at_most)
2485 << 0 /*function call*/ << 3 << NumArgs
2486 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002487
2488 // Argument 0 is checked for us and the remaining arguments must be
2489 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002490 for (unsigned i = 1; i != NumArgs; ++i)
2491 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002492 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002493
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002494 return false;
2495}
2496
Hal Finkelf0417332014-07-17 14:25:55 +00002497/// SemaBuiltinAssume - Handle __assume (MS Extension).
2498// __assume does not evaluate its arguments, and should warn if its argument
2499// has side effects.
2500bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2501 Expr *Arg = TheCall->getArg(0);
2502 if (Arg->isInstantiationDependent()) return false;
2503
2504 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002505 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002506 << Arg->getSourceRange()
2507 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2508
2509 return false;
2510}
2511
2512/// Handle __builtin_assume_aligned. This is declared
2513/// as (const void*, size_t, ...) and can take one optional constant int arg.
2514bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2515 unsigned NumArgs = TheCall->getNumArgs();
2516
2517 if (NumArgs > 3)
2518 return Diag(TheCall->getLocEnd(),
2519 diag::err_typecheck_call_too_many_args_at_most)
2520 << 0 /*function call*/ << 3 << NumArgs
2521 << TheCall->getSourceRange();
2522
2523 // The alignment must be a constant integer.
2524 Expr *Arg = TheCall->getArg(1);
2525
2526 // We can't check the value of a dependent argument.
2527 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2528 llvm::APSInt Result;
2529 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2530 return true;
2531
2532 if (!Result.isPowerOf2())
2533 return Diag(TheCall->getLocStart(),
2534 diag::err_alignment_not_power_of_two)
2535 << Arg->getSourceRange();
2536 }
2537
2538 if (NumArgs > 2) {
2539 ExprResult Arg(TheCall->getArg(2));
2540 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2541 Context.getSizeType(), false);
2542 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2543 if (Arg.isInvalid()) return true;
2544 TheCall->setArg(2, Arg.get());
2545 }
Hal Finkelf0417332014-07-17 14:25:55 +00002546
2547 return false;
2548}
2549
Eric Christopher8d0c6212010-04-17 02:26:23 +00002550/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2551/// TheCall is a constant expression.
2552bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2553 llvm::APSInt &Result) {
2554 Expr *Arg = TheCall->getArg(ArgNum);
2555 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2556 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2557
2558 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2559
2560 if (!Arg->isIntegerConstantExpr(Result, Context))
2561 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002562 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002563
Chris Lattnerd545ad12009-09-23 06:06:36 +00002564 return false;
2565}
2566
Richard Sandiford28940af2014-04-16 08:47:51 +00002567/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2568/// TheCall is a constant expression in the range [Low, High].
2569bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2570 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002571 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002572
2573 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002574 Expr *Arg = TheCall->getArg(ArgNum);
2575 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002576 return false;
2577
Eric Christopher8d0c6212010-04-17 02:26:23 +00002578 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002579 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002580 return true;
2581
Richard Sandiford28940af2014-04-16 08:47:51 +00002582 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002583 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002584 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002585
2586 return false;
2587}
2588
Eli Friedmanc97d0142009-05-03 06:04:26 +00002589/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002590/// This checks that the target supports __builtin_longjmp and
2591/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002592bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002593 if (!Context.getTargetInfo().hasSjLjLowering())
2594 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2595 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2596
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002597 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002598 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002599
Eric Christopher8d0c6212010-04-17 02:26:23 +00002600 // TODO: This is less than ideal. Overload this to take a value.
2601 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2602 return true;
2603
2604 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002605 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2606 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2607
2608 return false;
2609}
2610
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002611
2612/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2613/// This checks that the target supports __builtin_setjmp.
2614bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2615 if (!Context.getTargetInfo().hasSjLjLowering())
2616 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2617 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2618 return false;
2619}
2620
Richard Smithd7293d72013-08-05 18:49:43 +00002621namespace {
2622enum StringLiteralCheckType {
2623 SLCT_NotALiteral,
2624 SLCT_UncheckedLiteral,
2625 SLCT_CheckedLiteral
2626};
2627}
2628
Richard Smith55ce3522012-06-25 20:30:08 +00002629// Determine if an expression is a string literal or constant string.
2630// If this function returns false on the arguments to a function expecting a
2631// format string, we will usually need to emit a warning.
2632// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002633static StringLiteralCheckType
2634checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2635 bool HasVAListArg, unsigned format_idx,
2636 unsigned firstDataArg, Sema::FormatStringType Type,
2637 Sema::VariadicCallType CallType, bool InFunctionCall,
2638 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002639 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002640 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002641 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002642
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002643 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002644
Richard Smithd7293d72013-08-05 18:49:43 +00002645 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002646 // Technically -Wformat-nonliteral does not warn about this case.
2647 // The behavior of printf and friends in this case is implementation
2648 // dependent. Ideally if the format string cannot be null then
2649 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002650 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002651
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002652 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002653 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002654 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002655 // The expression is a literal if both sub-expressions were, and it was
2656 // completely checked only if both sub-expressions were checked.
2657 const AbstractConditionalOperator *C =
2658 cast<AbstractConditionalOperator>(E);
2659 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002660 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002661 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002662 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002663 if (Left == SLCT_NotALiteral)
2664 return SLCT_NotALiteral;
2665 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002666 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002667 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002668 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002669 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002670 }
2671
2672 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002673 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2674 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002675 }
2676
John McCallc07a0c72011-02-17 10:25:35 +00002677 case Stmt::OpaqueValueExprClass:
2678 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2679 E = src;
2680 goto tryAgain;
2681 }
Richard Smith55ce3522012-06-25 20:30:08 +00002682 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002683
Ted Kremeneka8890832011-02-24 23:03:04 +00002684 case Stmt::PredefinedExprClass:
2685 // While __func__, etc., are technically not string literals, they
2686 // cannot contain format specifiers and thus are not a security
2687 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002688 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002689
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002690 case Stmt::DeclRefExprClass: {
2691 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002692
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002693 // As an exception, do not flag errors for variables binding to
2694 // const string literals.
2695 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2696 bool isConstant = false;
2697 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002698
Richard Smithd7293d72013-08-05 18:49:43 +00002699 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2700 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002701 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002702 isConstant = T.isConstant(S.Context) &&
2703 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002704 } else if (T->isObjCObjectPointerType()) {
2705 // In ObjC, there is usually no "const ObjectPointer" type,
2706 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002707 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002708 }
Mike Stump11289f42009-09-09 15:08:12 +00002709
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002710 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002711 if (const Expr *Init = VD->getAnyInitializer()) {
2712 // Look through initializers like const char c[] = { "foo" }
2713 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2714 if (InitList->isStringLiteralInit())
2715 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2716 }
Richard Smithd7293d72013-08-05 18:49:43 +00002717 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002718 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002719 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002720 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002721 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002722 }
Mike Stump11289f42009-09-09 15:08:12 +00002723
Anders Carlssonb012ca92009-06-28 19:55:58 +00002724 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2725 // special check to see if the format string is a function parameter
2726 // of the function calling the printf function. If the function
2727 // has an attribute indicating it is a printf-like function, then we
2728 // should suppress warnings concerning non-literals being used in a call
2729 // to a vprintf function. For example:
2730 //
2731 // void
2732 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2733 // va_list ap;
2734 // va_start(ap, fmt);
2735 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2736 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002737 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002738 if (HasVAListArg) {
2739 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2740 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2741 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002742 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002743 // adjust for implicit parameter
2744 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2745 if (MD->isInstance())
2746 ++PVIndex;
2747 // We also check if the formats are compatible.
2748 // We can't pass a 'scanf' string to a 'printf' function.
2749 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002750 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002751 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002752 }
2753 }
2754 }
2755 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002756 }
Mike Stump11289f42009-09-09 15:08:12 +00002757
Richard Smith55ce3522012-06-25 20:30:08 +00002758 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002759 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002760
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002761 case Stmt::CallExprClass:
2762 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002763 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002764 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2765 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2766 unsigned ArgIndex = FA->getFormatIdx();
2767 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2768 if (MD->isInstance())
2769 --ArgIndex;
2770 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002771
Richard Smithd7293d72013-08-05 18:49:43 +00002772 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002773 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002774 Type, CallType, InFunctionCall,
2775 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002776 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2777 unsigned BuiltinID = FD->getBuiltinID();
2778 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2779 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2780 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002781 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002782 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002783 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002784 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002785 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002786 }
2787 }
Mike Stump11289f42009-09-09 15:08:12 +00002788
Richard Smith55ce3522012-06-25 20:30:08 +00002789 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002790 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002791 case Stmt::ObjCStringLiteralClass:
2792 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002793 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002794
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002795 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002796 StrE = ObjCFExpr->getString();
2797 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002798 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002800 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002801 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2802 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002803 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002804 }
Mike Stump11289f42009-09-09 15:08:12 +00002805
Richard Smith55ce3522012-06-25 20:30:08 +00002806 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002809 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002810 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002811 }
2812}
2813
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002814Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002815 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002816 .Case("scanf", FST_Scanf)
2817 .Cases("printf", "printf0", FST_Printf)
2818 .Cases("NSString", "CFString", FST_NSString)
2819 .Case("strftime", FST_Strftime)
2820 .Case("strfmon", FST_Strfmon)
2821 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002822 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002823 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002824 .Default(FST_Unknown);
2825}
2826
Jordan Rose3e0ec582012-07-19 18:10:23 +00002827/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002828/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002829/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002830bool Sema::CheckFormatArguments(const FormatAttr *Format,
2831 ArrayRef<const Expr *> Args,
2832 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002833 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002834 SourceLocation Loc, SourceRange Range,
2835 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002836 FormatStringInfo FSI;
2837 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002838 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002839 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002840 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002841 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002842}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002843
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002844bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002845 bool HasVAListArg, unsigned format_idx,
2846 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002847 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002848 SourceLocation Loc, SourceRange Range,
2849 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002850 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002851 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002852 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002853 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002854 }
Mike Stump11289f42009-09-09 15:08:12 +00002855
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002856 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002857
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002858 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002859 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002860 // Dynamically generated format strings are difficult to
2861 // automatically vet at compile time. Requiring that format strings
2862 // are string literals: (1) permits the checking of format strings by
2863 // the compiler and thereby (2) can practically remove the source of
2864 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002865
Mike Stump11289f42009-09-09 15:08:12 +00002866 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002867 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002868 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002869 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002870 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002871 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2872 format_idx, firstDataArg, Type, CallType,
2873 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002874 if (CT != SLCT_NotALiteral)
2875 // Literal format string found, check done!
2876 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002877
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002878 // Strftime is particular as it always uses a single 'time' argument,
2879 // so it is safe to pass a non-literal string.
2880 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002881 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002882
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002883 // Do not emit diag when the string param is a macro expansion and the
2884 // format is either NSString or CFString. This is a hack to prevent
2885 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2886 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002887 if (Type == FST_NSString &&
2888 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002889 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002890
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002891 // If there are no arguments specified, warn with -Wformat-security, otherwise
2892 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002893 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002894 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002895 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002896 << OrigFormatExpr->getSourceRange();
2897 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002898 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002899 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002900 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002901 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002902}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002903
Ted Kremenekab278de2010-01-28 23:39:18 +00002904namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002905class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2906protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002907 Sema &S;
2908 const StringLiteral *FExpr;
2909 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002910 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002911 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002912 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002913 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002914 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002915 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002916 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002917 bool usesPositionalArgs;
2918 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002919 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002920 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002921 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002922public:
Ted Kremenek02087932010-07-16 02:11:22 +00002923 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002924 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002925 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002926 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002927 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002928 Sema::VariadicCallType callType,
2929 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002930 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002931 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2932 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002933 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002934 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002935 inFunctionCall(inFunctionCall), CallType(callType),
2936 CheckedVarArgs(CheckedVarArgs) {
2937 CoveredArgs.resize(numDataArgs);
2938 CoveredArgs.reset();
2939 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002940
Ted Kremenek019d2242010-01-29 01:50:07 +00002941 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002942
Ted Kremenek02087932010-07-16 02:11:22 +00002943 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002944 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002945
Jordan Rose92303592012-09-08 04:00:03 +00002946 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002947 const analyze_format_string::FormatSpecifier &FS,
2948 const analyze_format_string::ConversionSpecifier &CS,
2949 const char *startSpecifier, unsigned specifierLen,
2950 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002951
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002952 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002953 const analyze_format_string::FormatSpecifier &FS,
2954 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002955
2956 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002957 const analyze_format_string::ConversionSpecifier &CS,
2958 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002959
Craig Toppere14c0f82014-03-12 04:55:44 +00002960 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002961
Craig Toppere14c0f82014-03-12 04:55:44 +00002962 void HandleInvalidPosition(const char *startSpecifier,
2963 unsigned specifierLen,
2964 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002965
Craig Toppere14c0f82014-03-12 04:55:44 +00002966 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002967
Craig Toppere14c0f82014-03-12 04:55:44 +00002968 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002969
Richard Trieu03cf7b72011-10-28 00:41:25 +00002970 template <typename Range>
2971 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2972 const Expr *ArgumentExpr,
2973 PartialDiagnostic PDiag,
2974 SourceLocation StringLoc,
2975 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002976 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002977
Ted Kremenek02087932010-07-16 02:11:22 +00002978protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002979 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2980 const char *startSpec,
2981 unsigned specifierLen,
2982 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002983
2984 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2985 const char *startSpec,
2986 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002987
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002988 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002989 CharSourceRange getSpecifierRange(const char *startSpecifier,
2990 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002991 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002992
Ted Kremenek5739de72010-01-29 01:06:55 +00002993 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002994
2995 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2996 const analyze_format_string::ConversionSpecifier &CS,
2997 const char *startSpecifier, unsigned specifierLen,
2998 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002999
3000 template <typename Range>
3001 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3002 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003003 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003004};
3005}
3006
Ted Kremenek02087932010-07-16 02:11:22 +00003007SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003008 return OrigFormatExpr->getSourceRange();
3009}
3010
Ted Kremenek02087932010-07-16 02:11:22 +00003011CharSourceRange CheckFormatHandler::
3012getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003013 SourceLocation Start = getLocationOfByte(startSpecifier);
3014 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3015
3016 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003017 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003018
3019 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003020}
3021
Ted Kremenek02087932010-07-16 02:11:22 +00003022SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003023 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003024}
3025
Ted Kremenek02087932010-07-16 02:11:22 +00003026void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3027 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003028 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3029 getLocationOfByte(startSpecifier),
3030 /*IsStringLocation*/true,
3031 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003032}
3033
Jordan Rose92303592012-09-08 04:00:03 +00003034void CheckFormatHandler::HandleInvalidLengthModifier(
3035 const analyze_format_string::FormatSpecifier &FS,
3036 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003037 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003038 using namespace analyze_format_string;
3039
3040 const LengthModifier &LM = FS.getLengthModifier();
3041 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3042
3043 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003044 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003045 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003046 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003047 getLocationOfByte(LM.getStart()),
3048 /*IsStringLocation*/true,
3049 getSpecifierRange(startSpecifier, specifierLen));
3050
3051 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3052 << FixedLM->toString()
3053 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3054
3055 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003056 FixItHint Hint;
3057 if (DiagID == diag::warn_format_nonsensical_length)
3058 Hint = FixItHint::CreateRemoval(LMRange);
3059
3060 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003061 getLocationOfByte(LM.getStart()),
3062 /*IsStringLocation*/true,
3063 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003064 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003065 }
3066}
3067
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003068void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003069 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003070 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003071 using namespace analyze_format_string;
3072
3073 const LengthModifier &LM = FS.getLengthModifier();
3074 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3075
3076 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003077 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003078 if (FixedLM) {
3079 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3080 << LM.toString() << 0,
3081 getLocationOfByte(LM.getStart()),
3082 /*IsStringLocation*/true,
3083 getSpecifierRange(startSpecifier, specifierLen));
3084
3085 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3086 << FixedLM->toString()
3087 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3088
3089 } else {
3090 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3091 << LM.toString() << 0,
3092 getLocationOfByte(LM.getStart()),
3093 /*IsStringLocation*/true,
3094 getSpecifierRange(startSpecifier, specifierLen));
3095 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003096}
3097
3098void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3099 const analyze_format_string::ConversionSpecifier &CS,
3100 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003101 using namespace analyze_format_string;
3102
3103 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003104 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003105 if (FixedCS) {
3106 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3107 << CS.toString() << /*conversion specifier*/1,
3108 getLocationOfByte(CS.getStart()),
3109 /*IsStringLocation*/true,
3110 getSpecifierRange(startSpecifier, specifierLen));
3111
3112 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3113 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3114 << FixedCS->toString()
3115 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3116 } else {
3117 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3118 << CS.toString() << /*conversion specifier*/1,
3119 getLocationOfByte(CS.getStart()),
3120 /*IsStringLocation*/true,
3121 getSpecifierRange(startSpecifier, specifierLen));
3122 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003123}
3124
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003125void CheckFormatHandler::HandlePosition(const char *startPos,
3126 unsigned posLen) {
3127 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3128 getLocationOfByte(startPos),
3129 /*IsStringLocation*/true,
3130 getSpecifierRange(startPos, posLen));
3131}
3132
Ted Kremenekd1668192010-02-27 01:41:03 +00003133void
Ted Kremenek02087932010-07-16 02:11:22 +00003134CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3135 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003136 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3137 << (unsigned) p,
3138 getLocationOfByte(startPos), /*IsStringLocation*/true,
3139 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003140}
3141
Ted Kremenek02087932010-07-16 02:11:22 +00003142void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003143 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003144 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3145 getLocationOfByte(startPos),
3146 /*IsStringLocation*/true,
3147 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003148}
3149
Ted Kremenek02087932010-07-16 02:11:22 +00003150void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003151 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003152 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003153 EmitFormatDiagnostic(
3154 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3155 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3156 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003157 }
Ted Kremenek02087932010-07-16 02:11:22 +00003158}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003159
Jordan Rose58bbe422012-07-19 18:10:08 +00003160// Note that this may return NULL if there was an error parsing or building
3161// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003162const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003163 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003164}
3165
3166void CheckFormatHandler::DoneProcessing() {
3167 // Does the number of data arguments exceed the number of
3168 // format conversions in the format string?
3169 if (!HasVAListArg) {
3170 // Find any arguments that weren't covered.
3171 CoveredArgs.flip();
3172 signed notCoveredArg = CoveredArgs.find_first();
3173 if (notCoveredArg >= 0) {
3174 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003175 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3176 SourceLocation Loc = E->getLocStart();
3177 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3178 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3179 Loc, /*IsStringLocation*/false,
3180 getFormatStringRange());
3181 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003182 }
Ted Kremenek02087932010-07-16 02:11:22 +00003183 }
3184 }
3185}
3186
Ted Kremenekce815422010-07-19 21:25:57 +00003187bool
3188CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3189 SourceLocation Loc,
3190 const char *startSpec,
3191 unsigned specifierLen,
3192 const char *csStart,
3193 unsigned csLen) {
3194
3195 bool keepGoing = true;
3196 if (argIndex < NumDataArgs) {
3197 // Consider the argument coverered, even though the specifier doesn't
3198 // make sense.
3199 CoveredArgs.set(argIndex);
3200 }
3201 else {
3202 // If argIndex exceeds the number of data arguments we
3203 // don't issue a warning because that is just a cascade of warnings (and
3204 // they may have intended '%%' anyway). We don't want to continue processing
3205 // the format string after this point, however, as we will like just get
3206 // gibberish when trying to match arguments.
3207 keepGoing = false;
3208 }
3209
Richard Trieu03cf7b72011-10-28 00:41:25 +00003210 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3211 << StringRef(csStart, csLen),
3212 Loc, /*IsStringLocation*/true,
3213 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003214
3215 return keepGoing;
3216}
3217
Richard Trieu03cf7b72011-10-28 00:41:25 +00003218void
3219CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3220 const char *startSpec,
3221 unsigned specifierLen) {
3222 EmitFormatDiagnostic(
3223 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3224 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3225}
3226
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003227bool
3228CheckFormatHandler::CheckNumArgs(
3229 const analyze_format_string::FormatSpecifier &FS,
3230 const analyze_format_string::ConversionSpecifier &CS,
3231 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3232
3233 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003234 PartialDiagnostic PDiag = FS.usesPositionalArg()
3235 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3236 << (argIndex+1) << NumDataArgs)
3237 : S.PDiag(diag::warn_printf_insufficient_data_args);
3238 EmitFormatDiagnostic(
3239 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3240 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003241 return false;
3242 }
3243 return true;
3244}
3245
Richard Trieu03cf7b72011-10-28 00:41:25 +00003246template<typename Range>
3247void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3248 SourceLocation Loc,
3249 bool IsStringLocation,
3250 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003251 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003252 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003253 Loc, IsStringLocation, StringRange, FixIt);
3254}
3255
3256/// \brief If the format string is not within the funcion call, emit a note
3257/// so that the function call and string are in diagnostic messages.
3258///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003259/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003260/// call and only one diagnostic message will be produced. Otherwise, an
3261/// extra note will be emitted pointing to location of the format string.
3262///
3263/// \param ArgumentExpr the expression that is passed as the format string
3264/// argument in the function call. Used for getting locations when two
3265/// diagnostics are emitted.
3266///
3267/// \param PDiag the callee should already have provided any strings for the
3268/// diagnostic message. This function only adds locations and fixits
3269/// to diagnostics.
3270///
3271/// \param Loc primary location for diagnostic. If two diagnostics are
3272/// required, one will be at Loc and a new SourceLocation will be created for
3273/// the other one.
3274///
3275/// \param IsStringLocation if true, Loc points to the format string should be
3276/// used for the note. Otherwise, Loc points to the argument list and will
3277/// be used with PDiag.
3278///
3279/// \param StringRange some or all of the string to highlight. This is
3280/// templated so it can accept either a CharSourceRange or a SourceRange.
3281///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003282/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003283template<typename Range>
3284void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3285 const Expr *ArgumentExpr,
3286 PartialDiagnostic PDiag,
3287 SourceLocation Loc,
3288 bool IsStringLocation,
3289 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003290 ArrayRef<FixItHint> FixIt) {
3291 if (InFunctionCall) {
3292 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3293 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003294 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003295 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003296 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3297 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003298
3299 const Sema::SemaDiagnosticBuilder &Note =
3300 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3301 diag::note_format_string_defined);
3302
3303 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003304 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003305 }
3306}
3307
Ted Kremenek02087932010-07-16 02:11:22 +00003308//===--- CHECK: Printf format string checking ------------------------------===//
3309
3310namespace {
3311class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003312 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003313public:
3314 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3315 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003316 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003317 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003318 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003319 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003320 Sema::VariadicCallType CallType,
3321 llvm::SmallBitVector &CheckedVarArgs)
3322 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3323 numDataArgs, beg, hasVAListArg, Args,
3324 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3325 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003326 {}
3327
Craig Toppere14c0f82014-03-12 04:55:44 +00003328
Ted Kremenek02087932010-07-16 02:11:22 +00003329 bool HandleInvalidPrintfConversionSpecifier(
3330 const analyze_printf::PrintfSpecifier &FS,
3331 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003332 unsigned specifierLen) override;
3333
Ted Kremenek02087932010-07-16 02:11:22 +00003334 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3335 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003336 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003337 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3338 const char *StartSpecifier,
3339 unsigned SpecifierLen,
3340 const Expr *E);
3341
Ted Kremenek02087932010-07-16 02:11:22 +00003342 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3343 const char *startSpecifier, unsigned specifierLen);
3344 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3345 const analyze_printf::OptionalAmount &Amt,
3346 unsigned type,
3347 const char *startSpecifier, unsigned specifierLen);
3348 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3349 const analyze_printf::OptionalFlag &flag,
3350 const char *startSpecifier, unsigned specifierLen);
3351 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3352 const analyze_printf::OptionalFlag &ignoredFlag,
3353 const analyze_printf::OptionalFlag &flag,
3354 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003355 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003356 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003357
Ted Kremenek02087932010-07-16 02:11:22 +00003358};
3359}
3360
3361bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3362 const analyze_printf::PrintfSpecifier &FS,
3363 const char *startSpecifier,
3364 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003365 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003366 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003367
Ted Kremenekce815422010-07-19 21:25:57 +00003368 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3369 getLocationOfByte(CS.getStart()),
3370 startSpecifier, specifierLen,
3371 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003372}
3373
Ted Kremenek02087932010-07-16 02:11:22 +00003374bool CheckPrintfHandler::HandleAmount(
3375 const analyze_format_string::OptionalAmount &Amt,
3376 unsigned k, const char *startSpecifier,
3377 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003378
3379 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003380 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003381 unsigned argIndex = Amt.getArgIndex();
3382 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003383 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3384 << k,
3385 getLocationOfByte(Amt.getStart()),
3386 /*IsStringLocation*/true,
3387 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003388 // Don't do any more checking. We will just emit
3389 // spurious errors.
3390 return false;
3391 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003392
Ted Kremenek5739de72010-01-29 01:06:55 +00003393 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003394 // Although not in conformance with C99, we also allow the argument to be
3395 // an 'unsigned int' as that is a reasonably safe case. GCC also
3396 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003397 CoveredArgs.set(argIndex);
3398 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003399 if (!Arg)
3400 return false;
3401
Ted Kremenek5739de72010-01-29 01:06:55 +00003402 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003403
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003404 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3405 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003406
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003407 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003408 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003409 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003410 << T << Arg->getSourceRange(),
3411 getLocationOfByte(Amt.getStart()),
3412 /*IsStringLocation*/true,
3413 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003414 // Don't do any more checking. We will just emit
3415 // spurious errors.
3416 return false;
3417 }
3418 }
3419 }
3420 return true;
3421}
Ted Kremenek5739de72010-01-29 01:06:55 +00003422
Tom Careb49ec692010-06-17 19:00:27 +00003423void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003424 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003425 const analyze_printf::OptionalAmount &Amt,
3426 unsigned type,
3427 const char *startSpecifier,
3428 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003429 const analyze_printf::PrintfConversionSpecifier &CS =
3430 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003431
Richard Trieu03cf7b72011-10-28 00:41:25 +00003432 FixItHint fixit =
3433 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3434 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3435 Amt.getConstantLength()))
3436 : FixItHint();
3437
3438 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3439 << type << CS.toString(),
3440 getLocationOfByte(Amt.getStart()),
3441 /*IsStringLocation*/true,
3442 getSpecifierRange(startSpecifier, specifierLen),
3443 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003444}
3445
Ted Kremenek02087932010-07-16 02:11:22 +00003446void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003447 const analyze_printf::OptionalFlag &flag,
3448 const char *startSpecifier,
3449 unsigned specifierLen) {
3450 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003451 const analyze_printf::PrintfConversionSpecifier &CS =
3452 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003453 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3454 << flag.toString() << CS.toString(),
3455 getLocationOfByte(flag.getPosition()),
3456 /*IsStringLocation*/true,
3457 getSpecifierRange(startSpecifier, specifierLen),
3458 FixItHint::CreateRemoval(
3459 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003460}
3461
3462void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003463 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003464 const analyze_printf::OptionalFlag &ignoredFlag,
3465 const analyze_printf::OptionalFlag &flag,
3466 const char *startSpecifier,
3467 unsigned specifierLen) {
3468 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003469 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3470 << ignoredFlag.toString() << flag.toString(),
3471 getLocationOfByte(ignoredFlag.getPosition()),
3472 /*IsStringLocation*/true,
3473 getSpecifierRange(startSpecifier, specifierLen),
3474 FixItHint::CreateRemoval(
3475 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003476}
3477
Richard Smith55ce3522012-06-25 20:30:08 +00003478// Determines if the specified is a C++ class or struct containing
3479// a member with the specified name and kind (e.g. a CXXMethodDecl named
3480// "c_str()").
3481template<typename MemberKind>
3482static llvm::SmallPtrSet<MemberKind*, 1>
3483CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3484 const RecordType *RT = Ty->getAs<RecordType>();
3485 llvm::SmallPtrSet<MemberKind*, 1> Results;
3486
3487 if (!RT)
3488 return Results;
3489 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003490 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003491 return Results;
3492
Alp Tokerb6cc5922014-05-03 03:45:55 +00003493 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003494 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003495 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003496
3497 // We just need to include all members of the right kind turned up by the
3498 // filter, at this point.
3499 if (S.LookupQualifiedName(R, RT->getDecl()))
3500 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3501 NamedDecl *decl = (*I)->getUnderlyingDecl();
3502 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3503 Results.insert(FK);
3504 }
3505 return Results;
3506}
3507
Richard Smith2868a732014-02-28 01:36:39 +00003508/// Check if we could call '.c_str()' on an object.
3509///
3510/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3511/// allow the call, or if it would be ambiguous).
3512bool Sema::hasCStrMethod(const Expr *E) {
3513 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3514 MethodSet Results =
3515 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3516 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3517 MI != ME; ++MI)
3518 if ((*MI)->getMinRequiredArguments() == 0)
3519 return true;
3520 return false;
3521}
3522
Richard Smith55ce3522012-06-25 20:30:08 +00003523// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003524// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003525// Returns true when a c_str() conversion method is found.
3526bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003527 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003528 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3529
3530 MethodSet Results =
3531 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3532
3533 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3534 MI != ME; ++MI) {
3535 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003536 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003537 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003538 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003539 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003540 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3541 << "c_str()"
3542 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3543 return true;
3544 }
3545 }
3546
3547 return false;
3548}
3549
Ted Kremenekab278de2010-01-28 23:39:18 +00003550bool
Ted Kremenek02087932010-07-16 02:11:22 +00003551CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003552 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003553 const char *startSpecifier,
3554 unsigned specifierLen) {
3555
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003556 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003557 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003558 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003559
Ted Kremenek6cd69422010-07-19 22:01:06 +00003560 if (FS.consumesDataArgument()) {
3561 if (atFirstArg) {
3562 atFirstArg = false;
3563 usesPositionalArgs = FS.usesPositionalArg();
3564 }
3565 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003566 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3567 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003568 return false;
3569 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003570 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003571
Ted Kremenekd1668192010-02-27 01:41:03 +00003572 // First check if the field width, precision, and conversion specifier
3573 // have matching data arguments.
3574 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3575 startSpecifier, specifierLen)) {
3576 return false;
3577 }
3578
3579 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3580 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003581 return false;
3582 }
3583
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003584 if (!CS.consumesDataArgument()) {
3585 // FIXME: Technically specifying a precision or field width here
3586 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003587 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003588 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003589
Ted Kremenek4a49d982010-02-26 19:18:41 +00003590 // Consume the argument.
3591 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003592 if (argIndex < NumDataArgs) {
3593 // The check to see if the argIndex is valid will come later.
3594 // We set the bit here because we may exit early from this
3595 // function if we encounter some other error.
3596 CoveredArgs.set(argIndex);
3597 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003598
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003599 // FreeBSD kernel extensions.
3600 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3601 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3602 // We need at least two arguments.
3603 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3604 return false;
3605
3606 // Claim the second argument.
3607 CoveredArgs.set(argIndex + 1);
3608
3609 // Type check the first argument (int for %b, pointer for %D)
3610 const Expr *Ex = getDataArg(argIndex);
3611 const analyze_printf::ArgType &AT =
3612 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3613 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3614 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3615 EmitFormatDiagnostic(
3616 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3617 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3618 << false << Ex->getSourceRange(),
3619 Ex->getLocStart(), /*IsStringLocation*/false,
3620 getSpecifierRange(startSpecifier, specifierLen));
3621
3622 // Type check the second argument (char * for both %b and %D)
3623 Ex = getDataArg(argIndex + 1);
3624 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3625 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3626 EmitFormatDiagnostic(
3627 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3628 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3629 << false << Ex->getSourceRange(),
3630 Ex->getLocStart(), /*IsStringLocation*/false,
3631 getSpecifierRange(startSpecifier, specifierLen));
3632
3633 return true;
3634 }
3635
Ted Kremenek4a49d982010-02-26 19:18:41 +00003636 // Check for using an Objective-C specific conversion specifier
3637 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003638 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003639 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3640 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003641 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003642
Tom Careb49ec692010-06-17 19:00:27 +00003643 // Check for invalid use of field width
3644 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003645 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003646 startSpecifier, specifierLen);
3647 }
3648
3649 // Check for invalid use of precision
3650 if (!FS.hasValidPrecision()) {
3651 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3652 startSpecifier, specifierLen);
3653 }
3654
3655 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003656 if (!FS.hasValidThousandsGroupingPrefix())
3657 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003658 if (!FS.hasValidLeadingZeros())
3659 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3660 if (!FS.hasValidPlusPrefix())
3661 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003662 if (!FS.hasValidSpacePrefix())
3663 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003664 if (!FS.hasValidAlternativeForm())
3665 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3666 if (!FS.hasValidLeftJustified())
3667 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3668
3669 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003670 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3671 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3672 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003673 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3674 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3675 startSpecifier, specifierLen);
3676
3677 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003678 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003679 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3680 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003681 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003682 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003683 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003684 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3685 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003686
Jordan Rose92303592012-09-08 04:00:03 +00003687 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3688 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3689
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003690 // The remaining checks depend on the data arguments.
3691 if (HasVAListArg)
3692 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003693
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003694 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003695 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003696
Jordan Rose58bbe422012-07-19 18:10:08 +00003697 const Expr *Arg = getDataArg(argIndex);
3698 if (!Arg)
3699 return true;
3700
3701 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003702}
3703
Jordan Roseaee34382012-09-05 22:56:26 +00003704static bool requiresParensToAddCast(const Expr *E) {
3705 // FIXME: We should have a general way to reason about operator
3706 // precedence and whether parens are actually needed here.
3707 // Take care of a few common cases where they aren't.
3708 const Expr *Inside = E->IgnoreImpCasts();
3709 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3710 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3711
3712 switch (Inside->getStmtClass()) {
3713 case Stmt::ArraySubscriptExprClass:
3714 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003715 case Stmt::CharacterLiteralClass:
3716 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003717 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003718 case Stmt::FloatingLiteralClass:
3719 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003720 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003721 case Stmt::ObjCArrayLiteralClass:
3722 case Stmt::ObjCBoolLiteralExprClass:
3723 case Stmt::ObjCBoxedExprClass:
3724 case Stmt::ObjCDictionaryLiteralClass:
3725 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003726 case Stmt::ObjCIvarRefExprClass:
3727 case Stmt::ObjCMessageExprClass:
3728 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003729 case Stmt::ObjCStringLiteralClass:
3730 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003731 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003732 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003733 case Stmt::UnaryOperatorClass:
3734 return false;
3735 default:
3736 return true;
3737 }
3738}
3739
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003740static std::pair<QualType, StringRef>
3741shouldNotPrintDirectly(const ASTContext &Context,
3742 QualType IntendedTy,
3743 const Expr *E) {
3744 // Use a 'while' to peel off layers of typedefs.
3745 QualType TyTy = IntendedTy;
3746 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3747 StringRef Name = UserTy->getDecl()->getName();
3748 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3749 .Case("NSInteger", Context.LongTy)
3750 .Case("NSUInteger", Context.UnsignedLongTy)
3751 .Case("SInt32", Context.IntTy)
3752 .Case("UInt32", Context.UnsignedIntTy)
3753 .Default(QualType());
3754
3755 if (!CastTy.isNull())
3756 return std::make_pair(CastTy, Name);
3757
3758 TyTy = UserTy->desugar();
3759 }
3760
3761 // Strip parens if necessary.
3762 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3763 return shouldNotPrintDirectly(Context,
3764 PE->getSubExpr()->getType(),
3765 PE->getSubExpr());
3766
3767 // If this is a conditional expression, then its result type is constructed
3768 // via usual arithmetic conversions and thus there might be no necessary
3769 // typedef sugar there. Recurse to operands to check for NSInteger &
3770 // Co. usage condition.
3771 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3772 QualType TrueTy, FalseTy;
3773 StringRef TrueName, FalseName;
3774
3775 std::tie(TrueTy, TrueName) =
3776 shouldNotPrintDirectly(Context,
3777 CO->getTrueExpr()->getType(),
3778 CO->getTrueExpr());
3779 std::tie(FalseTy, FalseName) =
3780 shouldNotPrintDirectly(Context,
3781 CO->getFalseExpr()->getType(),
3782 CO->getFalseExpr());
3783
3784 if (TrueTy == FalseTy)
3785 return std::make_pair(TrueTy, TrueName);
3786 else if (TrueTy.isNull())
3787 return std::make_pair(FalseTy, FalseName);
3788 else if (FalseTy.isNull())
3789 return std::make_pair(TrueTy, TrueName);
3790 }
3791
3792 return std::make_pair(QualType(), StringRef());
3793}
3794
Richard Smith55ce3522012-06-25 20:30:08 +00003795bool
3796CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3797 const char *StartSpecifier,
3798 unsigned SpecifierLen,
3799 const Expr *E) {
3800 using namespace analyze_format_string;
3801 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003802 // Now type check the data expression that matches the
3803 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003804 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3805 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003806 if (!AT.isValid())
3807 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003808
Jordan Rose598ec092012-12-05 18:44:40 +00003809 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003810 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3811 ExprTy = TET->getUnderlyingExpr()->getType();
3812 }
3813
Seth Cantrellb4802962015-03-04 03:12:10 +00003814 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3815
3816 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003817 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003818 }
Jordan Rose98709982012-06-04 22:48:57 +00003819
Jordan Rose22b74712012-09-05 22:56:19 +00003820 // Look through argument promotions for our error message's reported type.
3821 // This includes the integral and floating promotions, but excludes array
3822 // and function pointer decay; seeing that an argument intended to be a
3823 // string has type 'char [6]' is probably more confusing than 'char *'.
3824 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3825 if (ICE->getCastKind() == CK_IntegralCast ||
3826 ICE->getCastKind() == CK_FloatingCast) {
3827 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003828 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003829
3830 // Check if we didn't match because of an implicit cast from a 'char'
3831 // or 'short' to an 'int'. This is done because printf is a varargs
3832 // function.
3833 if (ICE->getType() == S.Context.IntTy ||
3834 ICE->getType() == S.Context.UnsignedIntTy) {
3835 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003836 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003837 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003838 }
Jordan Rose98709982012-06-04 22:48:57 +00003839 }
Jordan Rose598ec092012-12-05 18:44:40 +00003840 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3841 // Special case for 'a', which has type 'int' in C.
3842 // Note, however, that we do /not/ want to treat multibyte constants like
3843 // 'MooV' as characters! This form is deprecated but still exists.
3844 if (ExprTy == S.Context.IntTy)
3845 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3846 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003847 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003848
Jordan Rosebc53ed12014-05-31 04:12:14 +00003849 // Look through enums to their underlying type.
3850 bool IsEnum = false;
3851 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3852 ExprTy = EnumTy->getDecl()->getIntegerType();
3853 IsEnum = true;
3854 }
3855
Jordan Rose0e5badd2012-12-05 18:44:49 +00003856 // %C in an Objective-C context prints a unichar, not a wchar_t.
3857 // If the argument is an integer of some kind, believe the %C and suggest
3858 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003859 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003860 if (ObjCContext &&
3861 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3862 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3863 !ExprTy->isCharType()) {
3864 // 'unichar' is defined as a typedef of unsigned short, but we should
3865 // prefer using the typedef if it is visible.
3866 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003867
3868 // While we are here, check if the value is an IntegerLiteral that happens
3869 // to be within the valid range.
3870 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3871 const llvm::APInt &V = IL->getValue();
3872 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3873 return true;
3874 }
3875
Jordan Rose0e5badd2012-12-05 18:44:49 +00003876 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3877 Sema::LookupOrdinaryName);
3878 if (S.LookupName(Result, S.getCurScope())) {
3879 NamedDecl *ND = Result.getFoundDecl();
3880 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3881 if (TD->getUnderlyingType() == IntendedTy)
3882 IntendedTy = S.Context.getTypedefType(TD);
3883 }
3884 }
3885 }
3886
3887 // Special-case some of Darwin's platform-independence types by suggesting
3888 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003889 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003890 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003891 QualType CastTy;
3892 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3893 if (!CastTy.isNull()) {
3894 IntendedTy = CastTy;
3895 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003896 }
3897 }
3898
Jordan Rose22b74712012-09-05 22:56:19 +00003899 // We may be able to offer a FixItHint if it is a supported type.
3900 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003901 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003902 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003903
Jordan Rose22b74712012-09-05 22:56:19 +00003904 if (success) {
3905 // Get the fix string from the fixed format specifier
3906 SmallString<16> buf;
3907 llvm::raw_svector_ostream os(buf);
3908 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003909
Jordan Roseaee34382012-09-05 22:56:26 +00003910 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3911
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003912 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003913 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3914 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3915 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3916 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003917 // In this case, the specifier is wrong and should be changed to match
3918 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003919 EmitFormatDiagnostic(S.PDiag(diag)
3920 << AT.getRepresentativeTypeName(S.Context)
3921 << IntendedTy << IsEnum << E->getSourceRange(),
3922 E->getLocStart(),
3923 /*IsStringLocation*/ false, SpecRange,
3924 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003925
3926 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003927 // The canonical type for formatting this value is different from the
3928 // actual type of the expression. (This occurs, for example, with Darwin's
3929 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3930 // should be printed as 'long' for 64-bit compatibility.)
3931 // Rather than emitting a normal format/argument mismatch, we want to
3932 // add a cast to the recommended type (and correct the format string
3933 // if necessary).
3934 SmallString<16> CastBuf;
3935 llvm::raw_svector_ostream CastFix(CastBuf);
3936 CastFix << "(";
3937 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3938 CastFix << ")";
3939
3940 SmallVector<FixItHint,4> Hints;
3941 if (!AT.matchesType(S.Context, IntendedTy))
3942 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3943
3944 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3945 // If there's already a cast present, just replace it.
3946 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3947 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3948
3949 } else if (!requiresParensToAddCast(E)) {
3950 // If the expression has high enough precedence,
3951 // just write the C-style cast.
3952 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3953 CastFix.str()));
3954 } else {
3955 // Otherwise, add parens around the expression as well as the cast.
3956 CastFix << "(";
3957 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3958 CastFix.str()));
3959
Alp Tokerb6cc5922014-05-03 03:45:55 +00003960 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003961 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3962 }
3963
Jordan Rose0e5badd2012-12-05 18:44:49 +00003964 if (ShouldNotPrintDirectly) {
3965 // The expression has a type that should not be printed directly.
3966 // We extract the name from the typedef because we don't want to show
3967 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003968 StringRef Name;
3969 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3970 Name = TypedefTy->getDecl()->getName();
3971 else
3972 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003973 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003974 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003975 << E->getSourceRange(),
3976 E->getLocStart(), /*IsStringLocation=*/false,
3977 SpecRange, Hints);
3978 } else {
3979 // In this case, the expression could be printed using a different
3980 // specifier, but we've decided that the specifier is probably correct
3981 // and we should cast instead. Just use the normal warning message.
3982 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003983 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3984 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003985 << E->getSourceRange(),
3986 E->getLocStart(), /*IsStringLocation*/false,
3987 SpecRange, Hints);
3988 }
Jordan Roseaee34382012-09-05 22:56:26 +00003989 }
Jordan Rose22b74712012-09-05 22:56:19 +00003990 } else {
3991 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3992 SpecifierLen);
3993 // Since the warning for passing non-POD types to variadic functions
3994 // was deferred until now, we emit a warning for non-POD
3995 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003996 switch (S.isValidVarArgType(ExprTy)) {
3997 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003998 case Sema::VAK_ValidInCXX11: {
3999 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4000 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4001 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4002 }
Richard Smithd7293d72013-08-05 18:49:43 +00004003
Seth Cantrellb4802962015-03-04 03:12:10 +00004004 EmitFormatDiagnostic(
4005 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4006 << IsEnum << CSR << E->getSourceRange(),
4007 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4008 break;
4009 }
Richard Smithd7293d72013-08-05 18:49:43 +00004010 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004011 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004012 EmitFormatDiagnostic(
4013 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004014 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004015 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004016 << CallType
4017 << AT.getRepresentativeTypeName(S.Context)
4018 << CSR
4019 << E->getSourceRange(),
4020 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004021 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004022 break;
4023
4024 case Sema::VAK_Invalid:
4025 if (ExprTy->isObjCObjectType())
4026 EmitFormatDiagnostic(
4027 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4028 << S.getLangOpts().CPlusPlus11
4029 << ExprTy
4030 << CallType
4031 << AT.getRepresentativeTypeName(S.Context)
4032 << CSR
4033 << E->getSourceRange(),
4034 E->getLocStart(), /*IsStringLocation*/false, CSR);
4035 else
4036 // FIXME: If this is an initializer list, suggest removing the braces
4037 // or inserting a cast to the target type.
4038 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4039 << isa<InitListExpr>(E) << ExprTy << CallType
4040 << AT.getRepresentativeTypeName(S.Context)
4041 << E->getSourceRange();
4042 break;
4043 }
4044
4045 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4046 "format string specifier index out of range");
4047 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004048 }
4049
Ted Kremenekab278de2010-01-28 23:39:18 +00004050 return true;
4051}
4052
Ted Kremenek02087932010-07-16 02:11:22 +00004053//===--- CHECK: Scanf format string checking ------------------------------===//
4054
4055namespace {
4056class CheckScanfHandler : public CheckFormatHandler {
4057public:
4058 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4059 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004060 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004061 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004062 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004063 Sema::VariadicCallType CallType,
4064 llvm::SmallBitVector &CheckedVarArgs)
4065 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4066 numDataArgs, beg, hasVAListArg,
4067 Args, formatIdx, inFunctionCall, CallType,
4068 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004069 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004070
4071 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4072 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004073 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004074
4075 bool HandleInvalidScanfConversionSpecifier(
4076 const analyze_scanf::ScanfSpecifier &FS,
4077 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004078 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004079
Craig Toppere14c0f82014-03-12 04:55:44 +00004080 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004081};
Ted Kremenek019d2242010-01-29 01:50:07 +00004082}
Ted Kremenekab278de2010-01-28 23:39:18 +00004083
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004084void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4085 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004086 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4087 getLocationOfByte(end), /*IsStringLocation*/true,
4088 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004089}
4090
Ted Kremenekce815422010-07-19 21:25:57 +00004091bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4092 const analyze_scanf::ScanfSpecifier &FS,
4093 const char *startSpecifier,
4094 unsigned specifierLen) {
4095
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004096 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004097 FS.getConversionSpecifier();
4098
4099 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4100 getLocationOfByte(CS.getStart()),
4101 startSpecifier, specifierLen,
4102 CS.getStart(), CS.getLength());
4103}
4104
Ted Kremenek02087932010-07-16 02:11:22 +00004105bool CheckScanfHandler::HandleScanfSpecifier(
4106 const analyze_scanf::ScanfSpecifier &FS,
4107 const char *startSpecifier,
4108 unsigned specifierLen) {
4109
4110 using namespace analyze_scanf;
4111 using namespace analyze_format_string;
4112
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004113 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004114
Ted Kremenek6cd69422010-07-19 22:01:06 +00004115 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4116 // be used to decide if we are using positional arguments consistently.
4117 if (FS.consumesDataArgument()) {
4118 if (atFirstArg) {
4119 atFirstArg = false;
4120 usesPositionalArgs = FS.usesPositionalArg();
4121 }
4122 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004123 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4124 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004125 return false;
4126 }
Ted Kremenek02087932010-07-16 02:11:22 +00004127 }
4128
4129 // Check if the field with is non-zero.
4130 const OptionalAmount &Amt = FS.getFieldWidth();
4131 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4132 if (Amt.getConstantAmount() == 0) {
4133 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4134 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004135 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4136 getLocationOfByte(Amt.getStart()),
4137 /*IsStringLocation*/true, R,
4138 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004139 }
4140 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004141
Ted Kremenek02087932010-07-16 02:11:22 +00004142 if (!FS.consumesDataArgument()) {
4143 // FIXME: Technically specifying a precision or field width here
4144 // makes no sense. Worth issuing a warning at some point.
4145 return true;
4146 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004147
Ted Kremenek02087932010-07-16 02:11:22 +00004148 // Consume the argument.
4149 unsigned argIndex = FS.getArgIndex();
4150 if (argIndex < NumDataArgs) {
4151 // The check to see if the argIndex is valid will come later.
4152 // We set the bit here because we may exit early from this
4153 // function if we encounter some other error.
4154 CoveredArgs.set(argIndex);
4155 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004156
Ted Kremenek4407ea42010-07-20 20:04:47 +00004157 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004158 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004159 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4160 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004161 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004162 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004163 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004164 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4165 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004166
Jordan Rose92303592012-09-08 04:00:03 +00004167 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4168 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4169
Ted Kremenek02087932010-07-16 02:11:22 +00004170 // The remaining checks depend on the data arguments.
4171 if (HasVAListArg)
4172 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004173
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004174 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004175 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004176
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004177 // Check that the argument type matches the format specifier.
4178 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004179 if (!Ex)
4180 return true;
4181
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004182 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004183
4184 if (!AT.isValid()) {
4185 return true;
4186 }
4187
Seth Cantrellb4802962015-03-04 03:12:10 +00004188 analyze_format_string::ArgType::MatchKind match =
4189 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004190 if (match == analyze_format_string::ArgType::Match) {
4191 return true;
4192 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004193
Seth Cantrell79340072015-03-04 05:58:08 +00004194 ScanfSpecifier fixedFS = FS;
4195 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4196 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004197
Seth Cantrell79340072015-03-04 05:58:08 +00004198 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4199 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4200 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4201 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004202
Seth Cantrell79340072015-03-04 05:58:08 +00004203 if (success) {
4204 // Get the fix string from the fixed format specifier.
4205 SmallString<128> buf;
4206 llvm::raw_svector_ostream os(buf);
4207 fixedFS.toString(os);
4208
4209 EmitFormatDiagnostic(
4210 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4211 << Ex->getType() << false << Ex->getSourceRange(),
4212 Ex->getLocStart(),
4213 /*IsStringLocation*/ false,
4214 getSpecifierRange(startSpecifier, specifierLen),
4215 FixItHint::CreateReplacement(
4216 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4217 } else {
4218 EmitFormatDiagnostic(S.PDiag(diag)
4219 << AT.getRepresentativeTypeName(S.Context)
4220 << Ex->getType() << false << Ex->getSourceRange(),
4221 Ex->getLocStart(),
4222 /*IsStringLocation*/ false,
4223 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004224 }
4225
Ted Kremenek02087932010-07-16 02:11:22 +00004226 return true;
4227}
4228
4229void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004230 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004231 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004232 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004233 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004234 bool inFunctionCall, VariadicCallType CallType,
4235 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004236
Ted Kremenekab278de2010-01-28 23:39:18 +00004237 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004238 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004239 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004240 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004241 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4242 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004243 return;
4244 }
Ted Kremenek02087932010-07-16 02:11:22 +00004245
Ted Kremenekab278de2010-01-28 23:39:18 +00004246 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004247 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004248 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004249 // Account for cases where the string literal is truncated in a declaration.
4250 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4251 assert(T && "String literal not of constant array type!");
4252 size_t TypeSize = T->getSize().getZExtValue();
4253 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004254 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004255
4256 // Emit a warning if the string literal is truncated and does not contain an
4257 // embedded null character.
4258 if (TypeSize <= StrRef.size() &&
4259 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4260 CheckFormatHandler::EmitFormatDiagnostic(
4261 *this, inFunctionCall, Args[format_idx],
4262 PDiag(diag::warn_printf_format_string_not_null_terminated),
4263 FExpr->getLocStart(),
4264 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4265 return;
4266 }
4267
Ted Kremenekab278de2010-01-28 23:39:18 +00004268 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004269 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004270 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004271 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004272 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4273 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004274 return;
4275 }
Ted Kremenek02087932010-07-16 02:11:22 +00004276
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004277 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004278 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004279 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004280 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004281 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004282 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004283
Hans Wennborg23926bd2011-12-15 10:25:47 +00004284 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004285 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004286 Context.getTargetInfo(),
4287 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004288 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004289 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004290 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004291 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004292 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004293
Hans Wennborg23926bd2011-12-15 10:25:47 +00004294 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004295 getLangOpts(),
4296 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004297 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004298 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004299}
4300
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004301bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4302 // Str - The format string. NOTE: this is NOT null-terminated!
4303 StringRef StrRef = FExpr->getString();
4304 const char *Str = StrRef.data();
4305 // Account for cases where the string literal is truncated in a declaration.
4306 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4307 assert(T && "String literal not of constant array type!");
4308 size_t TypeSize = T->getSize().getZExtValue();
4309 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4310 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4311 getLangOpts(),
4312 Context.getTargetInfo());
4313}
4314
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004315//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4316
4317// Returns the related absolute value function that is larger, of 0 if one
4318// does not exist.
4319static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4320 switch (AbsFunction) {
4321 default:
4322 return 0;
4323
4324 case Builtin::BI__builtin_abs:
4325 return Builtin::BI__builtin_labs;
4326 case Builtin::BI__builtin_labs:
4327 return Builtin::BI__builtin_llabs;
4328 case Builtin::BI__builtin_llabs:
4329 return 0;
4330
4331 case Builtin::BI__builtin_fabsf:
4332 return Builtin::BI__builtin_fabs;
4333 case Builtin::BI__builtin_fabs:
4334 return Builtin::BI__builtin_fabsl;
4335 case Builtin::BI__builtin_fabsl:
4336 return 0;
4337
4338 case Builtin::BI__builtin_cabsf:
4339 return Builtin::BI__builtin_cabs;
4340 case Builtin::BI__builtin_cabs:
4341 return Builtin::BI__builtin_cabsl;
4342 case Builtin::BI__builtin_cabsl:
4343 return 0;
4344
4345 case Builtin::BIabs:
4346 return Builtin::BIlabs;
4347 case Builtin::BIlabs:
4348 return Builtin::BIllabs;
4349 case Builtin::BIllabs:
4350 return 0;
4351
4352 case Builtin::BIfabsf:
4353 return Builtin::BIfabs;
4354 case Builtin::BIfabs:
4355 return Builtin::BIfabsl;
4356 case Builtin::BIfabsl:
4357 return 0;
4358
4359 case Builtin::BIcabsf:
4360 return Builtin::BIcabs;
4361 case Builtin::BIcabs:
4362 return Builtin::BIcabsl;
4363 case Builtin::BIcabsl:
4364 return 0;
4365 }
4366}
4367
4368// Returns the argument type of the absolute value function.
4369static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4370 unsigned AbsType) {
4371 if (AbsType == 0)
4372 return QualType();
4373
4374 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4375 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4376 if (Error != ASTContext::GE_None)
4377 return QualType();
4378
4379 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4380 if (!FT)
4381 return QualType();
4382
4383 if (FT->getNumParams() != 1)
4384 return QualType();
4385
4386 return FT->getParamType(0);
4387}
4388
4389// Returns the best absolute value function, or zero, based on type and
4390// current absolute value function.
4391static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4392 unsigned AbsFunctionKind) {
4393 unsigned BestKind = 0;
4394 uint64_t ArgSize = Context.getTypeSize(ArgType);
4395 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4396 Kind = getLargerAbsoluteValueFunction(Kind)) {
4397 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4398 if (Context.getTypeSize(ParamType) >= ArgSize) {
4399 if (BestKind == 0)
4400 BestKind = Kind;
4401 else if (Context.hasSameType(ParamType, ArgType)) {
4402 BestKind = Kind;
4403 break;
4404 }
4405 }
4406 }
4407 return BestKind;
4408}
4409
4410enum AbsoluteValueKind {
4411 AVK_Integer,
4412 AVK_Floating,
4413 AVK_Complex
4414};
4415
4416static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4417 if (T->isIntegralOrEnumerationType())
4418 return AVK_Integer;
4419 if (T->isRealFloatingType())
4420 return AVK_Floating;
4421 if (T->isAnyComplexType())
4422 return AVK_Complex;
4423
4424 llvm_unreachable("Type not integer, floating, or complex");
4425}
4426
4427// Changes the absolute value function to a different type. Preserves whether
4428// the function is a builtin.
4429static unsigned changeAbsFunction(unsigned AbsKind,
4430 AbsoluteValueKind ValueKind) {
4431 switch (ValueKind) {
4432 case AVK_Integer:
4433 switch (AbsKind) {
4434 default:
4435 return 0;
4436 case Builtin::BI__builtin_fabsf:
4437 case Builtin::BI__builtin_fabs:
4438 case Builtin::BI__builtin_fabsl:
4439 case Builtin::BI__builtin_cabsf:
4440 case Builtin::BI__builtin_cabs:
4441 case Builtin::BI__builtin_cabsl:
4442 return Builtin::BI__builtin_abs;
4443 case Builtin::BIfabsf:
4444 case Builtin::BIfabs:
4445 case Builtin::BIfabsl:
4446 case Builtin::BIcabsf:
4447 case Builtin::BIcabs:
4448 case Builtin::BIcabsl:
4449 return Builtin::BIabs;
4450 }
4451 case AVK_Floating:
4452 switch (AbsKind) {
4453 default:
4454 return 0;
4455 case Builtin::BI__builtin_abs:
4456 case Builtin::BI__builtin_labs:
4457 case Builtin::BI__builtin_llabs:
4458 case Builtin::BI__builtin_cabsf:
4459 case Builtin::BI__builtin_cabs:
4460 case Builtin::BI__builtin_cabsl:
4461 return Builtin::BI__builtin_fabsf;
4462 case Builtin::BIabs:
4463 case Builtin::BIlabs:
4464 case Builtin::BIllabs:
4465 case Builtin::BIcabsf:
4466 case Builtin::BIcabs:
4467 case Builtin::BIcabsl:
4468 return Builtin::BIfabsf;
4469 }
4470 case AVK_Complex:
4471 switch (AbsKind) {
4472 default:
4473 return 0;
4474 case Builtin::BI__builtin_abs:
4475 case Builtin::BI__builtin_labs:
4476 case Builtin::BI__builtin_llabs:
4477 case Builtin::BI__builtin_fabsf:
4478 case Builtin::BI__builtin_fabs:
4479 case Builtin::BI__builtin_fabsl:
4480 return Builtin::BI__builtin_cabsf;
4481 case Builtin::BIabs:
4482 case Builtin::BIlabs:
4483 case Builtin::BIllabs:
4484 case Builtin::BIfabsf:
4485 case Builtin::BIfabs:
4486 case Builtin::BIfabsl:
4487 return Builtin::BIcabsf;
4488 }
4489 }
4490 llvm_unreachable("Unable to convert function");
4491}
4492
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004493static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004494 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4495 if (!FnInfo)
4496 return 0;
4497
4498 switch (FDecl->getBuiltinID()) {
4499 default:
4500 return 0;
4501 case Builtin::BI__builtin_abs:
4502 case Builtin::BI__builtin_fabs:
4503 case Builtin::BI__builtin_fabsf:
4504 case Builtin::BI__builtin_fabsl:
4505 case Builtin::BI__builtin_labs:
4506 case Builtin::BI__builtin_llabs:
4507 case Builtin::BI__builtin_cabs:
4508 case Builtin::BI__builtin_cabsf:
4509 case Builtin::BI__builtin_cabsl:
4510 case Builtin::BIabs:
4511 case Builtin::BIlabs:
4512 case Builtin::BIllabs:
4513 case Builtin::BIfabs:
4514 case Builtin::BIfabsf:
4515 case Builtin::BIfabsl:
4516 case Builtin::BIcabs:
4517 case Builtin::BIcabsf:
4518 case Builtin::BIcabsl:
4519 return FDecl->getBuiltinID();
4520 }
4521 llvm_unreachable("Unknown Builtin type");
4522}
4523
4524// If the replacement is valid, emit a note with replacement function.
4525// Additionally, suggest including the proper header if not already included.
4526static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004527 unsigned AbsKind, QualType ArgType) {
4528 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004529 const char *HeaderName = nullptr;
4530 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004531 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4532 FunctionName = "std::abs";
4533 if (ArgType->isIntegralOrEnumerationType()) {
4534 HeaderName = "cstdlib";
4535 } else if (ArgType->isRealFloatingType()) {
4536 HeaderName = "cmath";
4537 } else {
4538 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004539 }
Richard Trieubeffb832014-04-15 23:47:53 +00004540
4541 // Lookup all std::abs
4542 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004543 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004544 R.suppressDiagnostics();
4545 S.LookupQualifiedName(R, Std);
4546
4547 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004548 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004549 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4550 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4551 } else {
4552 FDecl = dyn_cast<FunctionDecl>(I);
4553 }
4554 if (!FDecl)
4555 continue;
4556
4557 // Found std::abs(), check that they are the right ones.
4558 if (FDecl->getNumParams() != 1)
4559 continue;
4560
4561 // Check that the parameter type can handle the argument.
4562 QualType ParamType = FDecl->getParamDecl(0)->getType();
4563 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4564 S.Context.getTypeSize(ArgType) <=
4565 S.Context.getTypeSize(ParamType)) {
4566 // Found a function, don't need the header hint.
4567 EmitHeaderHint = false;
4568 break;
4569 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004570 }
Richard Trieubeffb832014-04-15 23:47:53 +00004571 }
4572 } else {
4573 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4574 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4575
4576 if (HeaderName) {
4577 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4578 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4579 R.suppressDiagnostics();
4580 S.LookupName(R, S.getCurScope());
4581
4582 if (R.isSingleResult()) {
4583 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4584 if (FD && FD->getBuiltinID() == AbsKind) {
4585 EmitHeaderHint = false;
4586 } else {
4587 return;
4588 }
4589 } else if (!R.empty()) {
4590 return;
4591 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004592 }
4593 }
4594
4595 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004596 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004597
Richard Trieubeffb832014-04-15 23:47:53 +00004598 if (!HeaderName)
4599 return;
4600
4601 if (!EmitHeaderHint)
4602 return;
4603
Alp Toker5d96e0a2014-07-11 20:53:51 +00004604 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4605 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004606}
4607
4608static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4609 if (!FDecl)
4610 return false;
4611
4612 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4613 return false;
4614
4615 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4616
4617 while (ND && ND->isInlineNamespace()) {
4618 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004619 }
Richard Trieubeffb832014-04-15 23:47:53 +00004620
4621 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4622 return false;
4623
4624 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4625 return false;
4626
4627 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004628}
4629
4630// Warn when using the wrong abs() function.
4631void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4632 const FunctionDecl *FDecl,
4633 IdentifierInfo *FnInfo) {
4634 if (Call->getNumArgs() != 1)
4635 return;
4636
4637 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004638 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4639 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004640 return;
4641
4642 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4643 QualType ParamType = Call->getArg(0)->getType();
4644
Alp Toker5d96e0a2014-07-11 20:53:51 +00004645 // Unsigned types cannot be negative. Suggest removing the absolute value
4646 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004647 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004648 const char *FunctionName =
4649 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004650 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4651 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004652 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004653 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4654 return;
4655 }
4656
Richard Trieubeffb832014-04-15 23:47:53 +00004657 // std::abs has overloads which prevent most of the absolute value problems
4658 // from occurring.
4659 if (IsStdAbs)
4660 return;
4661
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004662 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4663 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4664
4665 // The argument and parameter are the same kind. Check if they are the right
4666 // size.
4667 if (ArgValueKind == ParamValueKind) {
4668 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4669 return;
4670
4671 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4672 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4673 << FDecl << ArgType << ParamType;
4674
4675 if (NewAbsKind == 0)
4676 return;
4677
4678 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004679 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004680 return;
4681 }
4682
4683 // ArgValueKind != ParamValueKind
4684 // The wrong type of absolute value function was used. Attempt to find the
4685 // proper one.
4686 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4687 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4688 if (NewAbsKind == 0)
4689 return;
4690
4691 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4692 << FDecl << ParamValueKind << ArgValueKind;
4693
4694 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004695 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004696 return;
4697}
4698
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004699//===--- CHECK: Standard memory functions ---------------------------------===//
4700
Nico Weber0e6daef2013-12-26 23:38:39 +00004701/// \brief Takes the expression passed to the size_t parameter of functions
4702/// such as memcmp, strncat, etc and warns if it's a comparison.
4703///
4704/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4705static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4706 IdentifierInfo *FnName,
4707 SourceLocation FnLoc,
4708 SourceLocation RParenLoc) {
4709 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4710 if (!Size)
4711 return false;
4712
4713 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4714 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4715 return false;
4716
Nico Weber0e6daef2013-12-26 23:38:39 +00004717 SourceRange SizeRange = Size->getSourceRange();
4718 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4719 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004720 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004721 << FnName << FixItHint::CreateInsertion(
4722 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004723 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004724 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004725 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004726 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4727 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004728
4729 return true;
4730}
4731
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004732/// \brief Determine whether the given type is or contains a dynamic class type
4733/// (e.g., whether it has a vtable).
4734static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4735 bool &IsContained) {
4736 // Look through array types while ignoring qualifiers.
4737 const Type *Ty = T->getBaseElementTypeUnsafe();
4738 IsContained = false;
4739
4740 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4741 RD = RD ? RD->getDefinition() : nullptr;
4742 if (!RD)
4743 return nullptr;
4744
4745 if (RD->isDynamicClass())
4746 return RD;
4747
4748 // Check all the fields. If any bases were dynamic, the class is dynamic.
4749 // It's impossible for a class to transitively contain itself by value, so
4750 // infinite recursion is impossible.
4751 for (auto *FD : RD->fields()) {
4752 bool SubContained;
4753 if (const CXXRecordDecl *ContainedRD =
4754 getContainedDynamicClass(FD->getType(), SubContained)) {
4755 IsContained = true;
4756 return ContainedRD;
4757 }
4758 }
4759
4760 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004761}
4762
Chandler Carruth889ed862011-06-21 23:04:20 +00004763/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004764/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00004765static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004766 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004767 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4768 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4769 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004770
Craig Topperc3ec1492014-05-26 06:22:03 +00004771 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004772}
4773
Chandler Carruth889ed862011-06-21 23:04:20 +00004774/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00004775static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004776 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4777 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4778 if (SizeOf->getKind() == clang::UETT_SizeOf)
4779 return SizeOf->getTypeOfArgument();
4780
4781 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004782}
4783
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004784/// \brief Check for dangerous or invalid arguments to memset().
4785///
Chandler Carruthac687262011-06-03 06:23:57 +00004786/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004787/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4788/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004789///
4790/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004791void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004792 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004793 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004794 assert(BId != 0);
4795
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004796 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004797 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004798 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004799 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004800 return;
4801
Anna Zaks22122702012-01-17 00:37:07 +00004802 unsigned LastArg = (BId == Builtin::BImemset ||
4803 BId == Builtin::BIstrndup ? 1 : 2);
4804 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004805 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004806
Nico Weber0e6daef2013-12-26 23:38:39 +00004807 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4808 Call->getLocStart(), Call->getRParenLoc()))
4809 return;
4810
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004811 // We have special checking when the length is a sizeof expression.
4812 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4813 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4814 llvm::FoldingSetNodeID SizeOfArgID;
4815
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004816 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4817 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004818 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004819
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004820 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00004821 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004822 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00004823 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004824
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004825 // Never warn about void type pointers. This can be used to suppress
4826 // false positives.
4827 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004828 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004829
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004830 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4831 // actually comparing the expressions for equality. Because computing the
4832 // expression IDs can be expensive, we only do this if the diagnostic is
4833 // enabled.
4834 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004835 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4836 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004837 // We only compute IDs for expressions if the warning is enabled, and
4838 // cache the sizeof arg's ID.
4839 if (SizeOfArgID == llvm::FoldingSetNodeID())
4840 SizeOfArg->Profile(SizeOfArgID, Context, true);
4841 llvm::FoldingSetNodeID DestID;
4842 Dest->Profile(DestID, Context, true);
4843 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004844 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4845 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004846 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004847 StringRef ReadableName = FnName->getName();
4848
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004849 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004850 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004851 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004852 if (!PointeeTy->isIncompleteType() &&
4853 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004854 ActionIdx = 2; // If the pointee's size is sizeof(char),
4855 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004856
4857 // If the function is defined as a builtin macro, do not show macro
4858 // expansion.
4859 SourceLocation SL = SizeOfArg->getExprLoc();
4860 SourceRange DSR = Dest->getSourceRange();
4861 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004862 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004863
4864 if (SM.isMacroArgExpansion(SL)) {
4865 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4866 SL = SM.getSpellingLoc(SL);
4867 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4868 SM.getSpellingLoc(DSR.getEnd()));
4869 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4870 SM.getSpellingLoc(SSR.getEnd()));
4871 }
4872
Anna Zaksd08d9152012-05-30 23:14:52 +00004873 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004874 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004875 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004876 << PointeeTy
4877 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004878 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004879 << SSR);
4880 DiagRuntimeBehavior(SL, SizeOfArg,
4881 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4882 << ActionIdx
4883 << SSR);
4884
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004885 break;
4886 }
4887 }
4888
4889 // Also check for cases where the sizeof argument is the exact same
4890 // type as the memory argument, and where it points to a user-defined
4891 // record type.
4892 if (SizeOfArgTy != QualType()) {
4893 if (PointeeTy->isRecordType() &&
4894 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4895 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4896 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4897 << FnName << SizeOfArgTy << ArgIdx
4898 << PointeeTy << Dest->getSourceRange()
4899 << LenExpr->getSourceRange());
4900 break;
4901 }
Nico Weberc5e73862011-06-14 16:14:58 +00004902 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00004903 } else if (DestTy->isArrayType()) {
4904 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00004905 }
Nico Weberc5e73862011-06-14 16:14:58 +00004906
Nico Weberc44b35e2015-03-21 17:37:46 +00004907 if (PointeeTy == QualType())
4908 continue;
Anna Zaks22122702012-01-17 00:37:07 +00004909
Nico Weberc44b35e2015-03-21 17:37:46 +00004910 // Always complain about dynamic classes.
4911 bool IsContained;
4912 if (const CXXRecordDecl *ContainedRD =
4913 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00004914
Nico Weberc44b35e2015-03-21 17:37:46 +00004915 unsigned OperationType = 0;
4916 // "overwritten" if we're warning about the destination for any call
4917 // but memcmp; otherwise a verb appropriate to the call.
4918 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4919 if (BId == Builtin::BImemcpy)
4920 OperationType = 1;
4921 else if(BId == Builtin::BImemmove)
4922 OperationType = 2;
4923 else if (BId == Builtin::BImemcmp)
4924 OperationType = 3;
4925 }
4926
John McCall31168b02011-06-15 23:02:42 +00004927 DiagRuntimeBehavior(
4928 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00004929 PDiag(diag::warn_dyn_class_memaccess)
4930 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4931 << FnName << IsContained << ContainedRD << OperationType
4932 << Call->getCallee()->getSourceRange());
4933 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4934 BId != Builtin::BImemset)
4935 DiagRuntimeBehavior(
4936 Dest->getExprLoc(), Dest,
4937 PDiag(diag::warn_arc_object_memaccess)
4938 << ArgIdx << FnName << PointeeTy
4939 << Call->getCallee()->getSourceRange());
4940 else
4941 continue;
4942
4943 DiagRuntimeBehavior(
4944 Dest->getExprLoc(), Dest,
4945 PDiag(diag::note_bad_memaccess_silence)
4946 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4947 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004948 }
Nico Weberc44b35e2015-03-21 17:37:46 +00004949
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004950}
4951
Ted Kremenek6865f772011-08-18 20:55:45 +00004952// A little helper routine: ignore addition and subtraction of integer literals.
4953// This intentionally does not ignore all integer constant expressions because
4954// we don't want to remove sizeof().
4955static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4956 Ex = Ex->IgnoreParenCasts();
4957
4958 for (;;) {
4959 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4960 if (!BO || !BO->isAdditiveOp())
4961 break;
4962
4963 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4964 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4965
4966 if (isa<IntegerLiteral>(RHS))
4967 Ex = LHS;
4968 else if (isa<IntegerLiteral>(LHS))
4969 Ex = RHS;
4970 else
4971 break;
4972 }
4973
4974 return Ex;
4975}
4976
Anna Zaks13b08572012-08-08 21:42:23 +00004977static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4978 ASTContext &Context) {
4979 // Only handle constant-sized or VLAs, but not flexible members.
4980 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4981 // Only issue the FIXIT for arrays of size > 1.
4982 if (CAT->getSize().getSExtValue() <= 1)
4983 return false;
4984 } else if (!Ty->isVariableArrayType()) {
4985 return false;
4986 }
4987 return true;
4988}
4989
Ted Kremenek6865f772011-08-18 20:55:45 +00004990// Warn if the user has made the 'size' argument to strlcpy or strlcat
4991// be the size of the source, instead of the destination.
4992void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4993 IdentifierInfo *FnName) {
4994
4995 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004996 unsigned NumArgs = Call->getNumArgs();
4997 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004998 return;
4999
5000 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5001 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005002 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005003
5004 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5005 Call->getLocStart(), Call->getRParenLoc()))
5006 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005007
5008 // Look for 'strlcpy(dst, x, sizeof(x))'
5009 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5010 CompareWithSrc = Ex;
5011 else {
5012 // Look for 'strlcpy(dst, x, strlen(x))'
5013 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005014 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5015 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005016 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5017 }
5018 }
5019
5020 if (!CompareWithSrc)
5021 return;
5022
5023 // Determine if the argument to sizeof/strlen is equal to the source
5024 // argument. In principle there's all kinds of things you could do
5025 // here, for instance creating an == expression and evaluating it with
5026 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5027 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5028 if (!SrcArgDRE)
5029 return;
5030
5031 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5032 if (!CompareWithSrcDRE ||
5033 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5034 return;
5035
5036 const Expr *OriginalSizeArg = Call->getArg(2);
5037 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5038 << OriginalSizeArg->getSourceRange() << FnName;
5039
5040 // Output a FIXIT hint if the destination is an array (rather than a
5041 // pointer to an array). This could be enhanced to handle some
5042 // pointers if we know the actual size, like if DstArg is 'array+2'
5043 // we could say 'sizeof(array)-2'.
5044 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005045 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005046 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005047
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005048 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005049 llvm::raw_svector_ostream OS(sizeString);
5050 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005051 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005052 OS << ")";
5053
5054 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5055 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5056 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005057}
5058
Anna Zaks314cd092012-02-01 19:08:57 +00005059/// Check if two expressions refer to the same declaration.
5060static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5061 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5062 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5063 return D1->getDecl() == D2->getDecl();
5064 return false;
5065}
5066
5067static const Expr *getStrlenExprArg(const Expr *E) {
5068 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5069 const FunctionDecl *FD = CE->getDirectCallee();
5070 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005071 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005072 return CE->getArg(0)->IgnoreParenCasts();
5073 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005074 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005075}
5076
5077// Warn on anti-patterns as the 'size' argument to strncat.
5078// The correct size argument should look like following:
5079// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5080void Sema::CheckStrncatArguments(const CallExpr *CE,
5081 IdentifierInfo *FnName) {
5082 // Don't crash if the user has the wrong number of arguments.
5083 if (CE->getNumArgs() < 3)
5084 return;
5085 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5086 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5087 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5088
Nico Weber0e6daef2013-12-26 23:38:39 +00005089 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5090 CE->getRParenLoc()))
5091 return;
5092
Anna Zaks314cd092012-02-01 19:08:57 +00005093 // Identify common expressions, which are wrongly used as the size argument
5094 // to strncat and may lead to buffer overflows.
5095 unsigned PatternType = 0;
5096 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5097 // - sizeof(dst)
5098 if (referToTheSameDecl(SizeOfArg, DstArg))
5099 PatternType = 1;
5100 // - sizeof(src)
5101 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5102 PatternType = 2;
5103 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5104 if (BE->getOpcode() == BO_Sub) {
5105 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5106 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5107 // - sizeof(dst) - strlen(dst)
5108 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5109 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5110 PatternType = 1;
5111 // - sizeof(src) - (anything)
5112 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5113 PatternType = 2;
5114 }
5115 }
5116
5117 if (PatternType == 0)
5118 return;
5119
Anna Zaks5069aa32012-02-03 01:27:37 +00005120 // Generate the diagnostic.
5121 SourceLocation SL = LenArg->getLocStart();
5122 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005123 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005124
5125 // If the function is defined as a builtin macro, do not show macro expansion.
5126 if (SM.isMacroArgExpansion(SL)) {
5127 SL = SM.getSpellingLoc(SL);
5128 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5129 SM.getSpellingLoc(SR.getEnd()));
5130 }
5131
Anna Zaks13b08572012-08-08 21:42:23 +00005132 // Check if the destination is an array (rather than a pointer to an array).
5133 QualType DstTy = DstArg->getType();
5134 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5135 Context);
5136 if (!isKnownSizeArray) {
5137 if (PatternType == 1)
5138 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5139 else
5140 Diag(SL, diag::warn_strncat_src_size) << SR;
5141 return;
5142 }
5143
Anna Zaks314cd092012-02-01 19:08:57 +00005144 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005145 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005146 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005147 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005148
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005149 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005150 llvm::raw_svector_ostream OS(sizeString);
5151 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005152 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005153 OS << ") - ";
5154 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005156 OS << ") - 1";
5157
Anna Zaks5069aa32012-02-03 01:27:37 +00005158 Diag(SL, diag::note_strncat_wrong_size)
5159 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005160}
5161
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005162//===--- CHECK: Return Address of Stack Variable --------------------------===//
5163
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005164static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5165 Decl *ParentDecl);
5166static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5167 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005168
5169/// CheckReturnStackAddr - Check if a return statement returns the address
5170/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005171static void
5172CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5173 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005174
Craig Topperc3ec1492014-05-26 06:22:03 +00005175 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005176 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005177
5178 // Perform checking for returned stack addresses, local blocks,
5179 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005180 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005181 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005182 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005183 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005184 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005185 }
5186
Craig Topperc3ec1492014-05-26 06:22:03 +00005187 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005188 return; // Nothing suspicious was found.
5189
5190 SourceLocation diagLoc;
5191 SourceRange diagRange;
5192 if (refVars.empty()) {
5193 diagLoc = stackE->getLocStart();
5194 diagRange = stackE->getSourceRange();
5195 } else {
5196 // We followed through a reference variable. 'stackE' contains the
5197 // problematic expression but we will warn at the return statement pointing
5198 // at the reference variable. We will later display the "trail" of
5199 // reference variables using notes.
5200 diagLoc = refVars[0]->getLocStart();
5201 diagRange = refVars[0]->getSourceRange();
5202 }
5203
5204 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005205 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005206 : diag::warn_ret_stack_addr)
5207 << DR->getDecl()->getDeclName() << diagRange;
5208 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005209 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005210 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005211 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005212 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005213 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5214 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005215 << diagRange;
5216 }
5217
5218 // Display the "trail" of reference variables that we followed until we
5219 // found the problematic expression using notes.
5220 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5221 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5222 // If this var binds to another reference var, show the range of the next
5223 // var, otherwise the var binds to the problematic expression, in which case
5224 // show the range of the expression.
5225 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5226 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005227 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5228 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005229 }
5230}
5231
5232/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5233/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005234/// to a location on the stack, a local block, an address of a label, or a
5235/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005236/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005237/// encounter a subexpression that (1) clearly does not lead to one of the
5238/// above problematic expressions (2) is something we cannot determine leads to
5239/// a problematic expression based on such local checking.
5240///
5241/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5242/// the expression that they point to. Such variables are added to the
5243/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005244///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005245/// EvalAddr processes expressions that are pointers that are used as
5246/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005247/// At the base case of the recursion is a check for the above problematic
5248/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005249///
5250/// This implementation handles:
5251///
5252/// * pointer-to-pointer casts
5253/// * implicit conversions from array references to pointers
5254/// * taking the address of fields
5255/// * arbitrary interplay between "&" and "*" operators
5256/// * pointer arithmetic from an address of a stack variable
5257/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005258static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5259 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005260 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005261 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005262
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005263 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005264 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005265 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005266 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005267 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005268
Peter Collingbourne91147592011-04-15 00:35:48 +00005269 E = E->IgnoreParens();
5270
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005271 // Our "symbolic interpreter" is just a dispatch off the currently
5272 // viewed AST node. We then recursively traverse the AST by calling
5273 // EvalAddr and EvalVal appropriately.
5274 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005275 case Stmt::DeclRefExprClass: {
5276 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5277
Richard Smith40f08eb2014-01-30 22:05:38 +00005278 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005279 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005280 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005281
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005282 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5283 // If this is a reference variable, follow through to the expression that
5284 // it points to.
5285 if (V->hasLocalStorage() &&
5286 V->getType()->isReferenceType() && V->hasInit()) {
5287 // Add the reference variable to the "trail".
5288 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005289 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005290 }
5291
Craig Topperc3ec1492014-05-26 06:22:03 +00005292 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005293 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005294
Chris Lattner934edb22007-12-28 05:31:15 +00005295 case Stmt::UnaryOperatorClass: {
5296 // The only unary operator that make sense to handle here
5297 // is AddrOf. All others don't make sense as pointers.
5298 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005299
John McCalle3027922010-08-25 11:45:40 +00005300 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005301 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005302 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005303 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005304 }
Mike Stump11289f42009-09-09 15:08:12 +00005305
Chris Lattner934edb22007-12-28 05:31:15 +00005306 case Stmt::BinaryOperatorClass: {
5307 // Handle pointer arithmetic. All other binary operators are not valid
5308 // in this context.
5309 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005310 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005311
John McCalle3027922010-08-25 11:45:40 +00005312 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005313 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005314
Chris Lattner934edb22007-12-28 05:31:15 +00005315 Expr *Base = B->getLHS();
5316
5317 // Determine which argument is the real pointer base. It could be
5318 // the RHS argument instead of the LHS.
5319 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005320
Chris Lattner934edb22007-12-28 05:31:15 +00005321 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005322 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005323 }
Steve Naroff2752a172008-09-10 19:17:48 +00005324
Chris Lattner934edb22007-12-28 05:31:15 +00005325 // For conditional operators we need to see if either the LHS or RHS are
5326 // valid DeclRefExpr*s. If one of them is valid, we return it.
5327 case Stmt::ConditionalOperatorClass: {
5328 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005329
Chris Lattner934edb22007-12-28 05:31:15 +00005330 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005331 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5332 if (Expr *LHSExpr = C->getLHS()) {
5333 // In C++, we can have a throw-expression, which has 'void' type.
5334 if (!LHSExpr->getType()->isVoidType())
5335 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005336 return LHS;
5337 }
Chris Lattner934edb22007-12-28 05:31:15 +00005338
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005339 // In C++, we can have a throw-expression, which has 'void' type.
5340 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005341 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005342
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005343 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005344 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005345
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005346 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005347 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005348 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005349 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005350
5351 case Stmt::AddrLabelExprClass:
5352 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005353
John McCall28fc7092011-11-10 05:35:25 +00005354 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005355 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5356 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005357
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005358 // For casts, we need to handle conversions from arrays to
5359 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005360 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005361 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005362 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005363 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005364 case Stmt::CXXStaticCastExprClass:
5365 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005366 case Stmt::CXXConstCastExprClass:
5367 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005368 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5369 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005370 case CK_LValueToRValue:
5371 case CK_NoOp:
5372 case CK_BaseToDerived:
5373 case CK_DerivedToBase:
5374 case CK_UncheckedDerivedToBase:
5375 case CK_Dynamic:
5376 case CK_CPointerToObjCPointerCast:
5377 case CK_BlockPointerToObjCPointerCast:
5378 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005379 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005380
5381 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005382 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005383
Richard Trieudadefde2014-07-02 04:39:38 +00005384 case CK_BitCast:
5385 if (SubExpr->getType()->isAnyPointerType() ||
5386 SubExpr->getType()->isBlockPointerType() ||
5387 SubExpr->getType()->isObjCQualifiedIdType())
5388 return EvalAddr(SubExpr, refVars, ParentDecl);
5389 else
5390 return nullptr;
5391
Eli Friedman8195ad72012-02-23 23:04:32 +00005392 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005393 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005394 }
Chris Lattner934edb22007-12-28 05:31:15 +00005395 }
Mike Stump11289f42009-09-09 15:08:12 +00005396
Douglas Gregorfe314812011-06-21 17:03:29 +00005397 case Stmt::MaterializeTemporaryExprClass:
5398 if (Expr *Result = EvalAddr(
5399 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005400 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005401 return Result;
5402
5403 return E;
5404
Chris Lattner934edb22007-12-28 05:31:15 +00005405 // Everything else: we simply don't reason about them.
5406 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005407 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005408 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005409}
Mike Stump11289f42009-09-09 15:08:12 +00005410
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005411
5412/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5413/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005414static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5415 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005416do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005417 // We should only be called for evaluating non-pointer expressions, or
5418 // expressions with a pointer type that are not used as references but instead
5419 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005420
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005421 // Our "symbolic interpreter" is just a dispatch off the currently
5422 // viewed AST node. We then recursively traverse the AST by calling
5423 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005424
5425 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005426 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005427 case Stmt::ImplicitCastExprClass: {
5428 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005429 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005430 E = IE->getSubExpr();
5431 continue;
5432 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005433 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005434 }
5435
John McCall28fc7092011-11-10 05:35:25 +00005436 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005437 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005438
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005439 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005440 // When we hit a DeclRefExpr we are looking at code that refers to a
5441 // variable's name. If it's not a reference variable we check if it has
5442 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005443 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005444
Richard Smith40f08eb2014-01-30 22:05:38 +00005445 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005446 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005447 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005448
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005449 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5450 // Check if it refers to itself, e.g. "int& i = i;".
5451 if (V == ParentDecl)
5452 return DR;
5453
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005454 if (V->hasLocalStorage()) {
5455 if (!V->getType()->isReferenceType())
5456 return DR;
5457
5458 // Reference variable, follow through to the expression that
5459 // it points to.
5460 if (V->hasInit()) {
5461 // Add the reference variable to the "trail".
5462 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005463 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005464 }
5465 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005466 }
Mike Stump11289f42009-09-09 15:08:12 +00005467
Craig Topperc3ec1492014-05-26 06:22:03 +00005468 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005469 }
Mike Stump11289f42009-09-09 15:08:12 +00005470
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005471 case Stmt::UnaryOperatorClass: {
5472 // The only unary operator that make sense to handle here
5473 // is Deref. All others don't resolve to a "name." This includes
5474 // handling all sorts of rvalues passed to a unary operator.
5475 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005476
John McCalle3027922010-08-25 11:45:40 +00005477 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005478 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005479
Craig Topperc3ec1492014-05-26 06:22:03 +00005480 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005481 }
Mike Stump11289f42009-09-09 15:08:12 +00005482
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005483 case Stmt::ArraySubscriptExprClass: {
5484 // Array subscripts are potential references to data on the stack. We
5485 // retrieve the DeclRefExpr* for the array variable if it indeed
5486 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005487 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005488 }
Mike Stump11289f42009-09-09 15:08:12 +00005489
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005490 case Stmt::ConditionalOperatorClass: {
5491 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005492 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005493 ConditionalOperator *C = cast<ConditionalOperator>(E);
5494
Anders Carlsson801c5c72007-11-30 19:04:31 +00005495 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005496 if (Expr *LHSExpr = C->getLHS()) {
5497 // In C++, we can have a throw-expression, which has 'void' type.
5498 if (!LHSExpr->getType()->isVoidType())
5499 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5500 return LHS;
5501 }
5502
5503 // In C++, we can have a throw-expression, which has 'void' type.
5504 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005505 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005506
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005507 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005508 }
Mike Stump11289f42009-09-09 15:08:12 +00005509
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005510 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005511 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005512 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005513
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005514 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005515 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005516 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005517
5518 // Check whether the member type is itself a reference, in which case
5519 // we're not going to refer to the member, but to what the member refers to.
5520 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005521 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005522
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005523 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005524 }
Mike Stump11289f42009-09-09 15:08:12 +00005525
Douglas Gregorfe314812011-06-21 17:03:29 +00005526 case Stmt::MaterializeTemporaryExprClass:
5527 if (Expr *Result = EvalVal(
5528 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005529 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005530 return Result;
5531
5532 return E;
5533
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005534 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005535 // Check that we don't return or take the address of a reference to a
5536 // temporary. This is only useful in C++.
5537 if (!E->isTypeDependent() && E->isRValue())
5538 return E;
5539
5540 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005541 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005542 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005543} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005544}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005545
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005546void
5547Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5548 SourceLocation ReturnLoc,
5549 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005550 const AttrVec *Attrs,
5551 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005552 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5553
5554 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005555 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5556 CheckNonNullExpr(*this, RetValExp))
5557 Diag(ReturnLoc, diag::warn_null_ret)
5558 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005559
5560 // C++11 [basic.stc.dynamic.allocation]p4:
5561 // If an allocation function declared with a non-throwing
5562 // exception-specification fails to allocate storage, it shall return
5563 // a null pointer. Any other allocation function that fails to allocate
5564 // storage shall indicate failure only by throwing an exception [...]
5565 if (FD) {
5566 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5567 if (Op == OO_New || Op == OO_Array_New) {
5568 const FunctionProtoType *Proto
5569 = FD->getType()->castAs<FunctionProtoType>();
5570 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5571 CheckNonNullExpr(*this, RetValExp))
5572 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5573 << FD << getLangOpts().CPlusPlus11;
5574 }
5575 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005576}
5577
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005578//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5579
5580/// Check for comparisons of floating point operands using != and ==.
5581/// Issue a warning if these are no self-comparisons, as they are not likely
5582/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005583void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005584 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5585 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005586
5587 // Special case: check for x == x (which is OK).
5588 // Do not emit warnings for such cases.
5589 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5590 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5591 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005592 return;
Mike Stump11289f42009-09-09 15:08:12 +00005593
5594
Ted Kremenekeda40e22007-11-29 00:59:04 +00005595 // Special case: check for comparisons against literals that can be exactly
5596 // represented by APFloat. In such cases, do not emit a warning. This
5597 // is a heuristic: often comparison against such literals are used to
5598 // detect if a value in a variable has not changed. This clearly can
5599 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005600 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5601 if (FLL->isExact())
5602 return;
5603 } else
5604 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5605 if (FLR->isExact())
5606 return;
Mike Stump11289f42009-09-09 15:08:12 +00005607
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005608 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005609 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005610 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005611 return;
Mike Stump11289f42009-09-09 15:08:12 +00005612
David Blaikie1f4ff152012-07-16 20:47:22 +00005613 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005614 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005615 return;
Mike Stump11289f42009-09-09 15:08:12 +00005616
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005617 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005618 Diag(Loc, diag::warn_floatingpoint_eq)
5619 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005620}
John McCallca01b222010-01-04 23:21:16 +00005621
John McCall70aa5392010-01-06 05:24:50 +00005622//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5623//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005624
John McCall70aa5392010-01-06 05:24:50 +00005625namespace {
John McCallca01b222010-01-04 23:21:16 +00005626
John McCall70aa5392010-01-06 05:24:50 +00005627/// Structure recording the 'active' range of an integer-valued
5628/// expression.
5629struct IntRange {
5630 /// The number of bits active in the int.
5631 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005632
John McCall70aa5392010-01-06 05:24:50 +00005633 /// True if the int is known not to have negative values.
5634 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005635
John McCall70aa5392010-01-06 05:24:50 +00005636 IntRange(unsigned Width, bool NonNegative)
5637 : Width(Width), NonNegative(NonNegative)
5638 {}
John McCallca01b222010-01-04 23:21:16 +00005639
John McCall817d4af2010-11-10 23:38:19 +00005640 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005641 static IntRange forBoolType() {
5642 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005643 }
5644
John McCall817d4af2010-11-10 23:38:19 +00005645 /// Returns the range of an opaque value of the given integral type.
5646 static IntRange forValueOfType(ASTContext &C, QualType T) {
5647 return forValueOfCanonicalType(C,
5648 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005649 }
5650
John McCall817d4af2010-11-10 23:38:19 +00005651 /// Returns the range of an opaque value of a canonical integral type.
5652 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005653 assert(T->isCanonicalUnqualified());
5654
5655 if (const VectorType *VT = dyn_cast<VectorType>(T))
5656 T = VT->getElementType().getTypePtr();
5657 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5658 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005659 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5660 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005661
David Majnemer6a426652013-06-07 22:07:20 +00005662 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005663 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005664 EnumDecl *Enum = ET->getDecl();
5665 if (!Enum->isCompleteDefinition())
5666 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005667
David Majnemer6a426652013-06-07 22:07:20 +00005668 unsigned NumPositive = Enum->getNumPositiveBits();
5669 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005670
David Majnemer6a426652013-06-07 22:07:20 +00005671 if (NumNegative == 0)
5672 return IntRange(NumPositive, true/*NonNegative*/);
5673 else
5674 return IntRange(std::max(NumPositive + 1, NumNegative),
5675 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005676 }
John McCall70aa5392010-01-06 05:24:50 +00005677
5678 const BuiltinType *BT = cast<BuiltinType>(T);
5679 assert(BT->isInteger());
5680
5681 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5682 }
5683
John McCall817d4af2010-11-10 23:38:19 +00005684 /// Returns the "target" range of a canonical integral type, i.e.
5685 /// the range of values expressible in the type.
5686 ///
5687 /// This matches forValueOfCanonicalType except that enums have the
5688 /// full range of their type, not the range of their enumerators.
5689 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5690 assert(T->isCanonicalUnqualified());
5691
5692 if (const VectorType *VT = dyn_cast<VectorType>(T))
5693 T = VT->getElementType().getTypePtr();
5694 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5695 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005696 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5697 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005698 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005699 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005700
5701 const BuiltinType *BT = cast<BuiltinType>(T);
5702 assert(BT->isInteger());
5703
5704 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5705 }
5706
5707 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005708 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005709 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005710 L.NonNegative && R.NonNegative);
5711 }
5712
John McCall817d4af2010-11-10 23:38:19 +00005713 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005714 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005715 return IntRange(std::min(L.Width, R.Width),
5716 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005717 }
5718};
5719
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005720static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5721 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005722 if (value.isSigned() && value.isNegative())
5723 return IntRange(value.getMinSignedBits(), false);
5724
5725 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005726 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005727
5728 // isNonNegative() just checks the sign bit without considering
5729 // signedness.
5730 return IntRange(value.getActiveBits(), true);
5731}
5732
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005733static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5734 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005735 if (result.isInt())
5736 return GetValueRange(C, result.getInt(), MaxWidth);
5737
5738 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005739 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5740 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5741 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5742 R = IntRange::join(R, El);
5743 }
John McCall70aa5392010-01-06 05:24:50 +00005744 return R;
5745 }
5746
5747 if (result.isComplexInt()) {
5748 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5749 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5750 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005751 }
5752
5753 // This can happen with lossless casts to intptr_t of "based" lvalues.
5754 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005755 // FIXME: The only reason we need to pass the type in here is to get
5756 // the sign right on this one case. It would be nice if APValue
5757 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005758 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005759 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005760}
John McCall70aa5392010-01-06 05:24:50 +00005761
Eli Friedmane6d33952013-07-08 20:20:06 +00005762static QualType GetExprType(Expr *E) {
5763 QualType Ty = E->getType();
5764 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5765 Ty = AtomicRHS->getValueType();
5766 return Ty;
5767}
5768
John McCall70aa5392010-01-06 05:24:50 +00005769/// Pseudo-evaluate the given integer expression, estimating the
5770/// range of values it might take.
5771///
5772/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005773static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005774 E = E->IgnoreParens();
5775
5776 // Try a full evaluation first.
5777 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005778 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005779 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005780
5781 // I think we only want to look through implicit casts here; if the
5782 // user has an explicit widening cast, we should treat the value as
5783 // being of the new, wider type.
5784 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005785 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005786 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5787
Eli Friedmane6d33952013-07-08 20:20:06 +00005788 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005789
John McCalle3027922010-08-25 11:45:40 +00005790 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005791
John McCall70aa5392010-01-06 05:24:50 +00005792 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005793 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005794 return OutputTypeRange;
5795
5796 IntRange SubRange
5797 = GetExprRange(C, CE->getSubExpr(),
5798 std::min(MaxWidth, OutputTypeRange.Width));
5799
5800 // Bail out if the subexpr's range is as wide as the cast type.
5801 if (SubRange.Width >= OutputTypeRange.Width)
5802 return OutputTypeRange;
5803
5804 // Otherwise, we take the smaller width, and we're non-negative if
5805 // either the output type or the subexpr is.
5806 return IntRange(SubRange.Width,
5807 SubRange.NonNegative || OutputTypeRange.NonNegative);
5808 }
5809
5810 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5811 // If we can fold the condition, just take that operand.
5812 bool CondResult;
5813 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5814 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5815 : CO->getFalseExpr(),
5816 MaxWidth);
5817
5818 // Otherwise, conservatively merge.
5819 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5820 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5821 return IntRange::join(L, R);
5822 }
5823
5824 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5825 switch (BO->getOpcode()) {
5826
5827 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005828 case BO_LAnd:
5829 case BO_LOr:
5830 case BO_LT:
5831 case BO_GT:
5832 case BO_LE:
5833 case BO_GE:
5834 case BO_EQ:
5835 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005836 return IntRange::forBoolType();
5837
John McCallc3688382011-07-13 06:35:24 +00005838 // The type of the assignments is the type of the LHS, so the RHS
5839 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005840 case BO_MulAssign:
5841 case BO_DivAssign:
5842 case BO_RemAssign:
5843 case BO_AddAssign:
5844 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005845 case BO_XorAssign:
5846 case BO_OrAssign:
5847 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005848 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005849
John McCallc3688382011-07-13 06:35:24 +00005850 // Simple assignments just pass through the RHS, which will have
5851 // been coerced to the LHS type.
5852 case BO_Assign:
5853 // TODO: bitfields?
5854 return GetExprRange(C, BO->getRHS(), MaxWidth);
5855
John McCall70aa5392010-01-06 05:24:50 +00005856 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005857 case BO_PtrMemD:
5858 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005859 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005860
John McCall2ce81ad2010-01-06 22:07:33 +00005861 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005862 case BO_And:
5863 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005864 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5865 GetExprRange(C, BO->getRHS(), MaxWidth));
5866
John McCall70aa5392010-01-06 05:24:50 +00005867 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005868 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005869 // ...except that we want to treat '1 << (blah)' as logically
5870 // positive. It's an important idiom.
5871 if (IntegerLiteral *I
5872 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5873 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005874 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005875 return IntRange(R.Width, /*NonNegative*/ true);
5876 }
5877 }
5878 // fallthrough
5879
John McCalle3027922010-08-25 11:45:40 +00005880 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005881 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005882
John McCall2ce81ad2010-01-06 22:07:33 +00005883 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005884 case BO_Shr:
5885 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005886 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5887
5888 // If the shift amount is a positive constant, drop the width by
5889 // that much.
5890 llvm::APSInt shift;
5891 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5892 shift.isNonNegative()) {
5893 unsigned zext = shift.getZExtValue();
5894 if (zext >= L.Width)
5895 L.Width = (L.NonNegative ? 0 : 1);
5896 else
5897 L.Width -= zext;
5898 }
5899
5900 return L;
5901 }
5902
5903 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005904 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005905 return GetExprRange(C, BO->getRHS(), MaxWidth);
5906
John McCall2ce81ad2010-01-06 22:07:33 +00005907 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005908 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005909 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005910 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005911 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005912
John McCall51431812011-07-14 22:39:48 +00005913 // The width of a division result is mostly determined by the size
5914 // of the LHS.
5915 case BO_Div: {
5916 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005917 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005918 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5919
5920 // If the divisor is constant, use that.
5921 llvm::APSInt divisor;
5922 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5923 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5924 if (log2 >= L.Width)
5925 L.Width = (L.NonNegative ? 0 : 1);
5926 else
5927 L.Width = std::min(L.Width - log2, MaxWidth);
5928 return L;
5929 }
5930
5931 // Otherwise, just use the LHS's width.
5932 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5933 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5934 }
5935
5936 // The result of a remainder can't be larger than the result of
5937 // either side.
5938 case BO_Rem: {
5939 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005940 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005941 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5942 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5943
5944 IntRange meet = IntRange::meet(L, R);
5945 meet.Width = std::min(meet.Width, MaxWidth);
5946 return meet;
5947 }
5948
5949 // The default behavior is okay for these.
5950 case BO_Mul:
5951 case BO_Add:
5952 case BO_Xor:
5953 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005954 break;
5955 }
5956
John McCall51431812011-07-14 22:39:48 +00005957 // The default case is to treat the operation as if it were closed
5958 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005959 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5960 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5961 return IntRange::join(L, R);
5962 }
5963
5964 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5965 switch (UO->getOpcode()) {
5966 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005967 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005968 return IntRange::forBoolType();
5969
5970 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005971 case UO_Deref:
5972 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005973 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005974
5975 default:
5976 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5977 }
5978 }
5979
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005980 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5981 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5982
John McCalld25db7e2013-05-06 21:39:12 +00005983 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005984 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005985 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005986
Eli Friedmane6d33952013-07-08 20:20:06 +00005987 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005988}
John McCall263a48b2010-01-04 23:31:57 +00005989
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005990static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005991 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005992}
5993
John McCall263a48b2010-01-04 23:31:57 +00005994/// Checks whether the given value, which currently has the given
5995/// source semantics, has the same value when coerced through the
5996/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005997static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5998 const llvm::fltSemantics &Src,
5999 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006000 llvm::APFloat truncated = value;
6001
6002 bool ignored;
6003 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6004 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6005
6006 return truncated.bitwiseIsEqual(value);
6007}
6008
6009/// Checks whether the given value, which currently has the given
6010/// source semantics, has the same value when coerced through the
6011/// target semantics.
6012///
6013/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006014static bool IsSameFloatAfterCast(const APValue &value,
6015 const llvm::fltSemantics &Src,
6016 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006017 if (value.isFloat())
6018 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6019
6020 if (value.isVector()) {
6021 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6022 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6023 return false;
6024 return true;
6025 }
6026
6027 assert(value.isComplexFloat());
6028 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6029 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6030}
6031
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006032static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006033
Ted Kremenek6274be42010-09-23 21:43:44 +00006034static bool IsZero(Sema &S, Expr *E) {
6035 // Suppress cases where we are comparing against an enum constant.
6036 if (const DeclRefExpr *DR =
6037 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6038 if (isa<EnumConstantDecl>(DR->getDecl()))
6039 return false;
6040
6041 // Suppress cases where the '0' value is expanded from a macro.
6042 if (E->getLocStart().isMacroID())
6043 return false;
6044
John McCallcc7e5bf2010-05-06 08:58:33 +00006045 llvm::APSInt Value;
6046 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6047}
6048
John McCall2551c1b2010-10-06 00:25:24 +00006049static bool HasEnumType(Expr *E) {
6050 // Strip off implicit integral promotions.
6051 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006052 if (ICE->getCastKind() != CK_IntegralCast &&
6053 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006054 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006055 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006056 }
6057
6058 return E->getType()->isEnumeralType();
6059}
6060
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006061static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006062 // Disable warning in template instantiations.
6063 if (!S.ActiveTemplateInstantiations.empty())
6064 return;
6065
John McCalle3027922010-08-25 11:45:40 +00006066 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006067 if (E->isValueDependent())
6068 return;
6069
John McCalle3027922010-08-25 11:45:40 +00006070 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006071 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006072 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006073 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006074 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006075 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006076 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006077 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006078 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006079 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006080 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006081 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006082 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006083 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006084 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006085 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6086 }
6087}
6088
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006089static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006090 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006091 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006092 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006093 // Disable warning in template instantiations.
6094 if (!S.ActiveTemplateInstantiations.empty())
6095 return;
6096
Richard Trieu0f097742014-04-04 04:13:47 +00006097 // TODO: Investigate using GetExprRange() to get tighter bounds
6098 // on the bit ranges.
6099 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006100 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
6101 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006102 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6103 unsigned OtherWidth = OtherRange.Width;
6104
6105 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6106
Richard Trieu560910c2012-11-14 22:50:24 +00006107 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006108 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006109 return;
6110
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006111 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006112 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006113
Richard Trieu0f097742014-04-04 04:13:47 +00006114 // Used for diagnostic printout.
6115 enum {
6116 LiteralConstant = 0,
6117 CXXBoolLiteralTrue,
6118 CXXBoolLiteralFalse
6119 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006120
Richard Trieu0f097742014-04-04 04:13:47 +00006121 if (!OtherIsBooleanType) {
6122 QualType ConstantT = Constant->getType();
6123 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006124
Richard Trieu0f097742014-04-04 04:13:47 +00006125 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6126 return;
6127 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6128 "comparison with non-integer type");
6129
6130 bool ConstantSigned = ConstantT->isSignedIntegerType();
6131 bool CommonSigned = CommonT->isSignedIntegerType();
6132
6133 bool EqualityOnly = false;
6134
6135 if (CommonSigned) {
6136 // The common type is signed, therefore no signed to unsigned conversion.
6137 if (!OtherRange.NonNegative) {
6138 // Check that the constant is representable in type OtherT.
6139 if (ConstantSigned) {
6140 if (OtherWidth >= Value.getMinSignedBits())
6141 return;
6142 } else { // !ConstantSigned
6143 if (OtherWidth >= Value.getActiveBits() + 1)
6144 return;
6145 }
6146 } else { // !OtherSigned
6147 // Check that the constant is representable in type OtherT.
6148 // Negative values are out of range.
6149 if (ConstantSigned) {
6150 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6151 return;
6152 } else { // !ConstantSigned
6153 if (OtherWidth >= Value.getActiveBits())
6154 return;
6155 }
Richard Trieu560910c2012-11-14 22:50:24 +00006156 }
Richard Trieu0f097742014-04-04 04:13:47 +00006157 } else { // !CommonSigned
6158 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006159 if (OtherWidth >= Value.getActiveBits())
6160 return;
Craig Toppercf360162014-06-18 05:13:11 +00006161 } else { // OtherSigned
6162 assert(!ConstantSigned &&
6163 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006164 // Check to see if the constant is representable in OtherT.
6165 if (OtherWidth > Value.getActiveBits())
6166 return;
6167 // Check to see if the constant is equivalent to a negative value
6168 // cast to CommonT.
6169 if (S.Context.getIntWidth(ConstantT) ==
6170 S.Context.getIntWidth(CommonT) &&
6171 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6172 return;
6173 // The constant value rests between values that OtherT can represent
6174 // after conversion. Relational comparison still works, but equality
6175 // comparisons will be tautological.
6176 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006177 }
6178 }
Richard Trieu0f097742014-04-04 04:13:47 +00006179
6180 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6181
6182 if (op == BO_EQ || op == BO_NE) {
6183 IsTrue = op == BO_NE;
6184 } else if (EqualityOnly) {
6185 return;
6186 } else if (RhsConstant) {
6187 if (op == BO_GT || op == BO_GE)
6188 IsTrue = !PositiveConstant;
6189 else // op == BO_LT || op == BO_LE
6190 IsTrue = PositiveConstant;
6191 } else {
6192 if (op == BO_LT || op == BO_LE)
6193 IsTrue = !PositiveConstant;
6194 else // op == BO_GT || op == BO_GE
6195 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006196 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006197 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006198 // Other isKnownToHaveBooleanValue
6199 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6200 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6201 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6202
6203 static const struct LinkedConditions {
6204 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6205 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6206 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6207 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6208 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6209 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6210
6211 } TruthTable = {
6212 // Constant on LHS. | Constant on RHS. |
6213 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6214 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6215 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6216 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6217 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6218 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6219 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6220 };
6221
6222 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6223
6224 enum ConstantValue ConstVal = Zero;
6225 if (Value.isUnsigned() || Value.isNonNegative()) {
6226 if (Value == 0) {
6227 LiteralOrBoolConstant =
6228 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6229 ConstVal = Zero;
6230 } else if (Value == 1) {
6231 LiteralOrBoolConstant =
6232 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6233 ConstVal = One;
6234 } else {
6235 LiteralOrBoolConstant = LiteralConstant;
6236 ConstVal = GT_One;
6237 }
6238 } else {
6239 ConstVal = LT_Zero;
6240 }
6241
6242 CompareBoolWithConstantResult CmpRes;
6243
6244 switch (op) {
6245 case BO_LT:
6246 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6247 break;
6248 case BO_GT:
6249 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6250 break;
6251 case BO_LE:
6252 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6253 break;
6254 case BO_GE:
6255 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6256 break;
6257 case BO_EQ:
6258 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6259 break;
6260 case BO_NE:
6261 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6262 break;
6263 default:
6264 CmpRes = Unkwn;
6265 break;
6266 }
6267
6268 if (CmpRes == AFals) {
6269 IsTrue = false;
6270 } else if (CmpRes == ATrue) {
6271 IsTrue = true;
6272 } else {
6273 return;
6274 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006275 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006276
6277 // If this is a comparison to an enum constant, include that
6278 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006279 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006280 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6281 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6282
6283 SmallString<64> PrettySourceValue;
6284 llvm::raw_svector_ostream OS(PrettySourceValue);
6285 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006286 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006287 else
6288 OS << Value;
6289
Richard Trieu0f097742014-04-04 04:13:47 +00006290 S.DiagRuntimeBehavior(
6291 E->getOperatorLoc(), E,
6292 S.PDiag(diag::warn_out_of_range_compare)
6293 << OS.str() << LiteralOrBoolConstant
6294 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6295 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006296}
6297
John McCallcc7e5bf2010-05-06 08:58:33 +00006298/// Analyze the operands of the given comparison. Implements the
6299/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006300static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006301 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6302 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006303}
John McCall263a48b2010-01-04 23:31:57 +00006304
John McCallca01b222010-01-04 23:21:16 +00006305/// \brief Implements -Wsign-compare.
6306///
Richard Trieu82402a02011-09-15 21:56:47 +00006307/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006308static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006309 // The type the comparison is being performed in.
6310 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006311
6312 // Only analyze comparison operators where both sides have been converted to
6313 // the same type.
6314 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6315 return AnalyzeImpConvsInComparison(S, E);
6316
6317 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006318 if (E->isValueDependent())
6319 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006320
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006321 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6322 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006323
6324 bool IsComparisonConstant = false;
6325
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006326 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006327 // of 'true' or 'false'.
6328 if (T->isIntegralType(S.Context)) {
6329 llvm::APSInt RHSValue;
6330 bool IsRHSIntegralLiteral =
6331 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6332 llvm::APSInt LHSValue;
6333 bool IsLHSIntegralLiteral =
6334 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6335 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6336 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6337 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6338 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6339 else
6340 IsComparisonConstant =
6341 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006342 } else if (!T->hasUnsignedIntegerRepresentation())
6343 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006344
John McCallcc7e5bf2010-05-06 08:58:33 +00006345 // We don't do anything special if this isn't an unsigned integral
6346 // comparison: we're only interested in integral comparisons, and
6347 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006348 //
6349 // We also don't care about value-dependent expressions or expressions
6350 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006351 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006352 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006353
John McCallcc7e5bf2010-05-06 08:58:33 +00006354 // Check to see if one of the (unmodified) operands is of different
6355 // signedness.
6356 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006357 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6358 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006359 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006360 signedOperand = LHS;
6361 unsignedOperand = RHS;
6362 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6363 signedOperand = RHS;
6364 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006365 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006366 CheckTrivialUnsignedComparison(S, E);
6367 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006368 }
6369
John McCallcc7e5bf2010-05-06 08:58:33 +00006370 // Otherwise, calculate the effective range of the signed operand.
6371 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006372
John McCallcc7e5bf2010-05-06 08:58:33 +00006373 // Go ahead and analyze implicit conversions in the operands. Note
6374 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006375 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6376 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006377
John McCallcc7e5bf2010-05-06 08:58:33 +00006378 // If the signed range is non-negative, -Wsign-compare won't fire,
6379 // but we should still check for comparisons which are always true
6380 // or false.
6381 if (signedRange.NonNegative)
6382 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006383
6384 // For (in)equality comparisons, if the unsigned operand is a
6385 // constant which cannot collide with a overflowed signed operand,
6386 // then reinterpreting the signed operand as unsigned will not
6387 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006388 if (E->isEqualityOp()) {
6389 unsigned comparisonWidth = S.Context.getIntWidth(T);
6390 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006391
John McCallcc7e5bf2010-05-06 08:58:33 +00006392 // We should never be unable to prove that the unsigned operand is
6393 // non-negative.
6394 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6395
6396 if (unsignedRange.Width < comparisonWidth)
6397 return;
6398 }
6399
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006400 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6401 S.PDiag(diag::warn_mixed_sign_comparison)
6402 << LHS->getType() << RHS->getType()
6403 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006404}
6405
John McCall1f425642010-11-11 03:21:53 +00006406/// Analyzes an attempt to assign the given value to a bitfield.
6407///
6408/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006409static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6410 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006411 assert(Bitfield->isBitField());
6412 if (Bitfield->isInvalidDecl())
6413 return false;
6414
John McCalldeebbcf2010-11-11 05:33:51 +00006415 // White-list bool bitfields.
6416 if (Bitfield->getType()->isBooleanType())
6417 return false;
6418
Douglas Gregor789adec2011-02-04 13:09:01 +00006419 // Ignore value- or type-dependent expressions.
6420 if (Bitfield->getBitWidth()->isValueDependent() ||
6421 Bitfield->getBitWidth()->isTypeDependent() ||
6422 Init->isValueDependent() ||
6423 Init->isTypeDependent())
6424 return false;
6425
John McCall1f425642010-11-11 03:21:53 +00006426 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6427
Richard Smith5fab0c92011-12-28 19:48:30 +00006428 llvm::APSInt Value;
6429 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006430 return false;
6431
John McCall1f425642010-11-11 03:21:53 +00006432 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006433 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006434
6435 if (OriginalWidth <= FieldWidth)
6436 return false;
6437
Eli Friedmanc267a322012-01-26 23:11:39 +00006438 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006439 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006440 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006441
Eli Friedmanc267a322012-01-26 23:11:39 +00006442 // Check whether the stored value is equal to the original value.
6443 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006444 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006445 return false;
6446
Eli Friedmanc267a322012-01-26 23:11:39 +00006447 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006448 // therefore don't strictly fit into a signed bitfield of width 1.
6449 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006450 return false;
6451
John McCall1f425642010-11-11 03:21:53 +00006452 std::string PrettyValue = Value.toString(10);
6453 std::string PrettyTrunc = TruncatedValue.toString(10);
6454
6455 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6456 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6457 << Init->getSourceRange();
6458
6459 return true;
6460}
6461
John McCalld2a53122010-11-09 23:24:47 +00006462/// Analyze the given simple or compound assignment for warning-worthy
6463/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006464static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006465 // Just recurse on the LHS.
6466 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6467
6468 // We want to recurse on the RHS as normal unless we're assigning to
6469 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006470 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006471 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006472 E->getOperatorLoc())) {
6473 // Recurse, ignoring any implicit conversions on the RHS.
6474 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6475 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006476 }
6477 }
6478
6479 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6480}
6481
John McCall263a48b2010-01-04 23:31:57 +00006482/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006483static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006484 SourceLocation CContext, unsigned diag,
6485 bool pruneControlFlow = false) {
6486 if (pruneControlFlow) {
6487 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6488 S.PDiag(diag)
6489 << SourceType << T << E->getSourceRange()
6490 << SourceRange(CContext));
6491 return;
6492 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006493 S.Diag(E->getExprLoc(), diag)
6494 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6495}
6496
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006497/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006498static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006499 SourceLocation CContext, unsigned diag,
6500 bool pruneControlFlow = false) {
6501 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006502}
6503
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006504/// Diagnose an implicit cast from a literal expression. Does not warn when the
6505/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006506void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6507 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006508 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006509 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006510 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006511 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6512 T->hasUnsignedIntegerRepresentation());
6513 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006514 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006515 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006516 return;
6517
Eli Friedman07185912013-08-29 23:44:43 +00006518 // FIXME: Force the precision of the source value down so we don't print
6519 // digits which are usually useless (we don't really care here if we
6520 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6521 // would automatically print the shortest representation, but it's a bit
6522 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006523 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006524 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6525 precision = (precision * 59 + 195) / 196;
6526 Value.toString(PrettySourceValue, precision);
6527
David Blaikie9b88cc02012-05-15 17:18:27 +00006528 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006529 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6530 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6531 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006532 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006533
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006534 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006535 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6536 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006537}
6538
John McCall18a2c2c2010-11-09 22:22:12 +00006539std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6540 if (!Range.Width) return "0";
6541
6542 llvm::APSInt ValueInRange = Value;
6543 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006544 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006545 return ValueInRange.toString(10);
6546}
6547
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006548static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6549 if (!isa<ImplicitCastExpr>(Ex))
6550 return false;
6551
6552 Expr *InnerE = Ex->IgnoreParenImpCasts();
6553 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6554 const Type *Source =
6555 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6556 if (Target->isDependentType())
6557 return false;
6558
6559 const BuiltinType *FloatCandidateBT =
6560 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6561 const Type *BoolCandidateType = ToBool ? Target : Source;
6562
6563 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6564 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6565}
6566
6567void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6568 SourceLocation CC) {
6569 unsigned NumArgs = TheCall->getNumArgs();
6570 for (unsigned i = 0; i < NumArgs; ++i) {
6571 Expr *CurrA = TheCall->getArg(i);
6572 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6573 continue;
6574
6575 bool IsSwapped = ((i > 0) &&
6576 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6577 IsSwapped |= ((i < (NumArgs - 1)) &&
6578 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6579 if (IsSwapped) {
6580 // Warn on this floating-point to bool conversion.
6581 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6582 CurrA->getType(), CC,
6583 diag::warn_impcast_floating_point_to_bool);
6584 }
6585 }
6586}
6587
Richard Trieu5b993502014-10-15 03:42:06 +00006588static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6589 SourceLocation CC) {
6590 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6591 E->getExprLoc()))
6592 return;
6593
6594 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6595 const Expr::NullPointerConstantKind NullKind =
6596 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6597 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6598 return;
6599
6600 // Return if target type is a safe conversion.
6601 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6602 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6603 return;
6604
6605 SourceLocation Loc = E->getSourceRange().getBegin();
6606
6607 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6608 if (NullKind == Expr::NPCK_GNUNull) {
6609 if (Loc.isMacroID())
6610 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6611 }
6612
6613 // Only warn if the null and context location are in the same macro expansion.
6614 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6615 return;
6616
6617 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6618 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6619 << FixItHint::CreateReplacement(Loc,
6620 S.getFixItZeroLiteralForType(T, Loc));
6621}
6622
John McCallcc7e5bf2010-05-06 08:58:33 +00006623void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006624 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006625 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006626
John McCallcc7e5bf2010-05-06 08:58:33 +00006627 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6628 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6629 if (Source == Target) return;
6630 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006631
Chandler Carruthc22845a2011-07-26 05:40:03 +00006632 // If the conversion context location is invalid don't complain. We also
6633 // don't want to emit a warning if the issue occurs from the expansion of
6634 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6635 // delay this check as long as possible. Once we detect we are in that
6636 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006637 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006638 return;
6639
Richard Trieu021baa32011-09-23 20:10:00 +00006640 // Diagnose implicit casts to bool.
6641 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6642 if (isa<StringLiteral>(E))
6643 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006644 // and expressions, for instance, assert(0 && "error here"), are
6645 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006646 return DiagnoseImpCast(S, E, T, CC,
6647 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006648 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6649 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6650 // This covers the literal expressions that evaluate to Objective-C
6651 // objects.
6652 return DiagnoseImpCast(S, E, T, CC,
6653 diag::warn_impcast_objective_c_literal_to_bool);
6654 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006655 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6656 // Warn on pointer to bool conversion that is always true.
6657 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6658 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006659 }
Richard Trieu021baa32011-09-23 20:10:00 +00006660 }
John McCall263a48b2010-01-04 23:31:57 +00006661
6662 // Strip vector types.
6663 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006664 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006665 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006666 return;
John McCallacf0ee52010-10-08 02:01:28 +00006667 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006668 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006669
6670 // If the vector cast is cast between two vectors of the same size, it is
6671 // a bitcast, not a conversion.
6672 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6673 return;
John McCall263a48b2010-01-04 23:31:57 +00006674
6675 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6676 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6677 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006678 if (auto VecTy = dyn_cast<VectorType>(Target))
6679 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006680
6681 // Strip complex types.
6682 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006683 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006684 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006685 return;
6686
John McCallacf0ee52010-10-08 02:01:28 +00006687 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006688 }
John McCall263a48b2010-01-04 23:31:57 +00006689
6690 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6691 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6692 }
6693
6694 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6695 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6696
6697 // If the source is floating point...
6698 if (SourceBT && SourceBT->isFloatingPoint()) {
6699 // ...and the target is floating point...
6700 if (TargetBT && TargetBT->isFloatingPoint()) {
6701 // ...then warn if we're dropping FP rank.
6702
6703 // Builtin FP kinds are ordered by increasing FP rank.
6704 if (SourceBT->getKind() > TargetBT->getKind()) {
6705 // Don't warn about float constants that are precisely
6706 // representable in the target type.
6707 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006708 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006709 // Value might be a float, a float vector, or a float complex.
6710 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006711 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6712 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006713 return;
6714 }
6715
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006716 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006717 return;
6718
John McCallacf0ee52010-10-08 02:01:28 +00006719 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006720 }
6721 return;
6722 }
6723
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006724 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006725 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006726 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006727 return;
6728
Chandler Carruth22c7a792011-02-17 11:05:49 +00006729 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006730 // We also want to warn on, e.g., "int i = -1.234"
6731 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6732 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6733 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6734
Chandler Carruth016ef402011-04-10 08:36:24 +00006735 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6736 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006737 } else {
6738 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6739 }
6740 }
John McCall263a48b2010-01-04 23:31:57 +00006741
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006742 // If the target is bool, warn if expr is a function or method call.
6743 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6744 isa<CallExpr>(E)) {
6745 // Check last argument of function call to see if it is an
6746 // implicit cast from a type matching the type the result
6747 // is being cast to.
6748 CallExpr *CEx = cast<CallExpr>(E);
6749 unsigned NumArgs = CEx->getNumArgs();
6750 if (NumArgs > 0) {
6751 Expr *LastA = CEx->getArg(NumArgs - 1);
6752 Expr *InnerE = LastA->IgnoreParenImpCasts();
6753 const Type *InnerType =
6754 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6755 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6756 // Warn on this floating-point to bool conversion
6757 DiagnoseImpCast(S, E, T, CC,
6758 diag::warn_impcast_floating_point_to_bool);
6759 }
6760 }
6761 }
John McCall263a48b2010-01-04 23:31:57 +00006762 return;
6763 }
6764
Richard Trieu5b993502014-10-15 03:42:06 +00006765 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006766
David Blaikie9366d2b2012-06-19 21:19:06 +00006767 if (!Source->isIntegerType() || !Target->isIntegerType())
6768 return;
6769
David Blaikie7555b6a2012-05-15 16:56:36 +00006770 // TODO: remove this early return once the false positives for constant->bool
6771 // in templates, macros, etc, are reduced or removed.
6772 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6773 return;
6774
John McCallcc7e5bf2010-05-06 08:58:33 +00006775 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006776 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006777
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006778 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006779 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006780 // TODO: this should happen for bitfield stores, too.
6781 llvm::APSInt Value(32);
6782 if (E->isIntegerConstantExpr(Value, S.Context)) {
6783 if (S.SourceMgr.isInSystemMacro(CC))
6784 return;
6785
John McCall18a2c2c2010-11-09 22:22:12 +00006786 std::string PrettySourceValue = Value.toString(10);
6787 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006788
Ted Kremenek33ba9952011-10-22 02:37:33 +00006789 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6790 S.PDiag(diag::warn_impcast_integer_precision_constant)
6791 << PrettySourceValue << PrettyTargetValue
6792 << E->getType() << T << E->getSourceRange()
6793 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006794 return;
6795 }
6796
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006797 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6798 if (S.SourceMgr.isInSystemMacro(CC))
6799 return;
6800
David Blaikie9455da02012-04-12 22:40:54 +00006801 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006802 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6803 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006804 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006805 }
6806
6807 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6808 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6809 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006810
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006811 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006812 return;
6813
John McCallcc7e5bf2010-05-06 08:58:33 +00006814 unsigned DiagID = diag::warn_impcast_integer_sign;
6815
6816 // Traditionally, gcc has warned about this under -Wsign-compare.
6817 // We also want to warn about it in -Wconversion.
6818 // So if -Wconversion is off, use a completely identical diagnostic
6819 // in the sign-compare group.
6820 // The conditional-checking code will
6821 if (ICContext) {
6822 DiagID = diag::warn_impcast_integer_sign_conditional;
6823 *ICContext = true;
6824 }
6825
John McCallacf0ee52010-10-08 02:01:28 +00006826 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006827 }
6828
Douglas Gregora78f1932011-02-22 02:45:07 +00006829 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006830 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6831 // type, to give us better diagnostics.
6832 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006833 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006834 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6835 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6836 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6837 SourceType = S.Context.getTypeDeclType(Enum);
6838 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6839 }
6840 }
6841
Douglas Gregora78f1932011-02-22 02:45:07 +00006842 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6843 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006844 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6845 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006846 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006847 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006848 return;
6849
Douglas Gregor364f7db2011-03-12 00:14:31 +00006850 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006851 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006852 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006853
John McCall263a48b2010-01-04 23:31:57 +00006854 return;
6855}
6856
David Blaikie18e9ac72012-05-15 21:57:38 +00006857void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6858 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006859
6860void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006861 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006862 E = E->IgnoreParenImpCasts();
6863
6864 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006865 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006866
John McCallacf0ee52010-10-08 02:01:28 +00006867 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006868 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006869 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006870 return;
6871}
6872
David Blaikie18e9ac72012-05-15 21:57:38 +00006873void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6874 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006875 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006876
6877 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006878 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6879 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006880
6881 // If -Wconversion would have warned about either of the candidates
6882 // for a signedness conversion to the context type...
6883 if (!Suspicious) return;
6884
6885 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006886 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006887 return;
6888
John McCallcc7e5bf2010-05-06 08:58:33 +00006889 // ...then check whether it would have warned about either of the
6890 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006891 if (E->getType() == T) return;
6892
6893 Suspicious = false;
6894 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6895 E->getType(), CC, &Suspicious);
6896 if (!Suspicious)
6897 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006898 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006899}
6900
Richard Trieu65724892014-11-15 06:37:39 +00006901/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6902/// Input argument E is a logical expression.
6903static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6904 if (S.getLangOpts().Bool)
6905 return;
6906 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6907}
6908
John McCallcc7e5bf2010-05-06 08:58:33 +00006909/// AnalyzeImplicitConversions - Find and report any interesting
6910/// implicit conversions in the given expression. There are a couple
6911/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006912void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006913 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006914 Expr *E = OrigE->IgnoreParenImpCasts();
6915
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006916 if (E->isTypeDependent() || E->isValueDependent())
6917 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006918
John McCallcc7e5bf2010-05-06 08:58:33 +00006919 // For conditional operators, we analyze the arguments as if they
6920 // were being fed directly into the output.
6921 if (isa<ConditionalOperator>(E)) {
6922 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006923 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006924 return;
6925 }
6926
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006927 // Check implicit argument conversions for function calls.
6928 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6929 CheckImplicitArgumentConversions(S, Call, CC);
6930
John McCallcc7e5bf2010-05-06 08:58:33 +00006931 // Go ahead and check any implicit conversions we might have skipped.
6932 // The non-canonical typecheck is just an optimization;
6933 // CheckImplicitConversion will filter out dead implicit conversions.
6934 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006935 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006936
6937 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006938
6939 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006940 if (POE->getResultExpr())
6941 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006942 }
6943
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006944 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6945 if (OVE->getSourceExpr())
6946 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6947 return;
6948 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006949
John McCallcc7e5bf2010-05-06 08:58:33 +00006950 // Skip past explicit casts.
6951 if (isa<ExplicitCastExpr>(E)) {
6952 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006953 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006954 }
6955
John McCalld2a53122010-11-09 23:24:47 +00006956 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6957 // Do a somewhat different check with comparison operators.
6958 if (BO->isComparisonOp())
6959 return AnalyzeComparison(S, BO);
6960
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006961 // And with simple assignments.
6962 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006963 return AnalyzeAssignment(S, BO);
6964 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006965
6966 // These break the otherwise-useful invariant below. Fortunately,
6967 // we don't really need to recurse into them, because any internal
6968 // expressions should have been analyzed already when they were
6969 // built into statements.
6970 if (isa<StmtExpr>(E)) return;
6971
6972 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006973 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006974
6975 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006976 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006977 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006978 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006979 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006980 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006981 if (!ChildExpr)
6982 continue;
6983
Richard Trieu955231d2014-01-25 01:10:35 +00006984 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006985 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006986 // Ignore checking string literals that are in logical and operators.
6987 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006988 continue;
6989 AnalyzeImplicitConversions(S, ChildExpr, CC);
6990 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006991
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006992 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006993 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6994 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006995 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006996
6997 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6998 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006999 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007000 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007001
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007002 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7003 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007004 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007005}
7006
7007} // end anonymous namespace
7008
Richard Trieu3bb8b562014-02-26 02:36:06 +00007009enum {
7010 AddressOf,
7011 FunctionPointer,
7012 ArrayPointer
7013};
7014
Richard Trieuc1888e02014-06-28 23:25:37 +00007015// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7016// Returns true when emitting a warning about taking the address of a reference.
7017static bool CheckForReference(Sema &SemaRef, const Expr *E,
7018 PartialDiagnostic PD) {
7019 E = E->IgnoreParenImpCasts();
7020
7021 const FunctionDecl *FD = nullptr;
7022
7023 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7024 if (!DRE->getDecl()->getType()->isReferenceType())
7025 return false;
7026 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7027 if (!M->getMemberDecl()->getType()->isReferenceType())
7028 return false;
7029 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007030 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007031 return false;
7032 FD = Call->getDirectCallee();
7033 } else {
7034 return false;
7035 }
7036
7037 SemaRef.Diag(E->getExprLoc(), PD);
7038
7039 // If possible, point to location of function.
7040 if (FD) {
7041 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7042 }
7043
7044 return true;
7045}
7046
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007047// Returns true if the SourceLocation is expanded from any macro body.
7048// Returns false if the SourceLocation is invalid, is from not in a macro
7049// expansion, or is from expanded from a top-level macro argument.
7050static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7051 if (Loc.isInvalid())
7052 return false;
7053
7054 while (Loc.isMacroID()) {
7055 if (SM.isMacroBodyExpansion(Loc))
7056 return true;
7057 Loc = SM.getImmediateMacroCallerLoc(Loc);
7058 }
7059
7060 return false;
7061}
7062
Richard Trieu3bb8b562014-02-26 02:36:06 +00007063/// \brief Diagnose pointers that are always non-null.
7064/// \param E the expression containing the pointer
7065/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7066/// compared to a null pointer
7067/// \param IsEqual True when the comparison is equal to a null pointer
7068/// \param Range Extra SourceRange to highlight in the diagnostic
7069void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7070 Expr::NullPointerConstantKind NullKind,
7071 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007072 if (!E)
7073 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007074
7075 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007076 if (E->getExprLoc().isMacroID()) {
7077 const SourceManager &SM = getSourceManager();
7078 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7079 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007080 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007081 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007082 E = E->IgnoreImpCasts();
7083
7084 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7085
Richard Trieuf7432752014-06-06 21:39:26 +00007086 if (isa<CXXThisExpr>(E)) {
7087 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7088 : diag::warn_this_bool_conversion;
7089 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7090 return;
7091 }
7092
Richard Trieu3bb8b562014-02-26 02:36:06 +00007093 bool IsAddressOf = false;
7094
7095 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7096 if (UO->getOpcode() != UO_AddrOf)
7097 return;
7098 IsAddressOf = true;
7099 E = UO->getSubExpr();
7100 }
7101
Richard Trieuc1888e02014-06-28 23:25:37 +00007102 if (IsAddressOf) {
7103 unsigned DiagID = IsCompare
7104 ? diag::warn_address_of_reference_null_compare
7105 : diag::warn_address_of_reference_bool_conversion;
7106 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7107 << IsEqual;
7108 if (CheckForReference(*this, E, PD)) {
7109 return;
7110 }
7111 }
7112
Richard Trieu3bb8b562014-02-26 02:36:06 +00007113 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007114 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007115 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7116 D = R->getDecl();
7117 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7118 D = M->getMemberDecl();
7119 }
7120
7121 // Weak Decls can be null.
7122 if (!D || D->isWeak())
7123 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007124
7125 // Check for parameter decl with nonnull attribute
7126 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7127 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7128 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7129 unsigned NumArgs = FD->getNumParams();
7130 llvm::SmallBitVector AttrNonNull(NumArgs);
7131 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7132 if (!NonNull->args_size()) {
7133 AttrNonNull.set(0, NumArgs);
7134 break;
7135 }
7136 for (unsigned Val : NonNull->args()) {
7137 if (Val >= NumArgs)
7138 continue;
7139 AttrNonNull.set(Val);
7140 }
7141 }
7142 if (!AttrNonNull.empty())
7143 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007144 if (FD->getParamDecl(i) == PV &&
7145 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007146 std::string Str;
7147 llvm::raw_string_ostream S(Str);
7148 E->printPretty(S, nullptr, getPrintingPolicy());
7149 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7150 : diag::warn_cast_nonnull_to_bool;
7151 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7152 << Range << IsEqual;
7153 return;
7154 }
7155 }
7156 }
7157
Richard Trieu3bb8b562014-02-26 02:36:06 +00007158 QualType T = D->getType();
7159 const bool IsArray = T->isArrayType();
7160 const bool IsFunction = T->isFunctionType();
7161
Richard Trieuc1888e02014-06-28 23:25:37 +00007162 // Address of function is used to silence the function warning.
7163 if (IsAddressOf && IsFunction) {
7164 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007165 }
7166
7167 // Found nothing.
7168 if (!IsAddressOf && !IsFunction && !IsArray)
7169 return;
7170
7171 // Pretty print the expression for the diagnostic.
7172 std::string Str;
7173 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007174 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007175
7176 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7177 : diag::warn_impcast_pointer_to_bool;
7178 unsigned DiagType;
7179 if (IsAddressOf)
7180 DiagType = AddressOf;
7181 else if (IsFunction)
7182 DiagType = FunctionPointer;
7183 else if (IsArray)
7184 DiagType = ArrayPointer;
7185 else
7186 llvm_unreachable("Could not determine diagnostic.");
7187 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7188 << Range << IsEqual;
7189
7190 if (!IsFunction)
7191 return;
7192
7193 // Suggest '&' to silence the function warning.
7194 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7195 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7196
7197 // Check to see if '()' fixit should be emitted.
7198 QualType ReturnType;
7199 UnresolvedSet<4> NonTemplateOverloads;
7200 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7201 if (ReturnType.isNull())
7202 return;
7203
7204 if (IsCompare) {
7205 // There are two cases here. If there is null constant, the only suggest
7206 // for a pointer return type. If the null is 0, then suggest if the return
7207 // type is a pointer or an integer type.
7208 if (!ReturnType->isPointerType()) {
7209 if (NullKind == Expr::NPCK_ZeroExpression ||
7210 NullKind == Expr::NPCK_ZeroLiteral) {
7211 if (!ReturnType->isIntegerType())
7212 return;
7213 } else {
7214 return;
7215 }
7216 }
7217 } else { // !IsCompare
7218 // For function to bool, only suggest if the function pointer has bool
7219 // return type.
7220 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7221 return;
7222 }
7223 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007224 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007225}
7226
7227
John McCallcc7e5bf2010-05-06 08:58:33 +00007228/// Diagnoses "dangerous" implicit conversions within the given
7229/// expression (which is a full expression). Implements -Wconversion
7230/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007231///
7232/// \param CC the "context" location of the implicit conversion, i.e.
7233/// the most location of the syntactic entity requiring the implicit
7234/// conversion
7235void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007236 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007237 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007238 return;
7239
7240 // Don't diagnose for value- or type-dependent expressions.
7241 if (E->isTypeDependent() || E->isValueDependent())
7242 return;
7243
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007244 // Check for array bounds violations in cases where the check isn't triggered
7245 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7246 // ArraySubscriptExpr is on the RHS of a variable initialization.
7247 CheckArrayAccess(E);
7248
John McCallacf0ee52010-10-08 02:01:28 +00007249 // This is not the right CC for (e.g.) a variable initialization.
7250 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007251}
7252
Richard Trieu65724892014-11-15 06:37:39 +00007253/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7254/// Input argument E is a logical expression.
7255void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7256 ::CheckBoolLikeConversion(*this, E, CC);
7257}
7258
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007259/// Diagnose when expression is an integer constant expression and its evaluation
7260/// results in integer overflow
7261void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007262 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7263 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007264}
7265
Richard Smithc406cb72013-01-17 01:17:56 +00007266namespace {
7267/// \brief Visitor for expressions which looks for unsequenced operations on the
7268/// same object.
7269class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007270 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7271
Richard Smithc406cb72013-01-17 01:17:56 +00007272 /// \brief A tree of sequenced regions within an expression. Two regions are
7273 /// unsequenced if one is an ancestor or a descendent of the other. When we
7274 /// finish processing an expression with sequencing, such as a comma
7275 /// expression, we fold its tree nodes into its parent, since they are
7276 /// unsequenced with respect to nodes we will visit later.
7277 class SequenceTree {
7278 struct Value {
7279 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7280 unsigned Parent : 31;
7281 bool Merged : 1;
7282 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007283 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007284
7285 public:
7286 /// \brief A region within an expression which may be sequenced with respect
7287 /// to some other region.
7288 class Seq {
7289 explicit Seq(unsigned N) : Index(N) {}
7290 unsigned Index;
7291 friend class SequenceTree;
7292 public:
7293 Seq() : Index(0) {}
7294 };
7295
7296 SequenceTree() { Values.push_back(Value(0)); }
7297 Seq root() const { return Seq(0); }
7298
7299 /// \brief Create a new sequence of operations, which is an unsequenced
7300 /// subset of \p Parent. This sequence of operations is sequenced with
7301 /// respect to other children of \p Parent.
7302 Seq allocate(Seq Parent) {
7303 Values.push_back(Value(Parent.Index));
7304 return Seq(Values.size() - 1);
7305 }
7306
7307 /// \brief Merge a sequence of operations into its parent.
7308 void merge(Seq S) {
7309 Values[S.Index].Merged = true;
7310 }
7311
7312 /// \brief Determine whether two operations are unsequenced. This operation
7313 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7314 /// should have been merged into its parent as appropriate.
7315 bool isUnsequenced(Seq Cur, Seq Old) {
7316 unsigned C = representative(Cur.Index);
7317 unsigned Target = representative(Old.Index);
7318 while (C >= Target) {
7319 if (C == Target)
7320 return true;
7321 C = Values[C].Parent;
7322 }
7323 return false;
7324 }
7325
7326 private:
7327 /// \brief Pick a representative for a sequence.
7328 unsigned representative(unsigned K) {
7329 if (Values[K].Merged)
7330 // Perform path compression as we go.
7331 return Values[K].Parent = representative(Values[K].Parent);
7332 return K;
7333 }
7334 };
7335
7336 /// An object for which we can track unsequenced uses.
7337 typedef NamedDecl *Object;
7338
7339 /// Different flavors of object usage which we track. We only track the
7340 /// least-sequenced usage of each kind.
7341 enum UsageKind {
7342 /// A read of an object. Multiple unsequenced reads are OK.
7343 UK_Use,
7344 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007345 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007346 UK_ModAsValue,
7347 /// A modification of an object which is not sequenced before the value
7348 /// computation of the expression, such as n++.
7349 UK_ModAsSideEffect,
7350
7351 UK_Count = UK_ModAsSideEffect + 1
7352 };
7353
7354 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007355 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007356 Expr *Use;
7357 SequenceTree::Seq Seq;
7358 };
7359
7360 struct UsageInfo {
7361 UsageInfo() : Diagnosed(false) {}
7362 Usage Uses[UK_Count];
7363 /// Have we issued a diagnostic for this variable already?
7364 bool Diagnosed;
7365 };
7366 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7367
7368 Sema &SemaRef;
7369 /// Sequenced regions within the expression.
7370 SequenceTree Tree;
7371 /// Declaration modifications and references which we have seen.
7372 UsageInfoMap UsageMap;
7373 /// The region we are currently within.
7374 SequenceTree::Seq Region;
7375 /// Filled in with declarations which were modified as a side-effect
7376 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007377 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007378 /// Expressions to check later. We defer checking these to reduce
7379 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007380 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007381
7382 /// RAII object wrapping the visitation of a sequenced subexpression of an
7383 /// expression. At the end of this process, the side-effects of the evaluation
7384 /// become sequenced with respect to the value computation of the result, so
7385 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7386 /// UK_ModAsValue.
7387 struct SequencedSubexpression {
7388 SequencedSubexpression(SequenceChecker &Self)
7389 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7390 Self.ModAsSideEffect = &ModAsSideEffect;
7391 }
7392 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007393 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7394 MI != ME; ++MI) {
7395 UsageInfo &U = Self.UsageMap[MI->first];
7396 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7397 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7398 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007399 }
7400 Self.ModAsSideEffect = OldModAsSideEffect;
7401 }
7402
7403 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007404 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7405 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007406 };
7407
Richard Smith40238f02013-06-20 22:21:56 +00007408 /// RAII object wrapping the visitation of a subexpression which we might
7409 /// choose to evaluate as a constant. If any subexpression is evaluated and
7410 /// found to be non-constant, this allows us to suppress the evaluation of
7411 /// the outer expression.
7412 class EvaluationTracker {
7413 public:
7414 EvaluationTracker(SequenceChecker &Self)
7415 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7416 Self.EvalTracker = this;
7417 }
7418 ~EvaluationTracker() {
7419 Self.EvalTracker = Prev;
7420 if (Prev)
7421 Prev->EvalOK &= EvalOK;
7422 }
7423
7424 bool evaluate(const Expr *E, bool &Result) {
7425 if (!EvalOK || E->isValueDependent())
7426 return false;
7427 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7428 return EvalOK;
7429 }
7430
7431 private:
7432 SequenceChecker &Self;
7433 EvaluationTracker *Prev;
7434 bool EvalOK;
7435 } *EvalTracker;
7436
Richard Smithc406cb72013-01-17 01:17:56 +00007437 /// \brief Find the object which is produced by the specified expression,
7438 /// if any.
7439 Object getObject(Expr *E, bool Mod) const {
7440 E = E->IgnoreParenCasts();
7441 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7442 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7443 return getObject(UO->getSubExpr(), Mod);
7444 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7445 if (BO->getOpcode() == BO_Comma)
7446 return getObject(BO->getRHS(), Mod);
7447 if (Mod && BO->isAssignmentOp())
7448 return getObject(BO->getLHS(), Mod);
7449 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7450 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7451 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7452 return ME->getMemberDecl();
7453 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7454 // FIXME: If this is a reference, map through to its value.
7455 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007456 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007457 }
7458
7459 /// \brief Note that an object was modified or used by an expression.
7460 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7461 Usage &U = UI.Uses[UK];
7462 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7463 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7464 ModAsSideEffect->push_back(std::make_pair(O, U));
7465 U.Use = Ref;
7466 U.Seq = Region;
7467 }
7468 }
7469 /// \brief Check whether a modification or use conflicts with a prior usage.
7470 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7471 bool IsModMod) {
7472 if (UI.Diagnosed)
7473 return;
7474
7475 const Usage &U = UI.Uses[OtherKind];
7476 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7477 return;
7478
7479 Expr *Mod = U.Use;
7480 Expr *ModOrUse = Ref;
7481 if (OtherKind == UK_Use)
7482 std::swap(Mod, ModOrUse);
7483
7484 SemaRef.Diag(Mod->getExprLoc(),
7485 IsModMod ? diag::warn_unsequenced_mod_mod
7486 : diag::warn_unsequenced_mod_use)
7487 << O << SourceRange(ModOrUse->getExprLoc());
7488 UI.Diagnosed = true;
7489 }
7490
7491 void notePreUse(Object O, Expr *Use) {
7492 UsageInfo &U = UsageMap[O];
7493 // Uses conflict with other modifications.
7494 checkUsage(O, U, Use, UK_ModAsValue, false);
7495 }
7496 void notePostUse(Object O, Expr *Use) {
7497 UsageInfo &U = UsageMap[O];
7498 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7499 addUsage(U, O, Use, UK_Use);
7500 }
7501
7502 void notePreMod(Object O, Expr *Mod) {
7503 UsageInfo &U = UsageMap[O];
7504 // Modifications conflict with other modifications and with uses.
7505 checkUsage(O, U, Mod, UK_ModAsValue, true);
7506 checkUsage(O, U, Mod, UK_Use, false);
7507 }
7508 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7509 UsageInfo &U = UsageMap[O];
7510 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7511 addUsage(U, O, Use, UK);
7512 }
7513
7514public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007515 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007516 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7517 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007518 Visit(E);
7519 }
7520
7521 void VisitStmt(Stmt *S) {
7522 // Skip all statements which aren't expressions for now.
7523 }
7524
7525 void VisitExpr(Expr *E) {
7526 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007527 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007528 }
7529
7530 void VisitCastExpr(CastExpr *E) {
7531 Object O = Object();
7532 if (E->getCastKind() == CK_LValueToRValue)
7533 O = getObject(E->getSubExpr(), false);
7534
7535 if (O)
7536 notePreUse(O, E);
7537 VisitExpr(E);
7538 if (O)
7539 notePostUse(O, E);
7540 }
7541
7542 void VisitBinComma(BinaryOperator *BO) {
7543 // C++11 [expr.comma]p1:
7544 // Every value computation and side effect associated with the left
7545 // expression is sequenced before every value computation and side
7546 // effect associated with the right expression.
7547 SequenceTree::Seq LHS = Tree.allocate(Region);
7548 SequenceTree::Seq RHS = Tree.allocate(Region);
7549 SequenceTree::Seq OldRegion = Region;
7550
7551 {
7552 SequencedSubexpression SeqLHS(*this);
7553 Region = LHS;
7554 Visit(BO->getLHS());
7555 }
7556
7557 Region = RHS;
7558 Visit(BO->getRHS());
7559
7560 Region = OldRegion;
7561
7562 // Forget that LHS and RHS are sequenced. They are both unsequenced
7563 // with respect to other stuff.
7564 Tree.merge(LHS);
7565 Tree.merge(RHS);
7566 }
7567
7568 void VisitBinAssign(BinaryOperator *BO) {
7569 // The modification is sequenced after the value computation of the LHS
7570 // and RHS, so check it before inspecting the operands and update the
7571 // map afterwards.
7572 Object O = getObject(BO->getLHS(), true);
7573 if (!O)
7574 return VisitExpr(BO);
7575
7576 notePreMod(O, BO);
7577
7578 // C++11 [expr.ass]p7:
7579 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7580 // only once.
7581 //
7582 // Therefore, for a compound assignment operator, O is considered used
7583 // everywhere except within the evaluation of E1 itself.
7584 if (isa<CompoundAssignOperator>(BO))
7585 notePreUse(O, BO);
7586
7587 Visit(BO->getLHS());
7588
7589 if (isa<CompoundAssignOperator>(BO))
7590 notePostUse(O, BO);
7591
7592 Visit(BO->getRHS());
7593
Richard Smith83e37bee2013-06-26 23:16:51 +00007594 // C++11 [expr.ass]p1:
7595 // the assignment is sequenced [...] before the value computation of the
7596 // assignment expression.
7597 // C11 6.5.16/3 has no such rule.
7598 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7599 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007600 }
7601 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7602 VisitBinAssign(CAO);
7603 }
7604
7605 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7606 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7607 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7608 Object O = getObject(UO->getSubExpr(), true);
7609 if (!O)
7610 return VisitExpr(UO);
7611
7612 notePreMod(O, UO);
7613 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007614 // C++11 [expr.pre.incr]p1:
7615 // the expression ++x is equivalent to x+=1
7616 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7617 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007618 }
7619
7620 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7621 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7622 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7623 Object O = getObject(UO->getSubExpr(), true);
7624 if (!O)
7625 return VisitExpr(UO);
7626
7627 notePreMod(O, UO);
7628 Visit(UO->getSubExpr());
7629 notePostMod(O, UO, UK_ModAsSideEffect);
7630 }
7631
7632 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7633 void VisitBinLOr(BinaryOperator *BO) {
7634 // The side-effects of the LHS of an '&&' are sequenced before the
7635 // value computation of the RHS, and hence before the value computation
7636 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7637 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007638 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007639 {
7640 SequencedSubexpression Sequenced(*this);
7641 Visit(BO->getLHS());
7642 }
7643
7644 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007645 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007646 if (!Result)
7647 Visit(BO->getRHS());
7648 } else {
7649 // Check for unsequenced operations in the RHS, treating it as an
7650 // entirely separate evaluation.
7651 //
7652 // FIXME: If there are operations in the RHS which are unsequenced
7653 // with respect to operations outside the RHS, and those operations
7654 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007655 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007656 }
Richard Smithc406cb72013-01-17 01:17:56 +00007657 }
7658 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007659 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007660 {
7661 SequencedSubexpression Sequenced(*this);
7662 Visit(BO->getLHS());
7663 }
7664
7665 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007666 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007667 if (Result)
7668 Visit(BO->getRHS());
7669 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007670 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007671 }
Richard Smithc406cb72013-01-17 01:17:56 +00007672 }
7673
7674 // Only visit the condition, unless we can be sure which subexpression will
7675 // be chosen.
7676 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007677 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007678 {
7679 SequencedSubexpression Sequenced(*this);
7680 Visit(CO->getCond());
7681 }
Richard Smithc406cb72013-01-17 01:17:56 +00007682
7683 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007684 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007685 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007686 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007687 WorkList.push_back(CO->getTrueExpr());
7688 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007689 }
Richard Smithc406cb72013-01-17 01:17:56 +00007690 }
7691
Richard Smithe3dbfe02013-06-30 10:40:20 +00007692 void VisitCallExpr(CallExpr *CE) {
7693 // C++11 [intro.execution]p15:
7694 // When calling a function [...], every value computation and side effect
7695 // associated with any argument expression, or with the postfix expression
7696 // designating the called function, is sequenced before execution of every
7697 // expression or statement in the body of the function [and thus before
7698 // the value computation of its result].
7699 SequencedSubexpression Sequenced(*this);
7700 Base::VisitCallExpr(CE);
7701
7702 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7703 }
7704
Richard Smithc406cb72013-01-17 01:17:56 +00007705 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007706 // This is a call, so all subexpressions are sequenced before the result.
7707 SequencedSubexpression Sequenced(*this);
7708
Richard Smithc406cb72013-01-17 01:17:56 +00007709 if (!CCE->isListInitialization())
7710 return VisitExpr(CCE);
7711
7712 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007713 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007714 SequenceTree::Seq Parent = Region;
7715 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7716 E = CCE->arg_end();
7717 I != E; ++I) {
7718 Region = Tree.allocate(Parent);
7719 Elts.push_back(Region);
7720 Visit(*I);
7721 }
7722
7723 // Forget that the initializers are sequenced.
7724 Region = Parent;
7725 for (unsigned I = 0; I < Elts.size(); ++I)
7726 Tree.merge(Elts[I]);
7727 }
7728
7729 void VisitInitListExpr(InitListExpr *ILE) {
7730 if (!SemaRef.getLangOpts().CPlusPlus11)
7731 return VisitExpr(ILE);
7732
7733 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007734 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007735 SequenceTree::Seq Parent = Region;
7736 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7737 Expr *E = ILE->getInit(I);
7738 if (!E) continue;
7739 Region = Tree.allocate(Parent);
7740 Elts.push_back(Region);
7741 Visit(E);
7742 }
7743
7744 // Forget that the initializers are sequenced.
7745 Region = Parent;
7746 for (unsigned I = 0; I < Elts.size(); ++I)
7747 Tree.merge(Elts[I]);
7748 }
7749};
7750}
7751
7752void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007753 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007754 WorkList.push_back(E);
7755 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007756 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007757 SequenceChecker(*this, Item, WorkList);
7758 }
Richard Smithc406cb72013-01-17 01:17:56 +00007759}
7760
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007761void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7762 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007763 CheckImplicitConversions(E, CheckLoc);
7764 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007765 if (!IsConstexpr && !E->isValueDependent())
7766 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007767}
7768
John McCall1f425642010-11-11 03:21:53 +00007769void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7770 FieldDecl *BitField,
7771 Expr *Init) {
7772 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7773}
7774
David Majnemer61a5bbf2015-04-07 22:08:51 +00007775static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7776 SourceLocation Loc) {
7777 if (!PType->isVariablyModifiedType())
7778 return;
7779 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7780 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7781 return;
7782 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00007783 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7784 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7785 return;
7786 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00007787 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7788 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7789 return;
7790 }
7791
7792 const ArrayType *AT = S.Context.getAsArrayType(PType);
7793 if (!AT)
7794 return;
7795
7796 if (AT->getSizeModifier() != ArrayType::Star) {
7797 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7798 return;
7799 }
7800
7801 S.Diag(Loc, diag::err_array_star_in_function_definition);
7802}
7803
Mike Stump0c2ec772010-01-21 03:59:47 +00007804/// CheckParmsForFunctionDef - Check that the parameters of the given
7805/// function are appropriate for the definition of a function. This
7806/// takes care of any checks that cannot be performed on the
7807/// declaration itself, e.g., that the types of each of the function
7808/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007809bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7810 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007811 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007812 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007813 for (; P != PEnd; ++P) {
7814 ParmVarDecl *Param = *P;
7815
Mike Stump0c2ec772010-01-21 03:59:47 +00007816 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7817 // function declarator that is part of a function definition of
7818 // that function shall not have incomplete type.
7819 //
7820 // This is also C++ [dcl.fct]p6.
7821 if (!Param->isInvalidDecl() &&
7822 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007823 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007824 Param->setInvalidDecl();
7825 HasInvalidParm = true;
7826 }
7827
7828 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7829 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007830 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007831 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007832 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007833 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007834 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007835
7836 // C99 6.7.5.3p12:
7837 // If the function declarator is not part of a definition of that
7838 // function, parameters may have incomplete type and may use the [*]
7839 // notation in their sequences of declarator specifiers to specify
7840 // variable length array types.
7841 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00007842 // FIXME: This diagnostic should point the '[*]' if source-location
7843 // information is added for it.
7844 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007845
7846 // MSVC destroys objects passed by value in the callee. Therefore a
7847 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007848 // object's destructor. However, we don't perform any direct access check
7849 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007850 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7851 .getCXXABI()
7852 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007853 if (!Param->isInvalidDecl()) {
7854 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7855 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7856 if (!ClassDecl->isInvalidDecl() &&
7857 !ClassDecl->hasIrrelevantDestructor() &&
7858 !ClassDecl->isDependentContext()) {
7859 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7860 MarkFunctionReferenced(Param->getLocation(), Destructor);
7861 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7862 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007863 }
7864 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007865 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007866 }
7867
7868 return HasInvalidParm;
7869}
John McCall2b5c1b22010-08-12 21:44:57 +00007870
7871/// CheckCastAlign - Implements -Wcast-align, which warns when a
7872/// pointer cast increases the alignment requirements.
7873void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7874 // This is actually a lot of work to potentially be doing on every
7875 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007876 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007877 return;
7878
7879 // Ignore dependent types.
7880 if (T->isDependentType() || Op->getType()->isDependentType())
7881 return;
7882
7883 // Require that the destination be a pointer type.
7884 const PointerType *DestPtr = T->getAs<PointerType>();
7885 if (!DestPtr) return;
7886
7887 // If the destination has alignment 1, we're done.
7888 QualType DestPointee = DestPtr->getPointeeType();
7889 if (DestPointee->isIncompleteType()) return;
7890 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7891 if (DestAlign.isOne()) return;
7892
7893 // Require that the source be a pointer type.
7894 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7895 if (!SrcPtr) return;
7896 QualType SrcPointee = SrcPtr->getPointeeType();
7897
7898 // Whitelist casts from cv void*. We already implicitly
7899 // whitelisted casts to cv void*, since they have alignment 1.
7900 // Also whitelist casts involving incomplete types, which implicitly
7901 // includes 'void'.
7902 if (SrcPointee->isIncompleteType()) return;
7903
7904 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7905 if (SrcAlign >= DestAlign) return;
7906
7907 Diag(TRange.getBegin(), diag::warn_cast_align)
7908 << Op->getType() << T
7909 << static_cast<unsigned>(SrcAlign.getQuantity())
7910 << static_cast<unsigned>(DestAlign.getQuantity())
7911 << TRange << Op->getSourceRange();
7912}
7913
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007914static const Type* getElementType(const Expr *BaseExpr) {
7915 const Type* EltType = BaseExpr->getType().getTypePtr();
7916 if (EltType->isAnyPointerType())
7917 return EltType->getPointeeType().getTypePtr();
7918 else if (EltType->isArrayType())
7919 return EltType->getBaseElementTypeUnsafe();
7920 return EltType;
7921}
7922
Chandler Carruth28389f02011-08-05 09:10:50 +00007923/// \brief Check whether this array fits the idiom of a size-one tail padded
7924/// array member of a struct.
7925///
7926/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7927/// commonly used to emulate flexible arrays in C89 code.
7928static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7929 const NamedDecl *ND) {
7930 if (Size != 1 || !ND) return false;
7931
7932 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7933 if (!FD) return false;
7934
7935 // Don't consider sizes resulting from macro expansions or template argument
7936 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007937
7938 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007939 while (TInfo) {
7940 TypeLoc TL = TInfo->getTypeLoc();
7941 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007942 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7943 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007944 TInfo = TDL->getTypeSourceInfo();
7945 continue;
7946 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007947 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7948 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007949 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7950 return false;
7951 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007952 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007953 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007954
7955 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007956 if (!RD) return false;
7957 if (RD->isUnion()) return false;
7958 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7959 if (!CRD->isStandardLayout()) return false;
7960 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007961
Benjamin Kramer8c543672011-08-06 03:04:42 +00007962 // See if this is the last field decl in the record.
7963 const Decl *D = FD;
7964 while ((D = D->getNextDeclInContext()))
7965 if (isa<FieldDecl>(D))
7966 return false;
7967 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007968}
7969
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007970void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007971 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007972 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007973 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007974 if (IndexExpr->isValueDependent())
7975 return;
7976
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007977 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007978 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007979 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007980 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007981 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007982 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007983
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007984 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007985 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007986 return;
Richard Smith13f67182011-12-16 19:31:14 +00007987 if (IndexNegated)
7988 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007989
Craig Topperc3ec1492014-05-26 06:22:03 +00007990 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007991 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7992 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007993 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007994 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007995
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007996 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007997 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007998 if (!size.isStrictlyPositive())
7999 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008000
8001 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008002 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008003 // Make sure we're comparing apples to apples when comparing index to size
8004 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8005 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008006 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008007 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008008 if (ptrarith_typesize != array_typesize) {
8009 // There's a cast to a different size type involved
8010 uint64_t ratio = array_typesize / ptrarith_typesize;
8011 // TODO: Be smarter about handling cases where array_typesize is not a
8012 // multiple of ptrarith_typesize
8013 if (ptrarith_typesize * ratio == array_typesize)
8014 size *= llvm::APInt(size.getBitWidth(), ratio);
8015 }
8016 }
8017
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008018 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008019 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008020 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008021 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008022
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008023 // For array subscripting the index must be less than size, but for pointer
8024 // arithmetic also allow the index (offset) to be equal to size since
8025 // computing the next address after the end of the array is legal and
8026 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008027 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008028 return;
8029
8030 // Also don't warn for arrays of size 1 which are members of some
8031 // structure. These are often used to approximate flexible arrays in C89
8032 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008033 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008034 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008035
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008036 // Suppress the warning if the subscript expression (as identified by the
8037 // ']' location) and the index expression are both from macro expansions
8038 // within a system header.
8039 if (ASE) {
8040 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8041 ASE->getRBracketLoc());
8042 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8043 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8044 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008045 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008046 return;
8047 }
8048 }
8049
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008050 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008051 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008052 DiagID = diag::warn_array_index_exceeds_bounds;
8053
8054 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8055 PDiag(DiagID) << index.toString(10, true)
8056 << size.toString(10, true)
8057 << (unsigned)size.getLimitedValue(~0U)
8058 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008059 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008060 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008061 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008062 DiagID = diag::warn_ptr_arith_precedes_bounds;
8063 if (index.isNegative()) index = -index;
8064 }
8065
8066 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8067 PDiag(DiagID) << index.toString(10, true)
8068 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008069 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008070
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008071 if (!ND) {
8072 // Try harder to find a NamedDecl to point at in the note.
8073 while (const ArraySubscriptExpr *ASE =
8074 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8075 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8077 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8078 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8079 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8080 }
8081
Chandler Carruth1af88f12011-02-17 21:10:52 +00008082 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008083 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8084 PDiag(diag::note_array_index_out_of_bounds)
8085 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008086}
8087
Ted Kremenekdf26df72011-03-01 18:41:00 +00008088void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008089 int AllowOnePastEnd = 0;
8090 while (expr) {
8091 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008092 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008093 case Stmt::ArraySubscriptExprClass: {
8094 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008095 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008096 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008097 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008098 }
8099 case Stmt::UnaryOperatorClass: {
8100 // Only unwrap the * and & unary operators
8101 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8102 expr = UO->getSubExpr();
8103 switch (UO->getOpcode()) {
8104 case UO_AddrOf:
8105 AllowOnePastEnd++;
8106 break;
8107 case UO_Deref:
8108 AllowOnePastEnd--;
8109 break;
8110 default:
8111 return;
8112 }
8113 break;
8114 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008115 case Stmt::ConditionalOperatorClass: {
8116 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8117 if (const Expr *lhs = cond->getLHS())
8118 CheckArrayAccess(lhs);
8119 if (const Expr *rhs = cond->getRHS())
8120 CheckArrayAccess(rhs);
8121 return;
8122 }
8123 default:
8124 return;
8125 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008126 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008127}
John McCall31168b02011-06-15 23:02:42 +00008128
8129//===--- CHECK: Objective-C retain cycles ----------------------------------//
8130
8131namespace {
8132 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008133 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008134 VarDecl *Variable;
8135 SourceRange Range;
8136 SourceLocation Loc;
8137 bool Indirect;
8138
8139 void setLocsFrom(Expr *e) {
8140 Loc = e->getExprLoc();
8141 Range = e->getSourceRange();
8142 }
8143 };
8144}
8145
8146/// Consider whether capturing the given variable can possibly lead to
8147/// a retain cycle.
8148static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008149 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008150 // lifetime. In MRR, it's captured strongly if the variable is
8151 // __block and has an appropriate type.
8152 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8153 return false;
8154
8155 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008156 if (ref)
8157 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008158 return true;
8159}
8160
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008161static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008162 while (true) {
8163 e = e->IgnoreParens();
8164 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8165 switch (cast->getCastKind()) {
8166 case CK_BitCast:
8167 case CK_LValueBitCast:
8168 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008169 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008170 e = cast->getSubExpr();
8171 continue;
8172
John McCall31168b02011-06-15 23:02:42 +00008173 default:
8174 return false;
8175 }
8176 }
8177
8178 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8179 ObjCIvarDecl *ivar = ref->getDecl();
8180 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8181 return false;
8182
8183 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008184 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008185 return false;
8186
8187 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8188 owner.Indirect = true;
8189 return true;
8190 }
8191
8192 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8193 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8194 if (!var) return false;
8195 return considerVariable(var, ref, owner);
8196 }
8197
John McCall31168b02011-06-15 23:02:42 +00008198 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8199 if (member->isArrow()) return false;
8200
8201 // Don't count this as an indirect ownership.
8202 e = member->getBase();
8203 continue;
8204 }
8205
John McCallfe96e0b2011-11-06 09:01:30 +00008206 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8207 // Only pay attention to pseudo-objects on property references.
8208 ObjCPropertyRefExpr *pre
8209 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8210 ->IgnoreParens());
8211 if (!pre) return false;
8212 if (pre->isImplicitProperty()) return false;
8213 ObjCPropertyDecl *property = pre->getExplicitProperty();
8214 if (!property->isRetaining() &&
8215 !(property->getPropertyIvarDecl() &&
8216 property->getPropertyIvarDecl()->getType()
8217 .getObjCLifetime() == Qualifiers::OCL_Strong))
8218 return false;
8219
8220 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008221 if (pre->isSuperReceiver()) {
8222 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8223 if (!owner.Variable)
8224 return false;
8225 owner.Loc = pre->getLocation();
8226 owner.Range = pre->getSourceRange();
8227 return true;
8228 }
John McCallfe96e0b2011-11-06 09:01:30 +00008229 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8230 ->getSourceExpr());
8231 continue;
8232 }
8233
John McCall31168b02011-06-15 23:02:42 +00008234 // Array ivars?
8235
8236 return false;
8237 }
8238}
8239
8240namespace {
8241 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8242 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8243 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008244 Context(Context), Variable(variable), Capturer(nullptr),
8245 VarWillBeReased(false) {}
8246 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008247 VarDecl *Variable;
8248 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008249 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008250
8251 void VisitDeclRefExpr(DeclRefExpr *ref) {
8252 if (ref->getDecl() == Variable && !Capturer)
8253 Capturer = ref;
8254 }
8255
John McCall31168b02011-06-15 23:02:42 +00008256 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8257 if (Capturer) return;
8258 Visit(ref->getBase());
8259 if (Capturer && ref->isFreeIvar())
8260 Capturer = ref;
8261 }
8262
8263 void VisitBlockExpr(BlockExpr *block) {
8264 // Look inside nested blocks
8265 if (block->getBlockDecl()->capturesVariable(Variable))
8266 Visit(block->getBlockDecl()->getBody());
8267 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008268
8269 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8270 if (Capturer) return;
8271 if (OVE->getSourceExpr())
8272 Visit(OVE->getSourceExpr());
8273 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008274 void VisitBinaryOperator(BinaryOperator *BinOp) {
8275 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8276 return;
8277 Expr *LHS = BinOp->getLHS();
8278 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8279 if (DRE->getDecl() != Variable)
8280 return;
8281 if (Expr *RHS = BinOp->getRHS()) {
8282 RHS = RHS->IgnoreParenCasts();
8283 llvm::APSInt Value;
8284 VarWillBeReased =
8285 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8286 }
8287 }
8288 }
John McCall31168b02011-06-15 23:02:42 +00008289 };
8290}
8291
8292/// Check whether the given argument is a block which captures a
8293/// variable.
8294static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8295 assert(owner.Variable && owner.Loc.isValid());
8296
8297 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008298
8299 // Look through [^{...} copy] and Block_copy(^{...}).
8300 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8301 Selector Cmd = ME->getSelector();
8302 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8303 e = ME->getInstanceReceiver();
8304 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008305 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008306 e = e->IgnoreParenCasts();
8307 }
8308 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8309 if (CE->getNumArgs() == 1) {
8310 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008311 if (Fn) {
8312 const IdentifierInfo *FnI = Fn->getIdentifier();
8313 if (FnI && FnI->isStr("_Block_copy")) {
8314 e = CE->getArg(0)->IgnoreParenCasts();
8315 }
8316 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008317 }
8318 }
8319
John McCall31168b02011-06-15 23:02:42 +00008320 BlockExpr *block = dyn_cast<BlockExpr>(e);
8321 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008322 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008323
8324 FindCaptureVisitor visitor(S.Context, owner.Variable);
8325 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008326 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008327}
8328
8329static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8330 RetainCycleOwner &owner) {
8331 assert(capturer);
8332 assert(owner.Variable && owner.Loc.isValid());
8333
8334 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8335 << owner.Variable << capturer->getSourceRange();
8336 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8337 << owner.Indirect << owner.Range;
8338}
8339
8340/// Check for a keyword selector that starts with the word 'add' or
8341/// 'set'.
8342static bool isSetterLikeSelector(Selector sel) {
8343 if (sel.isUnarySelector()) return false;
8344
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008345 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008346 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008347 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008348 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008349 else if (str.startswith("add")) {
8350 // Specially whitelist 'addOperationWithBlock:'.
8351 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8352 return false;
8353 str = str.substr(3);
8354 }
John McCall31168b02011-06-15 23:02:42 +00008355 else
8356 return false;
8357
8358 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008359 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008360}
8361
Benjamin Kramer3a743452015-03-09 15:03:32 +00008362static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8363 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008364 if (S.NSMutableArrayPointer.isNull()) {
8365 IdentifierInfo *NSMutableArrayId =
8366 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8367 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8368 Message->getLocStart(),
8369 Sema::LookupOrdinaryName);
8370 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8371 if (!InterfaceDecl) {
8372 return None;
8373 }
8374 QualType NSMutableArrayObject =
8375 S.Context.getObjCInterfaceType(InterfaceDecl);
8376 S.NSMutableArrayPointer =
8377 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8378 }
8379
8380 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8381 return None;
8382 }
8383
8384 Selector Sel = Message->getSelector();
8385
8386 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8387 S.NSAPIObj->getNSArrayMethodKind(Sel);
8388 if (!MKOpt) {
8389 return None;
8390 }
8391
8392 NSAPI::NSArrayMethodKind MK = *MKOpt;
8393
8394 switch (MK) {
8395 case NSAPI::NSMutableArr_addObject:
8396 case NSAPI::NSMutableArr_insertObjectAtIndex:
8397 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8398 return 0;
8399 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8400 return 1;
8401
8402 default:
8403 return None;
8404 }
8405
8406 return None;
8407}
8408
8409static
8410Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8411 ObjCMessageExpr *Message) {
8412
8413 if (S.NSMutableDictionaryPointer.isNull()) {
8414 IdentifierInfo *NSMutableDictionaryId =
8415 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8416 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8417 Message->getLocStart(),
8418 Sema::LookupOrdinaryName);
8419 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8420 if (!InterfaceDecl) {
8421 return None;
8422 }
8423 QualType NSMutableDictionaryObject =
8424 S.Context.getObjCInterfaceType(InterfaceDecl);
8425 S.NSMutableDictionaryPointer =
8426 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8427 }
8428
8429 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8430 return None;
8431 }
8432
8433 Selector Sel = Message->getSelector();
8434
8435 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8436 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8437 if (!MKOpt) {
8438 return None;
8439 }
8440
8441 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8442
8443 switch (MK) {
8444 case NSAPI::NSMutableDict_setObjectForKey:
8445 case NSAPI::NSMutableDict_setValueForKey:
8446 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8447 return 0;
8448
8449 default:
8450 return None;
8451 }
8452
8453 return None;
8454}
8455
8456static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8457
8458 ObjCInterfaceDecl *InterfaceDecl;
8459 if (S.NSMutableSetPointer.isNull()) {
8460 IdentifierInfo *NSMutableSetId =
8461 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8462 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8463 Message->getLocStart(),
8464 Sema::LookupOrdinaryName);
8465 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8466 if (InterfaceDecl) {
8467 QualType NSMutableSetObject =
8468 S.Context.getObjCInterfaceType(InterfaceDecl);
8469 S.NSMutableSetPointer =
8470 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8471 }
8472 }
8473
8474 if (S.NSCountedSetPointer.isNull()) {
8475 IdentifierInfo *NSCountedSetId =
8476 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8477 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8478 Message->getLocStart(),
8479 Sema::LookupOrdinaryName);
8480 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8481 if (InterfaceDecl) {
8482 QualType NSCountedSetObject =
8483 S.Context.getObjCInterfaceType(InterfaceDecl);
8484 S.NSCountedSetPointer =
8485 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8486 }
8487 }
8488
8489 if (S.NSMutableOrderedSetPointer.isNull()) {
8490 IdentifierInfo *NSOrderedSetId =
8491 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8492 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8493 Message->getLocStart(),
8494 Sema::LookupOrdinaryName);
8495 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8496 if (InterfaceDecl) {
8497 QualType NSOrderedSetObject =
8498 S.Context.getObjCInterfaceType(InterfaceDecl);
8499 S.NSMutableOrderedSetPointer =
8500 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8501 }
8502 }
8503
8504 QualType ReceiverType = Message->getReceiverType();
8505
8506 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8507 ReceiverType == S.NSMutableSetPointer;
8508 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8509 ReceiverType == S.NSMutableOrderedSetPointer;
8510 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8511 ReceiverType == S.NSCountedSetPointer;
8512
8513 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8514 return None;
8515 }
8516
8517 Selector Sel = Message->getSelector();
8518
8519 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8520 if (!MKOpt) {
8521 return None;
8522 }
8523
8524 NSAPI::NSSetMethodKind MK = *MKOpt;
8525
8526 switch (MK) {
8527 case NSAPI::NSMutableSet_addObject:
8528 case NSAPI::NSOrderedSet_setObjectAtIndex:
8529 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8530 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8531 return 0;
8532 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8533 return 1;
8534 }
8535
8536 return None;
8537}
8538
8539void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8540 if (!Message->isInstanceMessage()) {
8541 return;
8542 }
8543
8544 Optional<int> ArgOpt;
8545
8546 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8547 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8548 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8549 return;
8550 }
8551
8552 int ArgIndex = *ArgOpt;
8553
8554 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8555 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8556 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8557 }
8558
8559 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8560 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8561 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8562 }
8563
8564 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8565 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8566 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8567 ValueDecl *Decl = ReceiverRE->getDecl();
8568 Diag(Message->getSourceRange().getBegin(),
8569 diag::warn_objc_circular_container)
8570 << Decl->getName();
8571 Diag(Decl->getLocation(),
8572 diag::note_objc_circular_container_declared_here)
8573 << Decl->getName();
8574 }
8575 }
8576 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8577 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8578 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8579 ObjCIvarDecl *Decl = IvarRE->getDecl();
8580 Diag(Message->getSourceRange().getBegin(),
8581 diag::warn_objc_circular_container)
8582 << Decl->getName();
8583 Diag(Decl->getLocation(),
8584 diag::note_objc_circular_container_declared_here)
8585 << Decl->getName();
8586 }
8587 }
8588 }
8589
8590}
8591
John McCall31168b02011-06-15 23:02:42 +00008592/// Check a message send to see if it's likely to cause a retain cycle.
8593void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8594 // Only check instance methods whose selector looks like a setter.
8595 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8596 return;
8597
8598 // Try to find a variable that the receiver is strongly owned by.
8599 RetainCycleOwner owner;
8600 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008601 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008602 return;
8603 } else {
8604 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8605 owner.Variable = getCurMethodDecl()->getSelfDecl();
8606 owner.Loc = msg->getSuperLoc();
8607 owner.Range = msg->getSuperLoc();
8608 }
8609
8610 // Check whether the receiver is captured by any of the arguments.
8611 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8612 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8613 return diagnoseRetainCycle(*this, capturer, owner);
8614}
8615
8616/// Check a property assign to see if it's likely to cause a retain cycle.
8617void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8618 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008619 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008620 return;
8621
8622 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8623 diagnoseRetainCycle(*this, capturer, owner);
8624}
8625
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008626void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8627 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008628 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008629 return;
8630
8631 // Because we don't have an expression for the variable, we have to set the
8632 // location explicitly here.
8633 Owner.Loc = Var->getLocation();
8634 Owner.Range = Var->getSourceRange();
8635
8636 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8637 diagnoseRetainCycle(*this, Capturer, Owner);
8638}
8639
Ted Kremenek9304da92012-12-21 08:04:28 +00008640static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8641 Expr *RHS, bool isProperty) {
8642 // Check if RHS is an Objective-C object literal, which also can get
8643 // immediately zapped in a weak reference. Note that we explicitly
8644 // allow ObjCStringLiterals, since those are designed to never really die.
8645 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008646
Ted Kremenek64873352012-12-21 22:46:35 +00008647 // This enum needs to match with the 'select' in
8648 // warn_objc_arc_literal_assign (off-by-1).
8649 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8650 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8651 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008652
8653 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008654 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008655 << (isProperty ? 0 : 1)
8656 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008657
8658 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008659}
8660
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008661static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8662 Qualifiers::ObjCLifetime LT,
8663 Expr *RHS, bool isProperty) {
8664 // Strip off any implicit cast added to get to the one ARC-specific.
8665 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8666 if (cast->getCastKind() == CK_ARCConsumeObject) {
8667 S.Diag(Loc, diag::warn_arc_retained_assign)
8668 << (LT == Qualifiers::OCL_ExplicitNone)
8669 << (isProperty ? 0 : 1)
8670 << RHS->getSourceRange();
8671 return true;
8672 }
8673 RHS = cast->getSubExpr();
8674 }
8675
8676 if (LT == Qualifiers::OCL_Weak &&
8677 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8678 return true;
8679
8680 return false;
8681}
8682
Ted Kremenekb36234d2012-12-21 08:04:20 +00008683bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8684 QualType LHS, Expr *RHS) {
8685 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8686
8687 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8688 return false;
8689
8690 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8691 return true;
8692
8693 return false;
8694}
8695
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008696void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8697 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008698 QualType LHSType;
8699 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008700 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008701 ObjCPropertyRefExpr *PRE
8702 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8703 if (PRE && !PRE->isImplicitProperty()) {
8704 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8705 if (PD)
8706 LHSType = PD->getType();
8707 }
8708
8709 if (LHSType.isNull())
8710 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008711
8712 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8713
8714 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008715 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008716 getCurFunction()->markSafeWeakUse(LHS);
8717 }
8718
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008719 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8720 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008721
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008722 // FIXME. Check for other life times.
8723 if (LT != Qualifiers::OCL_None)
8724 return;
8725
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008726 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008727 if (PRE->isImplicitProperty())
8728 return;
8729 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8730 if (!PD)
8731 return;
8732
Bill Wendling44426052012-12-20 19:22:21 +00008733 unsigned Attributes = PD->getPropertyAttributes();
8734 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008735 // when 'assign' attribute was not explicitly specified
8736 // by user, ignore it and rely on property type itself
8737 // for lifetime info.
8738 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8739 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8740 LHSType->isObjCRetainableType())
8741 return;
8742
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008743 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008744 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008745 Diag(Loc, diag::warn_arc_retained_property_assign)
8746 << RHS->getSourceRange();
8747 return;
8748 }
8749 RHS = cast->getSubExpr();
8750 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008751 }
Bill Wendling44426052012-12-20 19:22:21 +00008752 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008753 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8754 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008755 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008756 }
8757}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008758
8759//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8760
8761namespace {
8762bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8763 SourceLocation StmtLoc,
8764 const NullStmt *Body) {
8765 // Do not warn if the body is a macro that expands to nothing, e.g:
8766 //
8767 // #define CALL(x)
8768 // if (condition)
8769 // CALL(0);
8770 //
8771 if (Body->hasLeadingEmptyMacro())
8772 return false;
8773
8774 // Get line numbers of statement and body.
8775 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008776 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008777 &StmtLineInvalid);
8778 if (StmtLineInvalid)
8779 return false;
8780
8781 bool BodyLineInvalid;
8782 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8783 &BodyLineInvalid);
8784 if (BodyLineInvalid)
8785 return false;
8786
8787 // Warn if null statement and body are on the same line.
8788 if (StmtLine != BodyLine)
8789 return false;
8790
8791 return true;
8792}
8793} // Unnamed namespace
8794
8795void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8796 const Stmt *Body,
8797 unsigned DiagID) {
8798 // Since this is a syntactic check, don't emit diagnostic for template
8799 // instantiations, this just adds noise.
8800 if (CurrentInstantiationScope)
8801 return;
8802
8803 // The body should be a null statement.
8804 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8805 if (!NBody)
8806 return;
8807
8808 // Do the usual checks.
8809 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8810 return;
8811
8812 Diag(NBody->getSemiLoc(), DiagID);
8813 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8814}
8815
8816void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8817 const Stmt *PossibleBody) {
8818 assert(!CurrentInstantiationScope); // Ensured by caller
8819
8820 SourceLocation StmtLoc;
8821 const Stmt *Body;
8822 unsigned DiagID;
8823 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8824 StmtLoc = FS->getRParenLoc();
8825 Body = FS->getBody();
8826 DiagID = diag::warn_empty_for_body;
8827 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8828 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8829 Body = WS->getBody();
8830 DiagID = diag::warn_empty_while_body;
8831 } else
8832 return; // Neither `for' nor `while'.
8833
8834 // The body should be a null statement.
8835 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8836 if (!NBody)
8837 return;
8838
8839 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008840 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008841 return;
8842
8843 // Do the usual checks.
8844 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8845 return;
8846
8847 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8848 // noise level low, emit diagnostics only if for/while is followed by a
8849 // CompoundStmt, e.g.:
8850 // for (int i = 0; i < n; i++);
8851 // {
8852 // a(i);
8853 // }
8854 // or if for/while is followed by a statement with more indentation
8855 // than for/while itself:
8856 // for (int i = 0; i < n; i++);
8857 // a(i);
8858 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8859 if (!ProbableTypo) {
8860 bool BodyColInvalid;
8861 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8862 PossibleBody->getLocStart(),
8863 &BodyColInvalid);
8864 if (BodyColInvalid)
8865 return;
8866
8867 bool StmtColInvalid;
8868 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8869 S->getLocStart(),
8870 &StmtColInvalid);
8871 if (StmtColInvalid)
8872 return;
8873
8874 if (BodyCol > StmtCol)
8875 ProbableTypo = true;
8876 }
8877
8878 if (ProbableTypo) {
8879 Diag(NBody->getSemiLoc(), DiagID);
8880 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8881 }
8882}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008883
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008884//===--- CHECK: Warn on self move with std::move. -------------------------===//
8885
8886/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8887void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8888 SourceLocation OpLoc) {
8889
8890 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8891 return;
8892
8893 if (!ActiveTemplateInstantiations.empty())
8894 return;
8895
8896 // Strip parens and casts away.
8897 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8898 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8899
8900 // Check for a call expression
8901 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8902 if (!CE || CE->getNumArgs() != 1)
8903 return;
8904
8905 // Check for a call to std::move
8906 const FunctionDecl *FD = CE->getDirectCallee();
8907 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8908 !FD->getIdentifier()->isStr("move"))
8909 return;
8910
8911 // Get argument from std::move
8912 RHSExpr = CE->getArg(0);
8913
8914 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8915 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8916
8917 // Two DeclRefExpr's, check that the decls are the same.
8918 if (LHSDeclRef && RHSDeclRef) {
8919 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8920 return;
8921 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8922 RHSDeclRef->getDecl()->getCanonicalDecl())
8923 return;
8924
8925 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8926 << LHSExpr->getSourceRange()
8927 << RHSExpr->getSourceRange();
8928 return;
8929 }
8930
8931 // Member variables require a different approach to check for self moves.
8932 // MemberExpr's are the same if every nested MemberExpr refers to the same
8933 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8934 // the base Expr's are CXXThisExpr's.
8935 const Expr *LHSBase = LHSExpr;
8936 const Expr *RHSBase = RHSExpr;
8937 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8938 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8939 if (!LHSME || !RHSME)
8940 return;
8941
8942 while (LHSME && RHSME) {
8943 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8944 RHSME->getMemberDecl()->getCanonicalDecl())
8945 return;
8946
8947 LHSBase = LHSME->getBase();
8948 RHSBase = RHSME->getBase();
8949 LHSME = dyn_cast<MemberExpr>(LHSBase);
8950 RHSME = dyn_cast<MemberExpr>(RHSBase);
8951 }
8952
8953 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8954 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8955 if (LHSDeclRef && RHSDeclRef) {
8956 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8957 return;
8958 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8959 RHSDeclRef->getDecl()->getCanonicalDecl())
8960 return;
8961
8962 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8963 << LHSExpr->getSourceRange()
8964 << RHSExpr->getSourceRange();
8965 return;
8966 }
8967
8968 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8969 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8970 << LHSExpr->getSourceRange()
8971 << RHSExpr->getSourceRange();
8972}
8973
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008974//===--- Layout compatibility ----------------------------------------------//
8975
8976namespace {
8977
8978bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8979
8980/// \brief Check if two enumeration types are layout-compatible.
8981bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8982 // C++11 [dcl.enum] p8:
8983 // Two enumeration types are layout-compatible if they have the same
8984 // underlying type.
8985 return ED1->isComplete() && ED2->isComplete() &&
8986 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8987}
8988
8989/// \brief Check if two fields are layout-compatible.
8990bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8991 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8992 return false;
8993
8994 if (Field1->isBitField() != Field2->isBitField())
8995 return false;
8996
8997 if (Field1->isBitField()) {
8998 // Make sure that the bit-fields are the same length.
8999 unsigned Bits1 = Field1->getBitWidthValue(C);
9000 unsigned Bits2 = Field2->getBitWidthValue(C);
9001
9002 if (Bits1 != Bits2)
9003 return false;
9004 }
9005
9006 return true;
9007}
9008
9009/// \brief Check if two standard-layout structs are layout-compatible.
9010/// (C++11 [class.mem] p17)
9011bool isLayoutCompatibleStruct(ASTContext &C,
9012 RecordDecl *RD1,
9013 RecordDecl *RD2) {
9014 // If both records are C++ classes, check that base classes match.
9015 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9016 // If one of records is a CXXRecordDecl we are in C++ mode,
9017 // thus the other one is a CXXRecordDecl, too.
9018 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9019 // Check number of base classes.
9020 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9021 return false;
9022
9023 // Check the base classes.
9024 for (CXXRecordDecl::base_class_const_iterator
9025 Base1 = D1CXX->bases_begin(),
9026 BaseEnd1 = D1CXX->bases_end(),
9027 Base2 = D2CXX->bases_begin();
9028 Base1 != BaseEnd1;
9029 ++Base1, ++Base2) {
9030 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9031 return false;
9032 }
9033 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9034 // If only RD2 is a C++ class, it should have zero base classes.
9035 if (D2CXX->getNumBases() > 0)
9036 return false;
9037 }
9038
9039 // Check the fields.
9040 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9041 Field2End = RD2->field_end(),
9042 Field1 = RD1->field_begin(),
9043 Field1End = RD1->field_end();
9044 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9045 if (!isLayoutCompatible(C, *Field1, *Field2))
9046 return false;
9047 }
9048 if (Field1 != Field1End || Field2 != Field2End)
9049 return false;
9050
9051 return true;
9052}
9053
9054/// \brief Check if two standard-layout unions are layout-compatible.
9055/// (C++11 [class.mem] p18)
9056bool isLayoutCompatibleUnion(ASTContext &C,
9057 RecordDecl *RD1,
9058 RecordDecl *RD2) {
9059 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009060 for (auto *Field2 : RD2->fields())
9061 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009062
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009063 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009064 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9065 I = UnmatchedFields.begin(),
9066 E = UnmatchedFields.end();
9067
9068 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009069 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009070 bool Result = UnmatchedFields.erase(*I);
9071 (void) Result;
9072 assert(Result);
9073 break;
9074 }
9075 }
9076 if (I == E)
9077 return false;
9078 }
9079
9080 return UnmatchedFields.empty();
9081}
9082
9083bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9084 if (RD1->isUnion() != RD2->isUnion())
9085 return false;
9086
9087 if (RD1->isUnion())
9088 return isLayoutCompatibleUnion(C, RD1, RD2);
9089 else
9090 return isLayoutCompatibleStruct(C, RD1, RD2);
9091}
9092
9093/// \brief Check if two types are layout-compatible in C++11 sense.
9094bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9095 if (T1.isNull() || T2.isNull())
9096 return false;
9097
9098 // C++11 [basic.types] p11:
9099 // If two types T1 and T2 are the same type, then T1 and T2 are
9100 // layout-compatible types.
9101 if (C.hasSameType(T1, T2))
9102 return true;
9103
9104 T1 = T1.getCanonicalType().getUnqualifiedType();
9105 T2 = T2.getCanonicalType().getUnqualifiedType();
9106
9107 const Type::TypeClass TC1 = T1->getTypeClass();
9108 const Type::TypeClass TC2 = T2->getTypeClass();
9109
9110 if (TC1 != TC2)
9111 return false;
9112
9113 if (TC1 == Type::Enum) {
9114 return isLayoutCompatible(C,
9115 cast<EnumType>(T1)->getDecl(),
9116 cast<EnumType>(T2)->getDecl());
9117 } else if (TC1 == Type::Record) {
9118 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9119 return false;
9120
9121 return isLayoutCompatible(C,
9122 cast<RecordType>(T1)->getDecl(),
9123 cast<RecordType>(T2)->getDecl());
9124 }
9125
9126 return false;
9127}
9128}
9129
9130//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9131
9132namespace {
9133/// \brief Given a type tag expression find the type tag itself.
9134///
9135/// \param TypeExpr Type tag expression, as it appears in user's code.
9136///
9137/// \param VD Declaration of an identifier that appears in a type tag.
9138///
9139/// \param MagicValue Type tag magic value.
9140bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9141 const ValueDecl **VD, uint64_t *MagicValue) {
9142 while(true) {
9143 if (!TypeExpr)
9144 return false;
9145
9146 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9147
9148 switch (TypeExpr->getStmtClass()) {
9149 case Stmt::UnaryOperatorClass: {
9150 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9151 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9152 TypeExpr = UO->getSubExpr();
9153 continue;
9154 }
9155 return false;
9156 }
9157
9158 case Stmt::DeclRefExprClass: {
9159 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9160 *VD = DRE->getDecl();
9161 return true;
9162 }
9163
9164 case Stmt::IntegerLiteralClass: {
9165 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9166 llvm::APInt MagicValueAPInt = IL->getValue();
9167 if (MagicValueAPInt.getActiveBits() <= 64) {
9168 *MagicValue = MagicValueAPInt.getZExtValue();
9169 return true;
9170 } else
9171 return false;
9172 }
9173
9174 case Stmt::BinaryConditionalOperatorClass:
9175 case Stmt::ConditionalOperatorClass: {
9176 const AbstractConditionalOperator *ACO =
9177 cast<AbstractConditionalOperator>(TypeExpr);
9178 bool Result;
9179 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9180 if (Result)
9181 TypeExpr = ACO->getTrueExpr();
9182 else
9183 TypeExpr = ACO->getFalseExpr();
9184 continue;
9185 }
9186 return false;
9187 }
9188
9189 case Stmt::BinaryOperatorClass: {
9190 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9191 if (BO->getOpcode() == BO_Comma) {
9192 TypeExpr = BO->getRHS();
9193 continue;
9194 }
9195 return false;
9196 }
9197
9198 default:
9199 return false;
9200 }
9201 }
9202}
9203
9204/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9205///
9206/// \param TypeExpr Expression that specifies a type tag.
9207///
9208/// \param MagicValues Registered magic values.
9209///
9210/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9211/// kind.
9212///
9213/// \param TypeInfo Information about the corresponding C type.
9214///
9215/// \returns true if the corresponding C type was found.
9216bool GetMatchingCType(
9217 const IdentifierInfo *ArgumentKind,
9218 const Expr *TypeExpr, const ASTContext &Ctx,
9219 const llvm::DenseMap<Sema::TypeTagMagicValue,
9220 Sema::TypeTagData> *MagicValues,
9221 bool &FoundWrongKind,
9222 Sema::TypeTagData &TypeInfo) {
9223 FoundWrongKind = false;
9224
9225 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009226 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009227
9228 uint64_t MagicValue;
9229
9230 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9231 return false;
9232
9233 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009234 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009235 if (I->getArgumentKind() != ArgumentKind) {
9236 FoundWrongKind = true;
9237 return false;
9238 }
9239 TypeInfo.Type = I->getMatchingCType();
9240 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9241 TypeInfo.MustBeNull = I->getMustBeNull();
9242 return true;
9243 }
9244 return false;
9245 }
9246
9247 if (!MagicValues)
9248 return false;
9249
9250 llvm::DenseMap<Sema::TypeTagMagicValue,
9251 Sema::TypeTagData>::const_iterator I =
9252 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9253 if (I == MagicValues->end())
9254 return false;
9255
9256 TypeInfo = I->second;
9257 return true;
9258}
9259} // unnamed namespace
9260
9261void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9262 uint64_t MagicValue, QualType Type,
9263 bool LayoutCompatible,
9264 bool MustBeNull) {
9265 if (!TypeTagForDatatypeMagicValues)
9266 TypeTagForDatatypeMagicValues.reset(
9267 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9268
9269 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9270 (*TypeTagForDatatypeMagicValues)[Magic] =
9271 TypeTagData(Type, LayoutCompatible, MustBeNull);
9272}
9273
9274namespace {
9275bool IsSameCharType(QualType T1, QualType T2) {
9276 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9277 if (!BT1)
9278 return false;
9279
9280 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9281 if (!BT2)
9282 return false;
9283
9284 BuiltinType::Kind T1Kind = BT1->getKind();
9285 BuiltinType::Kind T2Kind = BT2->getKind();
9286
9287 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9288 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9289 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9290 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9291}
9292} // unnamed namespace
9293
9294void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9295 const Expr * const *ExprArgs) {
9296 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9297 bool IsPointerAttr = Attr->getIsPointer();
9298
9299 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9300 bool FoundWrongKind;
9301 TypeTagData TypeInfo;
9302 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9303 TypeTagForDatatypeMagicValues.get(),
9304 FoundWrongKind, TypeInfo)) {
9305 if (FoundWrongKind)
9306 Diag(TypeTagExpr->getExprLoc(),
9307 diag::warn_type_tag_for_datatype_wrong_kind)
9308 << TypeTagExpr->getSourceRange();
9309 return;
9310 }
9311
9312 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9313 if (IsPointerAttr) {
9314 // Skip implicit cast of pointer to `void *' (as a function argument).
9315 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009316 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009317 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009318 ArgumentExpr = ICE->getSubExpr();
9319 }
9320 QualType ArgumentType = ArgumentExpr->getType();
9321
9322 // Passing a `void*' pointer shouldn't trigger a warning.
9323 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9324 return;
9325
9326 if (TypeInfo.MustBeNull) {
9327 // Type tag with matching void type requires a null pointer.
9328 if (!ArgumentExpr->isNullPointerConstant(Context,
9329 Expr::NPC_ValueDependentIsNotNull)) {
9330 Diag(ArgumentExpr->getExprLoc(),
9331 diag::warn_type_safety_null_pointer_required)
9332 << ArgumentKind->getName()
9333 << ArgumentExpr->getSourceRange()
9334 << TypeTagExpr->getSourceRange();
9335 }
9336 return;
9337 }
9338
9339 QualType RequiredType = TypeInfo.Type;
9340 if (IsPointerAttr)
9341 RequiredType = Context.getPointerType(RequiredType);
9342
9343 bool mismatch = false;
9344 if (!TypeInfo.LayoutCompatible) {
9345 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9346
9347 // C++11 [basic.fundamental] p1:
9348 // Plain char, signed char, and unsigned char are three distinct types.
9349 //
9350 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9351 // char' depending on the current char signedness mode.
9352 if (mismatch)
9353 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9354 RequiredType->getPointeeType())) ||
9355 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9356 mismatch = false;
9357 } else
9358 if (IsPointerAttr)
9359 mismatch = !isLayoutCompatible(Context,
9360 ArgumentType->getPointeeType(),
9361 RequiredType->getPointeeType());
9362 else
9363 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9364
9365 if (mismatch)
9366 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009367 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009368 << TypeInfo.LayoutCompatible << RequiredType
9369 << ArgumentExpr->getSourceRange()
9370 << TypeTagExpr->getSourceRange();
9371}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009372