blob: a64932b1c7176a813eee54ee116120edad4f3792 [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 Qin78b86532015-05-14 08:18:05 +0000626 if (IsInt64Long)
627 return Context.UnsignedLongTy;
628 else
629 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000630 case NeonTypeFlags::Poly128:
631 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000632 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000633 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000634 case NeonTypeFlags::Float32:
635 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000636 case NeonTypeFlags::Float64:
637 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000638 }
David Blaikie8a40f702012-01-17 06:56:22 +0000639 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000640}
641
Tim Northover12670412014-02-19 10:37:05 +0000642bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000643 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000644 uint64_t mask = 0;
645 unsigned TV = 0;
646 int PtrArgNum = -1;
647 bool HasConstPtr = false;
648 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000649#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000650#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000651#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000652 }
653
654 // For NEON intrinsics which are overloaded on vector element type, validate
655 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000656 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000657 if (mask) {
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
659 return true;
660
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
663 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000664 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000665 }
666
667 if (PtrArgNum >= 0) {
668 // Check that pointer arguments have the specified type.
669 Expr *Arg = TheCall->getArg(PtrArgNum);
670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
673 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000674
Tim Northovera2ee4332014-03-29 15:09:45 +0000675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000677 bool IsInt64Long =
678 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
679 QualType EltTy =
680 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000681 if (HasConstPtr)
682 EltTy = EltTy.withConst();
683 QualType LHSTy = Context.getPointerType(EltTy);
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
686 if (RHS.isInvalid())
687 return true;
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.get(), AA_Assigning))
690 return true;
691 }
692
693 // For NEON intrinsics which take an immediate value as part of the
694 // instruction, range check them here.
695 unsigned i = 0, l = 0, u = 0;
696 switch (BuiltinID) {
697 default:
698 return false;
Tim Northover12670412014-02-19 10:37:05 +0000699#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000700#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000701#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000702 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000703
Richard Sandiford28940af2014-04-16 08:47:51 +0000704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000705}
706
Tim Northovera2ee4332014-03-29 15:09:45 +0000707bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
708 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000711 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000712 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000717 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000722
723 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
724
725 // Ensure that we have the proper number of arguments.
726 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
727 return true;
728
729 // Inspect the pointer argument of the atomic builtin. This should always be
730 // a pointer type, whose element is an integral scalar or pointer type.
731 // Because it is a pointer type, we don't have to worry about any implicit
732 // casts here.
733 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
735 if (PointerArgRes.isInvalid())
736 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000737 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000738
739 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
740 if (!pointerType) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
747 // task is to insert the appropriate casts into the AST. First work out just
748 // what the appropriate type is.
749 QualType ValType = pointerType->getPointeeType();
750 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
751 if (IsLdrex)
752 AddrType.addConst();
753
754 // Issue a warning if the cast is dodgy.
755 CastKind CastNeeded = CK_NoOp;
756 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
757 CastNeeded = CK_BitCast;
758 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
759 << PointerArg->getType()
760 << Context.getPointerType(AddrType)
761 << AA_Passing << PointerArg->getSourceRange();
762 }
763
764 // Finally, do the cast and replace the argument with the corrected version.
765 AddrType = Context.getPointerType(AddrType);
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
767 if (PointerArgRes.isInvalid())
768 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000769 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000770
771 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
772
773 // In general, we allow ints, floats and pointers to be loaded and stored.
774 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
775 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->getType() << PointerArg->getSourceRange();
778 return true;
779 }
780
781 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000782 if (Context.getTypeSize(ValType) > MaxWidth) {
783 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->getType() << PointerArg->getSourceRange();
786 return true;
787 }
788
789 switch (ValType.getObjCLifetime()) {
790 case Qualifiers::OCL_None:
791 case Qualifiers::OCL_ExplicitNone:
792 // okay
793 break;
794
795 case Qualifiers::OCL_Weak:
796 case Qualifiers::OCL_Strong:
797 case Qualifiers::OCL_Autoreleasing:
798 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
799 << ValType << PointerArg->getSourceRange();
800 return true;
801 }
802
803
804 if (IsLdrex) {
805 TheCall->setType(ValType);
806 return false;
807 }
808
809 // Initialize the argument to be stored.
810 ExprResult ValArg = TheCall->getArg(0);
811 InitializedEntity Entity = InitializedEntity::InitializeParameter(
812 Context, ValType, /*consume*/ false);
813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
814 if (ValArg.isInvalid())
815 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000816 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000817
818 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
819 // but the custom checker bypasses all default analysis.
820 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000821 return false;
822}
823
Nate Begeman4904e322010-06-08 02:47:44 +0000824bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000825 llvm::APSInt Result;
826
Tim Northover6aacd492013-07-16 09:47:53 +0000827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000832 }
833
Yi Kong26d104a2014-08-13 19:18:14 +0000834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
837 }
838
Tim Northover12670412014-02-19 10:37:05 +0000839 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
840 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000841
Yi Kong4efadfb2014-07-03 16:01:25 +0000842 // For intrinsics which take an immediate value as part of the instruction,
843 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000844 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000845 switch (BuiltinID) {
846 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000847 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
848 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000849 case ARM::BI__builtin_arm_vcvtr_f:
850 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000851 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000852 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000853 case ARM::BI__builtin_arm_isb:
854 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000855 }
Nate Begemand773fe62010-06-13 04:47:52 +0000856
Nate Begemanf568b072010-08-03 21:32:34 +0000857 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000858 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000859}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000860
Tim Northover573cbee2014-05-24 12:52:07 +0000861bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000862 CallExpr *TheCall) {
863 llvm::APSInt Result;
864
Tim Northover573cbee2014-05-24 12:52:07 +0000865 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000866 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
867 BuiltinID == AArch64::BI__builtin_arm_strex ||
868 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000869 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
870 }
871
Yi Konga5548432014-08-13 19:18:20 +0000872 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
873 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
874 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
875 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
876 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
877 }
878
Tim Northovera2ee4332014-03-29 15:09:45 +0000879 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
880 return true;
881
Yi Kong19a29ac2014-07-17 10:52:06 +0000882 // For intrinsics which take an immediate value as part of the instruction,
883 // range check them here.
884 unsigned i = 0, l = 0, u = 0;
885 switch (BuiltinID) {
886 default: return false;
887 case AArch64::BI__builtin_arm_dmb:
888 case AArch64::BI__builtin_arm_dsb:
889 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
890 }
891
Yi Kong19a29ac2014-07-17 10:52:06 +0000892 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000893}
894
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000895bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
896 unsigned i = 0, l = 0, u = 0;
897 switch (BuiltinID) {
898 default: return false;
899 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
900 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000901 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
902 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
903 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
904 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
905 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000906 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000907
Richard Sandiford28940af2014-04-16 08:47:51 +0000908 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000909}
910
Kit Bartone50adcb2015-03-30 19:40:59 +0000911bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
912 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000913 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
914 BuiltinID == PPC::BI__builtin_divdeu ||
915 BuiltinID == PPC::BI__builtin_bpermd;
916 bool IsTarget64Bit = Context.getTargetInfo()
917 .getTypeWidth(Context
918 .getTargetInfo()
919 .getIntPtrType()) == 64;
920 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
921 BuiltinID == PPC::BI__builtin_divweu ||
922 BuiltinID == PPC::BI__builtin_divde ||
923 BuiltinID == PPC::BI__builtin_divdeu;
924
925 if (Is64BitBltin && !IsTarget64Bit)
926 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
927 << TheCall->getSourceRange();
928
929 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
930 (BuiltinID == PPC::BI__builtin_bpermd &&
931 !Context.getTargetInfo().hasFeature("bpermd")))
932 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
933 << TheCall->getSourceRange();
934
Kit Bartone50adcb2015-03-30 19:40:59 +0000935 switch (BuiltinID) {
936 default: return false;
937 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
938 case PPC::BI__builtin_altivec_crypto_vshasigmad:
939 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
940 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
941 case PPC::BI__builtin_tbegin:
942 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
943 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
944 case PPC::BI__builtin_tabortwc:
945 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
946 case PPC::BI__builtin_tabortwci:
947 case PPC::BI__builtin_tabortdci:
948 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
949 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
950 }
951 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
952}
953
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000954bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
955 CallExpr *TheCall) {
956 if (BuiltinID == SystemZ::BI__builtin_tabort) {
957 Expr *Arg = TheCall->getArg(0);
958 llvm::APSInt AbortCode(32);
959 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
960 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
961 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
962 << Arg->getSourceRange();
963 }
964
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000965 // For intrinsics which take an immediate value as part of the instruction,
966 // range check them here.
967 unsigned i = 0, l = 0, u = 0;
968 switch (BuiltinID) {
969 default: return false;
970 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
971 case SystemZ::BI__builtin_s390_verimb:
972 case SystemZ::BI__builtin_s390_verimh:
973 case SystemZ::BI__builtin_s390_verimf:
974 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
975 case SystemZ::BI__builtin_s390_vfaeb:
976 case SystemZ::BI__builtin_s390_vfaeh:
977 case SystemZ::BI__builtin_s390_vfaef:
978 case SystemZ::BI__builtin_s390_vfaebs:
979 case SystemZ::BI__builtin_s390_vfaehs:
980 case SystemZ::BI__builtin_s390_vfaefs:
981 case SystemZ::BI__builtin_s390_vfaezb:
982 case SystemZ::BI__builtin_s390_vfaezh:
983 case SystemZ::BI__builtin_s390_vfaezf:
984 case SystemZ::BI__builtin_s390_vfaezbs:
985 case SystemZ::BI__builtin_s390_vfaezhs:
986 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
987 case SystemZ::BI__builtin_s390_vfidb:
988 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
989 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
990 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
991 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
992 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
993 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
994 case SystemZ::BI__builtin_s390_vstrcb:
995 case SystemZ::BI__builtin_s390_vstrch:
996 case SystemZ::BI__builtin_s390_vstrcf:
997 case SystemZ::BI__builtin_s390_vstrczb:
998 case SystemZ::BI__builtin_s390_vstrczh:
999 case SystemZ::BI__builtin_s390_vstrczf:
1000 case SystemZ::BI__builtin_s390_vstrcbs:
1001 case SystemZ::BI__builtin_s390_vstrchs:
1002 case SystemZ::BI__builtin_s390_vstrcfs:
1003 case SystemZ::BI__builtin_s390_vstrczbs:
1004 case SystemZ::BI__builtin_s390_vstrczhs:
1005 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1006 }
1007 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001008}
1009
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001010bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001011 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001012 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001013 default: return false;
1014 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001015 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001016 case X86::BI__builtin_ia32_vpermil2pd:
1017 case X86::BI__builtin_ia32_vpermil2pd256:
1018 case X86::BI__builtin_ia32_vpermil2ps:
1019 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001020 case X86::BI__builtin_ia32_cmpb128_mask:
1021 case X86::BI__builtin_ia32_cmpw128_mask:
1022 case X86::BI__builtin_ia32_cmpd128_mask:
1023 case X86::BI__builtin_ia32_cmpq128_mask:
1024 case X86::BI__builtin_ia32_cmpb256_mask:
1025 case X86::BI__builtin_ia32_cmpw256_mask:
1026 case X86::BI__builtin_ia32_cmpd256_mask:
1027 case X86::BI__builtin_ia32_cmpq256_mask:
1028 case X86::BI__builtin_ia32_cmpb512_mask:
1029 case X86::BI__builtin_ia32_cmpw512_mask:
1030 case X86::BI__builtin_ia32_cmpd512_mask:
1031 case X86::BI__builtin_ia32_cmpq512_mask:
1032 case X86::BI__builtin_ia32_ucmpb128_mask:
1033 case X86::BI__builtin_ia32_ucmpw128_mask:
1034 case X86::BI__builtin_ia32_ucmpd128_mask:
1035 case X86::BI__builtin_ia32_ucmpq128_mask:
1036 case X86::BI__builtin_ia32_ucmpb256_mask:
1037 case X86::BI__builtin_ia32_ucmpw256_mask:
1038 case X86::BI__builtin_ia32_ucmpd256_mask:
1039 case X86::BI__builtin_ia32_ucmpq256_mask:
1040 case X86::BI__builtin_ia32_ucmpb512_mask:
1041 case X86::BI__builtin_ia32_ucmpw512_mask:
1042 case X86::BI__builtin_ia32_ucmpd512_mask:
1043 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001044 case X86::BI__builtin_ia32_roundps:
1045 case X86::BI__builtin_ia32_roundpd:
1046 case X86::BI__builtin_ia32_roundps256:
1047 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1048 case X86::BI__builtin_ia32_roundss:
1049 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1050 case X86::BI__builtin_ia32_cmpps:
1051 case X86::BI__builtin_ia32_cmpss:
1052 case X86::BI__builtin_ia32_cmppd:
1053 case X86::BI__builtin_ia32_cmpsd:
1054 case X86::BI__builtin_ia32_cmpps256:
1055 case X86::BI__builtin_ia32_cmppd256:
1056 case X86::BI__builtin_ia32_cmpps512_mask:
1057 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001058 case X86::BI__builtin_ia32_vpcomub:
1059 case X86::BI__builtin_ia32_vpcomuw:
1060 case X86::BI__builtin_ia32_vpcomud:
1061 case X86::BI__builtin_ia32_vpcomuq:
1062 case X86::BI__builtin_ia32_vpcomb:
1063 case X86::BI__builtin_ia32_vpcomw:
1064 case X86::BI__builtin_ia32_vpcomd:
1065 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001066 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001067 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001068}
1069
Richard Smith55ce3522012-06-25 20:30:08 +00001070/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1071/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1072/// Returns true when the format fits the function and the FormatStringInfo has
1073/// been populated.
1074bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1075 FormatStringInfo *FSI) {
1076 FSI->HasVAListArg = Format->getFirstArg() == 0;
1077 FSI->FormatIdx = Format->getFormatIdx() - 1;
1078 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001079
Richard Smith55ce3522012-06-25 20:30:08 +00001080 // The way the format attribute works in GCC, the implicit this argument
1081 // of member functions is counted. However, it doesn't appear in our own
1082 // lists, so decrement format_idx in that case.
1083 if (IsCXXMember) {
1084 if(FSI->FormatIdx == 0)
1085 return false;
1086 --FSI->FormatIdx;
1087 if (FSI->FirstDataArg != 0)
1088 --FSI->FirstDataArg;
1089 }
1090 return true;
1091}
Mike Stump11289f42009-09-09 15:08:12 +00001092
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001093/// Checks if a the given expression evaluates to null.
1094///
1095/// \brief Returns true if the value evaluates to null.
1096static bool CheckNonNullExpr(Sema &S,
1097 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001098 // As a special case, transparent unions initialized with zero are
1099 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001100 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001101 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1102 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001103 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001104 if (const InitListExpr *ILE =
1105 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001106 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001107 }
1108
1109 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001110 return (!Expr->isValueDependent() &&
1111 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1112 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001113}
1114
1115static void CheckNonNullArgument(Sema &S,
1116 const Expr *ArgExpr,
1117 SourceLocation CallSiteLoc) {
1118 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001119 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1120}
1121
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001122bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1123 FormatStringInfo FSI;
1124 if ((GetFormatStringType(Format) == FST_NSString) &&
1125 getFormatStringInfo(Format, false, &FSI)) {
1126 Idx = FSI.FormatIdx;
1127 return true;
1128 }
1129 return false;
1130}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001131/// \brief Diagnose use of %s directive in an NSString which is being passed
1132/// as formatting string to formatting method.
1133static void
1134DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1135 const NamedDecl *FDecl,
1136 Expr **Args,
1137 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001138 unsigned Idx = 0;
1139 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001140 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1141 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001142 Idx = 2;
1143 Format = true;
1144 }
1145 else
1146 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1147 if (S.GetFormatNSStringIdx(I, Idx)) {
1148 Format = true;
1149 break;
1150 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001151 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001152 if (!Format || NumArgs <= Idx)
1153 return;
1154 const Expr *FormatExpr = Args[Idx];
1155 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1156 FormatExpr = CSCE->getSubExpr();
1157 const StringLiteral *FormatString;
1158 if (const ObjCStringLiteral *OSL =
1159 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1160 FormatString = OSL->getString();
1161 else
1162 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1163 if (!FormatString)
1164 return;
1165 if (S.FormatStringHasSArg(FormatString)) {
1166 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1167 << "%s" << 1 << 1;
1168 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1169 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001170 }
1171}
1172
Ted Kremenek2bc73332014-01-17 06:24:43 +00001173static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001174 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001175 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001176 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001177 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001178 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001179 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001180 if (!NonNull->args_size()) {
1181 // Easy case: all pointer arguments are nonnull.
1182 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001183 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001184 CheckNonNullArgument(S, Arg, CallSiteLoc);
1185 return;
1186 }
1187
1188 for (unsigned Val : NonNull->args()) {
1189 if (Val >= Args.size())
1190 continue;
1191 if (NonNullArgs.empty())
1192 NonNullArgs.resize(Args.size());
1193 NonNullArgs.set(Val);
1194 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001195 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001196
1197 // Check the attributes on the parameters.
1198 ArrayRef<ParmVarDecl*> parms;
1199 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1200 parms = FD->parameters();
1201 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1202 parms = MD->parameters();
1203
Richard Smith588bd9b2014-08-27 04:59:42 +00001204 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001205 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001206 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001207 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001208 if (PVD->hasAttr<NonNullAttr>() ||
1209 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1210 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001211 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001212
1213 // In case this is a variadic call, check any remaining arguments.
1214 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1215 if (NonNullArgs[ArgIndex])
1216 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001217}
1218
Richard Smith55ce3522012-06-25 20:30:08 +00001219/// Handles the checks for format strings, non-POD arguments to vararg
1220/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001221void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1222 unsigned NumParams, bool IsMemberFunction,
1223 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001224 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001225 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001226 if (CurContext->isDependentContext())
1227 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001228
Ted Kremenekb8176da2010-09-09 04:33:05 +00001229 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001230 llvm::SmallBitVector CheckedVarArgs;
1231 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001232 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001233 // Only create vector if there are format attributes.
1234 CheckedVarArgs.resize(Args.size());
1235
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001236 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001237 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001238 }
Richard Smithd7293d72013-08-05 18:49:43 +00001239 }
Richard Smith55ce3522012-06-25 20:30:08 +00001240
1241 // Refuse POD arguments that weren't caught by the format string
1242 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001243 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001244 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001245 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001246 if (const Expr *Arg = Args[ArgIdx]) {
1247 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1248 checkVariadicArgument(Arg, CallType);
1249 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001250 }
Richard Smithd7293d72013-08-05 18:49:43 +00001251 }
Mike Stump11289f42009-09-09 15:08:12 +00001252
Richard Trieu41bc0992013-06-22 00:20:41 +00001253 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001254 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001255
Richard Trieu41bc0992013-06-22 00:20:41 +00001256 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001257 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1258 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001259 }
Richard Smith55ce3522012-06-25 20:30:08 +00001260}
1261
1262/// CheckConstructorCall - Check a constructor call for correctness and safety
1263/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001264void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1265 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001266 const FunctionProtoType *Proto,
1267 SourceLocation Loc) {
1268 VariadicCallType CallType =
1269 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001270 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001271 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1272}
1273
1274/// CheckFunctionCall - Check a direct function call for various correctness
1275/// and safety properties not strictly enforced by the C type system.
1276bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1277 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001278 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1279 isa<CXXMethodDecl>(FDecl);
1280 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1281 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001282 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1283 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001284 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001285 Expr** Args = TheCall->getArgs();
1286 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001287 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001288 // If this is a call to a member operator, hide the first argument
1289 // from checkCall.
1290 // FIXME: Our choice of AST representation here is less than ideal.
1291 ++Args;
1292 --NumArgs;
1293 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001294 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001295 IsMemberFunction, TheCall->getRParenLoc(),
1296 TheCall->getCallee()->getSourceRange(), CallType);
1297
1298 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1299 // None of the checks below are needed for functions that don't have
1300 // simple names (e.g., C++ conversion functions).
1301 if (!FnInfo)
1302 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001303
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001304 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001305 if (getLangOpts().ObjC1)
1306 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001307
Anna Zaks22122702012-01-17 00:37:07 +00001308 unsigned CMId = FDecl->getMemoryFunctionKind();
1309 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001310 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001311
Anna Zaks201d4892012-01-13 21:52:01 +00001312 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001313 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001314 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001315 else if (CMId == Builtin::BIstrncat)
1316 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001317 else
Anna Zaks22122702012-01-17 00:37:07 +00001318 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001319
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001320 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001321}
1322
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001323bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001324 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001325 VariadicCallType CallType =
1326 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001327
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001328 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001329 /*IsMemberFunction=*/false,
1330 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001331
1332 return false;
1333}
1334
Richard Trieu664c4c62013-06-20 21:03:13 +00001335bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1336 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001337 QualType Ty;
1338 if (const auto *V = dyn_cast<VarDecl>(NDecl))
1339 Ty = V->getType();
1340 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1341 Ty = F->getType();
1342 else
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 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001346 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001347
Richard Trieu664c4c62013-06-20 21:03:13 +00001348 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001349 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001350 CallType = VariadicDoesNotApply;
1351 } else if (Ty->isBlockPointerType()) {
1352 CallType = VariadicBlock;
1353 } else { // Ty->isFunctionPointerType()
1354 CallType = VariadicFunction;
1355 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001356 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001357
Craig Topper8c2a2a02014-08-30 16:55:39 +00001358 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1359 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001361 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001362
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001363 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001364}
1365
Richard Trieu41bc0992013-06-22 00:20:41 +00001366/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1367/// such as function pointers returned from functions.
1368bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001369 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001370 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001371 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001372
Craig Topperc3ec1492014-05-26 06:22:03 +00001373 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001374 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001375 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001376 TheCall->getCallee()->getSourceRange(), CallType);
1377
1378 return false;
1379}
1380
Tim Northovere94a34c2014-03-11 10:49:14 +00001381static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1382 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1383 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1384 return false;
1385
1386 switch (Op) {
1387 case AtomicExpr::AO__c11_atomic_init:
1388 llvm_unreachable("There is no ordering argument for an init");
1389
1390 case AtomicExpr::AO__c11_atomic_load:
1391 case AtomicExpr::AO__atomic_load_n:
1392 case AtomicExpr::AO__atomic_load:
1393 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1394 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1395
1396 case AtomicExpr::AO__c11_atomic_store:
1397 case AtomicExpr::AO__atomic_store:
1398 case AtomicExpr::AO__atomic_store_n:
1399 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1400 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1401 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1402
1403 default:
1404 return true;
1405 }
1406}
1407
Richard Smithfeea8832012-04-12 05:08:17 +00001408ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1409 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001410 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1411 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001412
Richard Smithfeea8832012-04-12 05:08:17 +00001413 // All these operations take one of the following forms:
1414 enum {
1415 // C __c11_atomic_init(A *, C)
1416 Init,
1417 // C __c11_atomic_load(A *, int)
1418 Load,
1419 // void __atomic_load(A *, CP, int)
1420 Copy,
1421 // C __c11_atomic_add(A *, M, int)
1422 Arithmetic,
1423 // C __atomic_exchange_n(A *, CP, int)
1424 Xchg,
1425 // void __atomic_exchange(A *, C *, CP, int)
1426 GNUXchg,
1427 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1428 C11CmpXchg,
1429 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1430 GNUCmpXchg
1431 } Form = Init;
1432 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1433 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1434 // where:
1435 // C is an appropriate type,
1436 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1437 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1438 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1439 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001440
Gabor Horvath98bd0982015-03-16 09:59:54 +00001441 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1442 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1443 AtomicExpr::AO__atomic_load,
1444 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001445 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1446 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1447 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1448 Op == AtomicExpr::AO__atomic_store_n ||
1449 Op == AtomicExpr::AO__atomic_exchange_n ||
1450 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1451 bool IsAddSub = false;
1452
1453 switch (Op) {
1454 case AtomicExpr::AO__c11_atomic_init:
1455 Form = Init;
1456 break;
1457
1458 case AtomicExpr::AO__c11_atomic_load:
1459 case AtomicExpr::AO__atomic_load_n:
1460 Form = Load;
1461 break;
1462
1463 case AtomicExpr::AO__c11_atomic_store:
1464 case AtomicExpr::AO__atomic_load:
1465 case AtomicExpr::AO__atomic_store:
1466 case AtomicExpr::AO__atomic_store_n:
1467 Form = Copy;
1468 break;
1469
1470 case AtomicExpr::AO__c11_atomic_fetch_add:
1471 case AtomicExpr::AO__c11_atomic_fetch_sub:
1472 case AtomicExpr::AO__atomic_fetch_add:
1473 case AtomicExpr::AO__atomic_fetch_sub:
1474 case AtomicExpr::AO__atomic_add_fetch:
1475 case AtomicExpr::AO__atomic_sub_fetch:
1476 IsAddSub = true;
1477 // Fall through.
1478 case AtomicExpr::AO__c11_atomic_fetch_and:
1479 case AtomicExpr::AO__c11_atomic_fetch_or:
1480 case AtomicExpr::AO__c11_atomic_fetch_xor:
1481 case AtomicExpr::AO__atomic_fetch_and:
1482 case AtomicExpr::AO__atomic_fetch_or:
1483 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001484 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001485 case AtomicExpr::AO__atomic_and_fetch:
1486 case AtomicExpr::AO__atomic_or_fetch:
1487 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001488 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001489 Form = Arithmetic;
1490 break;
1491
1492 case AtomicExpr::AO__c11_atomic_exchange:
1493 case AtomicExpr::AO__atomic_exchange_n:
1494 Form = Xchg;
1495 break;
1496
1497 case AtomicExpr::AO__atomic_exchange:
1498 Form = GNUXchg;
1499 break;
1500
1501 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1502 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1503 Form = C11CmpXchg;
1504 break;
1505
1506 case AtomicExpr::AO__atomic_compare_exchange:
1507 case AtomicExpr::AO__atomic_compare_exchange_n:
1508 Form = GNUCmpXchg;
1509 break;
1510 }
1511
1512 // Check we have the right number of arguments.
1513 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001514 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001515 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001516 << TheCall->getCallee()->getSourceRange();
1517 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001518 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1519 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001520 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001521 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001522 << TheCall->getCallee()->getSourceRange();
1523 return ExprError();
1524 }
1525
Richard Smithfeea8832012-04-12 05:08:17 +00001526 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001527 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001528 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1529 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1530 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001531 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001532 << Ptr->getType() << Ptr->getSourceRange();
1533 return ExprError();
1534 }
1535
Richard Smithfeea8832012-04-12 05:08:17 +00001536 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1537 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1538 QualType ValType = AtomTy; // 'C'
1539 if (IsC11) {
1540 if (!AtomTy->isAtomicType()) {
1541 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1542 << Ptr->getType() << Ptr->getSourceRange();
1543 return ExprError();
1544 }
Richard Smithe00921a2012-09-15 06:09:58 +00001545 if (AtomTy.isConstQualified()) {
1546 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1547 << Ptr->getType() << Ptr->getSourceRange();
1548 return ExprError();
1549 }
Richard Smithfeea8832012-04-12 05:08:17 +00001550 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001551 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001552
Richard Smithfeea8832012-04-12 05:08:17 +00001553 // For an arithmetic operation, the implied arithmetic must be well-formed.
1554 if (Form == Arithmetic) {
1555 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1556 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1557 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1558 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1559 return ExprError();
1560 }
1561 if (!IsAddSub && !ValType->isIntegerType()) {
1562 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1563 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1564 return ExprError();
1565 }
David Majnemere85cff82015-01-28 05:48:06 +00001566 if (IsC11 && ValType->isPointerType() &&
1567 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1568 diag::err_incomplete_type)) {
1569 return ExprError();
1570 }
Richard Smithfeea8832012-04-12 05:08:17 +00001571 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1572 // For __atomic_*_n operations, the value type must be a scalar integral or
1573 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001574 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001575 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1576 return ExprError();
1577 }
1578
Eli Friedmanaa769812013-09-11 03:49:34 +00001579 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1580 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001581 // For GNU atomics, require a trivially-copyable type. This is not part of
1582 // the GNU atomics specification, but we enforce it for sanity.
1583 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001584 << Ptr->getType() << Ptr->getSourceRange();
1585 return ExprError();
1586 }
1587
Richard Smithfeea8832012-04-12 05:08:17 +00001588 // FIXME: For any builtin other than a load, the ValType must not be
1589 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001590
1591 switch (ValType.getObjCLifetime()) {
1592 case Qualifiers::OCL_None:
1593 case Qualifiers::OCL_ExplicitNone:
1594 // okay
1595 break;
1596
1597 case Qualifiers::OCL_Weak:
1598 case Qualifiers::OCL_Strong:
1599 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001600 // FIXME: Can this happen? By this point, ValType should be known
1601 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001602 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1603 << ValType << Ptr->getSourceRange();
1604 return ExprError();
1605 }
1606
1607 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001608 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001609 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001610 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001611 ResultType = Context.BoolTy;
1612
Richard Smithfeea8832012-04-12 05:08:17 +00001613 // The type of a parameter passed 'by value'. In the GNU atomics, such
1614 // arguments are actually passed as pointers.
1615 QualType ByValType = ValType; // 'CP'
1616 if (!IsC11 && !IsN)
1617 ByValType = Ptr->getType();
1618
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001619 // The first argument --- the pointer --- has a fixed type; we
1620 // deduce the types of the rest of the arguments accordingly. Walk
1621 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001622 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001623 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001624 if (i < NumVals[Form] + 1) {
1625 switch (i) {
1626 case 1:
1627 // The second argument is the non-atomic operand. For arithmetic, this
1628 // is always passed by value, and for a compare_exchange it is always
1629 // passed by address. For the rest, GNU uses by-address and C11 uses
1630 // by-value.
1631 assert(Form != Load);
1632 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1633 Ty = ValType;
1634 else if (Form == Copy || Form == Xchg)
1635 Ty = ByValType;
1636 else if (Form == Arithmetic)
1637 Ty = Context.getPointerDiffType();
1638 else
1639 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1640 break;
1641 case 2:
1642 // The third argument to compare_exchange / GNU exchange is a
1643 // (pointer to a) desired value.
1644 Ty = ByValType;
1645 break;
1646 case 3:
1647 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1648 Ty = Context.BoolTy;
1649 break;
1650 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001651 } else {
1652 // The order(s) are always converted to int.
1653 Ty = Context.IntTy;
1654 }
Richard Smithfeea8832012-04-12 05:08:17 +00001655
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001656 InitializedEntity Entity =
1657 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001658 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001659 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1660 if (Arg.isInvalid())
1661 return true;
1662 TheCall->setArg(i, Arg.get());
1663 }
1664
Richard Smithfeea8832012-04-12 05:08:17 +00001665 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001666 SmallVector<Expr*, 5> SubExprs;
1667 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001668 switch (Form) {
1669 case Init:
1670 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001671 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001672 break;
1673 case Load:
1674 SubExprs.push_back(TheCall->getArg(1)); // Order
1675 break;
1676 case Copy:
1677 case Arithmetic:
1678 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001679 SubExprs.push_back(TheCall->getArg(2)); // Order
1680 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001681 break;
1682 case GNUXchg:
1683 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1684 SubExprs.push_back(TheCall->getArg(3)); // Order
1685 SubExprs.push_back(TheCall->getArg(1)); // Val1
1686 SubExprs.push_back(TheCall->getArg(2)); // Val2
1687 break;
1688 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001689 SubExprs.push_back(TheCall->getArg(3)); // Order
1690 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001691 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001692 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001693 break;
1694 case GNUCmpXchg:
1695 SubExprs.push_back(TheCall->getArg(4)); // Order
1696 SubExprs.push_back(TheCall->getArg(1)); // Val1
1697 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1698 SubExprs.push_back(TheCall->getArg(2)); // Val2
1699 SubExprs.push_back(TheCall->getArg(3)); // Weak
1700 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001701 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001702
1703 if (SubExprs.size() >= 2 && Form != Init) {
1704 llvm::APSInt Result(32);
1705 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1706 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001707 Diag(SubExprs[1]->getLocStart(),
1708 diag::warn_atomic_op_has_invalid_memory_order)
1709 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001710 }
1711
Fariborz Jahanian615de762013-05-28 17:37:39 +00001712 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1713 SubExprs, ResultType, Op,
1714 TheCall->getRParenLoc());
1715
1716 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1717 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1718 Context.AtomicUsesUnsupportedLibcall(AE))
1719 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1720 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001721
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001722 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001723}
1724
1725
John McCall29ad95b2011-08-27 01:09:30 +00001726/// checkBuiltinArgument - Given a call to a builtin function, perform
1727/// normal type-checking on the given argument, updating the call in
1728/// place. This is useful when a builtin function requires custom
1729/// type-checking for some of its arguments but not necessarily all of
1730/// them.
1731///
1732/// Returns true on error.
1733static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1734 FunctionDecl *Fn = E->getDirectCallee();
1735 assert(Fn && "builtin call without direct callee!");
1736
1737 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1738 InitializedEntity Entity =
1739 InitializedEntity::InitializeParameter(S.Context, Param);
1740
1741 ExprResult Arg = E->getArg(0);
1742 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1743 if (Arg.isInvalid())
1744 return true;
1745
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001746 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001747 return false;
1748}
1749
Chris Lattnerdc046542009-05-08 06:58:22 +00001750/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1751/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1752/// type of its first argument. The main ActOnCallExpr routines have already
1753/// promoted the types of arguments because all of these calls are prototyped as
1754/// void(...).
1755///
1756/// This function goes through and does final semantic checking for these
1757/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001758ExprResult
1759Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001760 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001761 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1762 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1763
1764 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001765 if (TheCall->getNumArgs() < 1) {
1766 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1767 << 0 << 1 << TheCall->getNumArgs()
1768 << TheCall->getCallee()->getSourceRange();
1769 return ExprError();
1770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Chris Lattnerdc046542009-05-08 06:58:22 +00001772 // Inspect the first argument of the atomic builtin. This should always be
1773 // a pointer type, whose element is an integral scalar or pointer type.
1774 // Because it is a pointer type, we don't have to worry about any implicit
1775 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001776 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001777 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001778 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1779 if (FirstArgResult.isInvalid())
1780 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001781 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001782 TheCall->setArg(0, FirstArg);
1783
John McCall31168b02011-06-15 23:02:42 +00001784 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1785 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001786 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1787 << FirstArg->getType() << FirstArg->getSourceRange();
1788 return ExprError();
1789 }
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCall31168b02011-06-15 23:02:42 +00001791 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001792 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001793 !ValType->isBlockPointerType()) {
1794 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1795 << FirstArg->getType() << FirstArg->getSourceRange();
1796 return ExprError();
1797 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001798
John McCall31168b02011-06-15 23:02:42 +00001799 switch (ValType.getObjCLifetime()) {
1800 case Qualifiers::OCL_None:
1801 case Qualifiers::OCL_ExplicitNone:
1802 // okay
1803 break;
1804
1805 case Qualifiers::OCL_Weak:
1806 case Qualifiers::OCL_Strong:
1807 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001808 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001809 << ValType << FirstArg->getSourceRange();
1810 return ExprError();
1811 }
1812
John McCallb50451a2011-10-05 07:41:44 +00001813 // Strip any qualifiers off ValType.
1814 ValType = ValType.getUnqualifiedType();
1815
Chandler Carruth3973af72010-07-18 20:54:12 +00001816 // The majority of builtins return a value, but a few have special return
1817 // types, so allow them to override appropriately below.
1818 QualType ResultType = ValType;
1819
Chris Lattnerdc046542009-05-08 06:58:22 +00001820 // We need to figure out which concrete builtin this maps onto. For example,
1821 // __sync_fetch_and_add with a 2 byte object turns into
1822 // __sync_fetch_and_add_2.
1823#define BUILTIN_ROW(x) \
1824 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1825 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001826
Chris Lattnerdc046542009-05-08 06:58:22 +00001827 static const unsigned BuiltinIndices[][5] = {
1828 BUILTIN_ROW(__sync_fetch_and_add),
1829 BUILTIN_ROW(__sync_fetch_and_sub),
1830 BUILTIN_ROW(__sync_fetch_and_or),
1831 BUILTIN_ROW(__sync_fetch_and_and),
1832 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001833 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001834
Chris Lattnerdc046542009-05-08 06:58:22 +00001835 BUILTIN_ROW(__sync_add_and_fetch),
1836 BUILTIN_ROW(__sync_sub_and_fetch),
1837 BUILTIN_ROW(__sync_and_and_fetch),
1838 BUILTIN_ROW(__sync_or_and_fetch),
1839 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001840 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001841
Chris Lattnerdc046542009-05-08 06:58:22 +00001842 BUILTIN_ROW(__sync_val_compare_and_swap),
1843 BUILTIN_ROW(__sync_bool_compare_and_swap),
1844 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001845 BUILTIN_ROW(__sync_lock_release),
1846 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001847 };
Mike Stump11289f42009-09-09 15:08:12 +00001848#undef BUILTIN_ROW
1849
Chris Lattnerdc046542009-05-08 06:58:22 +00001850 // Determine the index of the size.
1851 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001852 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001853 case 1: SizeIndex = 0; break;
1854 case 2: SizeIndex = 1; break;
1855 case 4: SizeIndex = 2; break;
1856 case 8: SizeIndex = 3; break;
1857 case 16: SizeIndex = 4; break;
1858 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001859 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1860 << FirstArg->getType() << FirstArg->getSourceRange();
1861 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001862 }
Mike Stump11289f42009-09-09 15:08:12 +00001863
Chris Lattnerdc046542009-05-08 06:58:22 +00001864 // Each of these builtins has one pointer argument, followed by some number of
1865 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1866 // that we ignore. Find out which row of BuiltinIndices to read from as well
1867 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001868 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001869 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001870 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001871 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001872 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001873 case Builtin::BI__sync_fetch_and_add:
1874 case Builtin::BI__sync_fetch_and_add_1:
1875 case Builtin::BI__sync_fetch_and_add_2:
1876 case Builtin::BI__sync_fetch_and_add_4:
1877 case Builtin::BI__sync_fetch_and_add_8:
1878 case Builtin::BI__sync_fetch_and_add_16:
1879 BuiltinIndex = 0;
1880 break;
1881
1882 case Builtin::BI__sync_fetch_and_sub:
1883 case Builtin::BI__sync_fetch_and_sub_1:
1884 case Builtin::BI__sync_fetch_and_sub_2:
1885 case Builtin::BI__sync_fetch_and_sub_4:
1886 case Builtin::BI__sync_fetch_and_sub_8:
1887 case Builtin::BI__sync_fetch_and_sub_16:
1888 BuiltinIndex = 1;
1889 break;
1890
1891 case Builtin::BI__sync_fetch_and_or:
1892 case Builtin::BI__sync_fetch_and_or_1:
1893 case Builtin::BI__sync_fetch_and_or_2:
1894 case Builtin::BI__sync_fetch_and_or_4:
1895 case Builtin::BI__sync_fetch_and_or_8:
1896 case Builtin::BI__sync_fetch_and_or_16:
1897 BuiltinIndex = 2;
1898 break;
1899
1900 case Builtin::BI__sync_fetch_and_and:
1901 case Builtin::BI__sync_fetch_and_and_1:
1902 case Builtin::BI__sync_fetch_and_and_2:
1903 case Builtin::BI__sync_fetch_and_and_4:
1904 case Builtin::BI__sync_fetch_and_and_8:
1905 case Builtin::BI__sync_fetch_and_and_16:
1906 BuiltinIndex = 3;
1907 break;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Douglas Gregor73722482011-11-28 16:30:08 +00001909 case Builtin::BI__sync_fetch_and_xor:
1910 case Builtin::BI__sync_fetch_and_xor_1:
1911 case Builtin::BI__sync_fetch_and_xor_2:
1912 case Builtin::BI__sync_fetch_and_xor_4:
1913 case Builtin::BI__sync_fetch_and_xor_8:
1914 case Builtin::BI__sync_fetch_and_xor_16:
1915 BuiltinIndex = 4;
1916 break;
1917
Hal Finkeld2208b52014-10-02 20:53:50 +00001918 case Builtin::BI__sync_fetch_and_nand:
1919 case Builtin::BI__sync_fetch_and_nand_1:
1920 case Builtin::BI__sync_fetch_and_nand_2:
1921 case Builtin::BI__sync_fetch_and_nand_4:
1922 case Builtin::BI__sync_fetch_and_nand_8:
1923 case Builtin::BI__sync_fetch_and_nand_16:
1924 BuiltinIndex = 5;
1925 WarnAboutSemanticsChange = true;
1926 break;
1927
Douglas Gregor73722482011-11-28 16:30:08 +00001928 case Builtin::BI__sync_add_and_fetch:
1929 case Builtin::BI__sync_add_and_fetch_1:
1930 case Builtin::BI__sync_add_and_fetch_2:
1931 case Builtin::BI__sync_add_and_fetch_4:
1932 case Builtin::BI__sync_add_and_fetch_8:
1933 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001934 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001935 break;
1936
1937 case Builtin::BI__sync_sub_and_fetch:
1938 case Builtin::BI__sync_sub_and_fetch_1:
1939 case Builtin::BI__sync_sub_and_fetch_2:
1940 case Builtin::BI__sync_sub_and_fetch_4:
1941 case Builtin::BI__sync_sub_and_fetch_8:
1942 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001943 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001944 break;
1945
1946 case Builtin::BI__sync_and_and_fetch:
1947 case Builtin::BI__sync_and_and_fetch_1:
1948 case Builtin::BI__sync_and_and_fetch_2:
1949 case Builtin::BI__sync_and_and_fetch_4:
1950 case Builtin::BI__sync_and_and_fetch_8:
1951 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001952 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001953 break;
1954
1955 case Builtin::BI__sync_or_and_fetch:
1956 case Builtin::BI__sync_or_and_fetch_1:
1957 case Builtin::BI__sync_or_and_fetch_2:
1958 case Builtin::BI__sync_or_and_fetch_4:
1959 case Builtin::BI__sync_or_and_fetch_8:
1960 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001961 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001962 break;
1963
1964 case Builtin::BI__sync_xor_and_fetch:
1965 case Builtin::BI__sync_xor_and_fetch_1:
1966 case Builtin::BI__sync_xor_and_fetch_2:
1967 case Builtin::BI__sync_xor_and_fetch_4:
1968 case Builtin::BI__sync_xor_and_fetch_8:
1969 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001970 BuiltinIndex = 10;
1971 break;
1972
1973 case Builtin::BI__sync_nand_and_fetch:
1974 case Builtin::BI__sync_nand_and_fetch_1:
1975 case Builtin::BI__sync_nand_and_fetch_2:
1976 case Builtin::BI__sync_nand_and_fetch_4:
1977 case Builtin::BI__sync_nand_and_fetch_8:
1978 case Builtin::BI__sync_nand_and_fetch_16:
1979 BuiltinIndex = 11;
1980 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001981 break;
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattnerdc046542009-05-08 06:58:22 +00001983 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001984 case Builtin::BI__sync_val_compare_and_swap_1:
1985 case Builtin::BI__sync_val_compare_and_swap_2:
1986 case Builtin::BI__sync_val_compare_and_swap_4:
1987 case Builtin::BI__sync_val_compare_and_swap_8:
1988 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001989 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001990 NumFixed = 2;
1991 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001992
Chris Lattnerdc046542009-05-08 06:58:22 +00001993 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001994 case Builtin::BI__sync_bool_compare_and_swap_1:
1995 case Builtin::BI__sync_bool_compare_and_swap_2:
1996 case Builtin::BI__sync_bool_compare_and_swap_4:
1997 case Builtin::BI__sync_bool_compare_and_swap_8:
1998 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001999 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002000 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002001 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002002 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002003
2004 case Builtin::BI__sync_lock_test_and_set:
2005 case Builtin::BI__sync_lock_test_and_set_1:
2006 case Builtin::BI__sync_lock_test_and_set_2:
2007 case Builtin::BI__sync_lock_test_and_set_4:
2008 case Builtin::BI__sync_lock_test_and_set_8:
2009 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002010 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002011 break;
2012
Chris Lattnerdc046542009-05-08 06:58:22 +00002013 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002014 case Builtin::BI__sync_lock_release_1:
2015 case Builtin::BI__sync_lock_release_2:
2016 case Builtin::BI__sync_lock_release_4:
2017 case Builtin::BI__sync_lock_release_8:
2018 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002019 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002020 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002021 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002022 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002023
2024 case Builtin::BI__sync_swap:
2025 case Builtin::BI__sync_swap_1:
2026 case Builtin::BI__sync_swap_2:
2027 case Builtin::BI__sync_swap_4:
2028 case Builtin::BI__sync_swap_8:
2029 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002030 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002031 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002032 }
Mike Stump11289f42009-09-09 15:08:12 +00002033
Chris Lattnerdc046542009-05-08 06:58:22 +00002034 // Now that we know how many fixed arguments we expect, first check that we
2035 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002036 if (TheCall->getNumArgs() < 1+NumFixed) {
2037 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2038 << 0 << 1+NumFixed << TheCall->getNumArgs()
2039 << TheCall->getCallee()->getSourceRange();
2040 return ExprError();
2041 }
Mike Stump11289f42009-09-09 15:08:12 +00002042
Hal Finkeld2208b52014-10-02 20:53:50 +00002043 if (WarnAboutSemanticsChange) {
2044 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2045 << TheCall->getCallee()->getSourceRange();
2046 }
2047
Chris Lattner5b9241b2009-05-08 15:36:58 +00002048 // Get the decl for the concrete builtin from this, we can tell what the
2049 // concrete integer type we should convert to is.
2050 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2051 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002052 FunctionDecl *NewBuiltinDecl;
2053 if (NewBuiltinID == BuiltinID)
2054 NewBuiltinDecl = FDecl;
2055 else {
2056 // Perform builtin lookup to avoid redeclaring it.
2057 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2058 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2059 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2060 assert(Res.getFoundDecl());
2061 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002062 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002063 return ExprError();
2064 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002065
John McCallcf142162010-08-07 06:22:56 +00002066 // The first argument --- the pointer --- has a fixed type; we
2067 // deduce the types of the rest of the arguments accordingly. Walk
2068 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002069 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002070 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002071
Chris Lattnerdc046542009-05-08 06:58:22 +00002072 // GCC does an implicit conversion to the pointer or integer ValType. This
2073 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002074 // Initialize the argument.
2075 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2076 ValType, /*consume*/ false);
2077 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002078 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002079 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattnerdc046542009-05-08 06:58:22 +00002081 // Okay, we have something that *can* be converted to the right type. Check
2082 // to see if there is a potentially weird extension going on here. This can
2083 // happen when you do an atomic operation on something like an char* and
2084 // pass in 42. The 42 gets converted to char. This is even more strange
2085 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002086 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002087 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002088 }
Mike Stump11289f42009-09-09 15:08:12 +00002089
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002090 ASTContext& Context = this->getASTContext();
2091
2092 // Create a new DeclRefExpr to refer to the new decl.
2093 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2094 Context,
2095 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002096 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002097 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002098 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002099 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002100 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002101 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002102
Chris Lattnerdc046542009-05-08 06:58:22 +00002103 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002104 // FIXME: This loses syntactic information.
2105 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2106 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2107 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002108 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002109
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002110 // Change the result type of the call to match the original value type. This
2111 // is arbitrary, but the codegen for these builtins ins design to handle it
2112 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002113 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002114
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002115 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002116}
2117
Chris Lattner6436fb62009-02-18 06:01:06 +00002118/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002119/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002120/// Note: It might also make sense to do the UTF-16 conversion here (would
2121/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002122bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002123 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002124 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2125
Douglas Gregorfb65e592011-07-27 05:40:30 +00002126 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002127 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2128 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002129 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002130 }
Mike Stump11289f42009-09-09 15:08:12 +00002131
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002132 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002133 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002134 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002135 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002136 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002137 UTF16 *ToPtr = &ToBuf[0];
2138
2139 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2140 &ToPtr, ToPtr + NumBytes,
2141 strictConversion);
2142 // Check for conversion failure.
2143 if (Result != conversionOK)
2144 Diag(Arg->getLocStart(),
2145 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2146 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002147 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002148}
2149
Chris Lattnere202e6a2007-12-20 00:05:45 +00002150/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2151/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002152bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2153 Expr *Fn = TheCall->getCallee();
2154 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002155 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002156 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002157 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2158 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002159 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002160 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002161 return true;
2162 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002163
2164 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002165 return Diag(TheCall->getLocEnd(),
2166 diag::err_typecheck_call_too_few_args_at_least)
2167 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002168 }
2169
John McCall29ad95b2011-08-27 01:09:30 +00002170 // Type-check the first argument normally.
2171 if (checkBuiltinArgument(*this, TheCall, 0))
2172 return true;
2173
Chris Lattnere202e6a2007-12-20 00:05:45 +00002174 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002175 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002176 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002177 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002178 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002179 else if (FunctionDecl *FD = getCurFunctionDecl())
2180 isVariadic = FD->isVariadic();
2181 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002182 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002183
Chris Lattnere202e6a2007-12-20 00:05:45 +00002184 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002185 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2186 return true;
2187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Chris Lattner43be2e62007-12-19 23:59:04 +00002189 // Verify that the second argument to the builtin is the last argument of the
2190 // current function or method.
2191 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002192 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002193
Nico Weber9eea7642013-05-24 23:31:57 +00002194 // These are valid if SecondArgIsLastNamedArgument is false after the next
2195 // block.
2196 QualType Type;
2197 SourceLocation ParamLoc;
2198
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002199 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2200 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002201 // FIXME: This isn't correct for methods (results in bogus warning).
2202 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002203 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002204 if (CurBlock)
2205 LastArg = *(CurBlock->TheDecl->param_end()-1);
2206 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002207 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002208 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002209 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002210 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002211
2212 Type = PV->getType();
2213 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002214 }
2215 }
Mike Stump11289f42009-09-09 15:08:12 +00002216
Chris Lattner43be2e62007-12-19 23:59:04 +00002217 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002218 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002219 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002220 else if (Type->isReferenceType()) {
2221 Diag(Arg->getLocStart(),
2222 diag::warn_va_start_of_reference_type_is_undefined);
2223 Diag(ParamLoc, diag::note_parameter_type) << Type;
2224 }
2225
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002226 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002227 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002228}
Chris Lattner43be2e62007-12-19 23:59:04 +00002229
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002230bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2231 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2232 // const char *named_addr);
2233
2234 Expr *Func = Call->getCallee();
2235
2236 if (Call->getNumArgs() < 3)
2237 return Diag(Call->getLocEnd(),
2238 diag::err_typecheck_call_too_few_args_at_least)
2239 << 0 /*function call*/ << 3 << Call->getNumArgs();
2240
2241 // Determine whether the current function is variadic or not.
2242 bool IsVariadic;
2243 if (BlockScopeInfo *CurBlock = getCurBlock())
2244 IsVariadic = CurBlock->TheDecl->isVariadic();
2245 else if (FunctionDecl *FD = getCurFunctionDecl())
2246 IsVariadic = FD->isVariadic();
2247 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2248 IsVariadic = MD->isVariadic();
2249 else
2250 llvm_unreachable("unexpected statement type");
2251
2252 if (!IsVariadic) {
2253 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2254 return true;
2255 }
2256
2257 // Type-check the first argument normally.
2258 if (checkBuiltinArgument(*this, Call, 0))
2259 return true;
2260
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002261 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002262 unsigned ArgNo;
2263 QualType Type;
2264 } ArgumentTypes[] = {
2265 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2266 { 2, Context.getSizeType() },
2267 };
2268
2269 for (const auto &AT : ArgumentTypes) {
2270 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2271 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2272 continue;
2273 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2274 << Arg->getType() << AT.Type << 1 /* different class */
2275 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2276 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2277 }
2278
2279 return false;
2280}
2281
Chris Lattner2da14fb2007-12-20 00:26:33 +00002282/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2283/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002284bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2285 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002286 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002287 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002288 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002289 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002290 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002291 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002292 << SourceRange(TheCall->getArg(2)->getLocStart(),
2293 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002294
John Wiegley01296292011-04-08 18:41:53 +00002295 ExprResult OrigArg0 = TheCall->getArg(0);
2296 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002297
Chris Lattner2da14fb2007-12-20 00:26:33 +00002298 // Do standard promotions between the two arguments, returning their common
2299 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002300 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002301 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2302 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002303
2304 // Make sure any conversions are pushed back into the call; this is
2305 // type safe since unordered compare builtins are declared as "_Bool
2306 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002307 TheCall->setArg(0, OrigArg0.get());
2308 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002309
John Wiegley01296292011-04-08 18:41:53 +00002310 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002311 return false;
2312
Chris Lattner2da14fb2007-12-20 00:26:33 +00002313 // If the common type isn't a real floating type, then the arguments were
2314 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002315 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002316 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002317 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002318 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2319 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002320
Chris Lattner2da14fb2007-12-20 00:26:33 +00002321 return false;
2322}
2323
Benjamin Kramer634fc102010-02-15 22:42:31 +00002324/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2325/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002326/// to check everything. We expect the last argument to be a floating point
2327/// value.
2328bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2329 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002330 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002331 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002332 if (TheCall->getNumArgs() > NumArgs)
2333 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002334 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002335 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002336 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002337 (*(TheCall->arg_end()-1))->getLocEnd());
2338
Benjamin Kramer64aae502010-02-16 10:07:31 +00002339 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002340
Eli Friedman7e4faac2009-08-31 20:06:00 +00002341 if (OrigArg->isTypeDependent())
2342 return false;
2343
Chris Lattner68784ef2010-05-06 05:50:07 +00002344 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002345 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002346 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002347 diag::err_typecheck_call_invalid_unary_fp)
2348 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002349
Chris Lattner68784ef2010-05-06 05:50:07 +00002350 // If this is an implicit conversion from float -> double, remove it.
2351 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2352 Expr *CastArg = Cast->getSubExpr();
2353 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2354 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2355 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002356 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002357 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002358 }
2359 }
2360
Eli Friedman7e4faac2009-08-31 20:06:00 +00002361 return false;
2362}
2363
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002364/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2365// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002366ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002367 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002368 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002369 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002370 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2371 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002372
Nate Begemana0110022010-06-08 00:16:34 +00002373 // Determine which of the following types of shufflevector we're checking:
2374 // 1) unary, vector mask: (lhs, mask)
2375 // 2) binary, vector mask: (lhs, rhs, mask)
2376 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2377 QualType resType = TheCall->getArg(0)->getType();
2378 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002379
Douglas Gregorc25f7662009-05-19 22:10:17 +00002380 if (!TheCall->getArg(0)->isTypeDependent() &&
2381 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002382 QualType LHSType = TheCall->getArg(0)->getType();
2383 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002384
Craig Topperbaca3892013-07-29 06:47:04 +00002385 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2386 return ExprError(Diag(TheCall->getLocStart(),
2387 diag::err_shufflevector_non_vector)
2388 << SourceRange(TheCall->getArg(0)->getLocStart(),
2389 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002390
Nate Begemana0110022010-06-08 00:16:34 +00002391 numElements = LHSType->getAs<VectorType>()->getNumElements();
2392 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002393
Nate Begemana0110022010-06-08 00:16:34 +00002394 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2395 // with mask. If so, verify that RHS is an integer vector type with the
2396 // same number of elts as lhs.
2397 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002398 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002399 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002400 return ExprError(Diag(TheCall->getLocStart(),
2401 diag::err_shufflevector_incompatible_vector)
2402 << SourceRange(TheCall->getArg(1)->getLocStart(),
2403 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002404 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002405 return ExprError(Diag(TheCall->getLocStart(),
2406 diag::err_shufflevector_incompatible_vector)
2407 << SourceRange(TheCall->getArg(0)->getLocStart(),
2408 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002409 } else if (numElements != numResElements) {
2410 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002411 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002412 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002413 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002414 }
2415
2416 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002417 if (TheCall->getArg(i)->isTypeDependent() ||
2418 TheCall->getArg(i)->isValueDependent())
2419 continue;
2420
Nate Begemana0110022010-06-08 00:16:34 +00002421 llvm::APSInt Result(32);
2422 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2423 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002424 diag::err_shufflevector_nonconstant_argument)
2425 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002426
Craig Topper50ad5b72013-08-03 17:40:38 +00002427 // Allow -1 which will be translated to undef in the IR.
2428 if (Result.isSigned() && Result.isAllOnesValue())
2429 continue;
2430
Chris Lattner7ab824e2008-08-10 02:05:13 +00002431 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002432 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002433 diag::err_shufflevector_argument_too_large)
2434 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002435 }
2436
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002437 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002438
Chris Lattner7ab824e2008-08-10 02:05:13 +00002439 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002440 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002441 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002442 }
2443
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002444 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2445 TheCall->getCallee()->getLocStart(),
2446 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002447}
Chris Lattner43be2e62007-12-19 23:59:04 +00002448
Hal Finkelc4d7c822013-09-18 03:29:45 +00002449/// SemaConvertVectorExpr - Handle __builtin_convertvector
2450ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2451 SourceLocation BuiltinLoc,
2452 SourceLocation RParenLoc) {
2453 ExprValueKind VK = VK_RValue;
2454 ExprObjectKind OK = OK_Ordinary;
2455 QualType DstTy = TInfo->getType();
2456 QualType SrcTy = E->getType();
2457
2458 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2459 return ExprError(Diag(BuiltinLoc,
2460 diag::err_convertvector_non_vector)
2461 << E->getSourceRange());
2462 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2463 return ExprError(Diag(BuiltinLoc,
2464 diag::err_convertvector_non_vector_type));
2465
2466 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2467 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2468 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2469 if (SrcElts != DstElts)
2470 return ExprError(Diag(BuiltinLoc,
2471 diag::err_convertvector_incompatible_vector)
2472 << E->getSourceRange());
2473 }
2474
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002475 return new (Context)
2476 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002477}
2478
Daniel Dunbarb7257262008-07-21 22:59:13 +00002479/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2480// This is declared to take (const void*, ...) and can take two
2481// optional constant int args.
2482bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002483 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002484
Chris Lattner3b054132008-11-19 05:08:23 +00002485 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002486 return Diag(TheCall->getLocEnd(),
2487 diag::err_typecheck_call_too_many_args_at_most)
2488 << 0 /*function call*/ << 3 << NumArgs
2489 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002490
2491 // Argument 0 is checked for us and the remaining arguments must be
2492 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002493 for (unsigned i = 1; i != NumArgs; ++i)
2494 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002495 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002496
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002497 return false;
2498}
2499
Hal Finkelf0417332014-07-17 14:25:55 +00002500/// SemaBuiltinAssume - Handle __assume (MS Extension).
2501// __assume does not evaluate its arguments, and should warn if its argument
2502// has side effects.
2503bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2504 Expr *Arg = TheCall->getArg(0);
2505 if (Arg->isInstantiationDependent()) return false;
2506
2507 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002508 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002509 << Arg->getSourceRange()
2510 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2511
2512 return false;
2513}
2514
2515/// Handle __builtin_assume_aligned. This is declared
2516/// as (const void*, size_t, ...) and can take one optional constant int arg.
2517bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2518 unsigned NumArgs = TheCall->getNumArgs();
2519
2520 if (NumArgs > 3)
2521 return Diag(TheCall->getLocEnd(),
2522 diag::err_typecheck_call_too_many_args_at_most)
2523 << 0 /*function call*/ << 3 << NumArgs
2524 << TheCall->getSourceRange();
2525
2526 // The alignment must be a constant integer.
2527 Expr *Arg = TheCall->getArg(1);
2528
2529 // We can't check the value of a dependent argument.
2530 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2531 llvm::APSInt Result;
2532 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2533 return true;
2534
2535 if (!Result.isPowerOf2())
2536 return Diag(TheCall->getLocStart(),
2537 diag::err_alignment_not_power_of_two)
2538 << Arg->getSourceRange();
2539 }
2540
2541 if (NumArgs > 2) {
2542 ExprResult Arg(TheCall->getArg(2));
2543 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2544 Context.getSizeType(), false);
2545 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2546 if (Arg.isInvalid()) return true;
2547 TheCall->setArg(2, Arg.get());
2548 }
Hal Finkelf0417332014-07-17 14:25:55 +00002549
2550 return false;
2551}
2552
Eric Christopher8d0c6212010-04-17 02:26:23 +00002553/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2554/// TheCall is a constant expression.
2555bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2556 llvm::APSInt &Result) {
2557 Expr *Arg = TheCall->getArg(ArgNum);
2558 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2559 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2560
2561 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2562
2563 if (!Arg->isIntegerConstantExpr(Result, Context))
2564 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002565 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002566
Chris Lattnerd545ad12009-09-23 06:06:36 +00002567 return false;
2568}
2569
Richard Sandiford28940af2014-04-16 08:47:51 +00002570/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2571/// TheCall is a constant expression in the range [Low, High].
2572bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2573 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002574 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002575
2576 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002577 Expr *Arg = TheCall->getArg(ArgNum);
2578 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002579 return false;
2580
Eric Christopher8d0c6212010-04-17 02:26:23 +00002581 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002582 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002583 return true;
2584
Richard Sandiford28940af2014-04-16 08:47:51 +00002585 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002586 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002587 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002588
2589 return false;
2590}
2591
Eli Friedmanc97d0142009-05-03 06:04:26 +00002592/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002593/// This checks that the target supports __builtin_longjmp and
2594/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002595bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002596 if (!Context.getTargetInfo().hasSjLjLowering())
2597 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2598 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2599
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002600 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002601 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002602
Eric Christopher8d0c6212010-04-17 02:26:23 +00002603 // TODO: This is less than ideal. Overload this to take a value.
2604 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2605 return true;
2606
2607 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002608 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2609 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2610
2611 return false;
2612}
2613
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002614
2615/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2616/// This checks that the target supports __builtin_setjmp.
2617bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2618 if (!Context.getTargetInfo().hasSjLjLowering())
2619 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2620 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2621 return false;
2622}
2623
Richard Smithd7293d72013-08-05 18:49:43 +00002624namespace {
2625enum StringLiteralCheckType {
2626 SLCT_NotALiteral,
2627 SLCT_UncheckedLiteral,
2628 SLCT_CheckedLiteral
2629};
2630}
2631
Richard Smith55ce3522012-06-25 20:30:08 +00002632// Determine if an expression is a string literal or constant string.
2633// If this function returns false on the arguments to a function expecting a
2634// format string, we will usually need to emit a warning.
2635// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002636static StringLiteralCheckType
2637checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2638 bool HasVAListArg, unsigned format_idx,
2639 unsigned firstDataArg, Sema::FormatStringType Type,
2640 Sema::VariadicCallType CallType, bool InFunctionCall,
2641 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002642 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002643 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002644 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002645
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002646 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002647
Richard Smithd7293d72013-08-05 18:49:43 +00002648 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002649 // Technically -Wformat-nonliteral does not warn about this case.
2650 // The behavior of printf and friends in this case is implementation
2651 // dependent. Ideally if the format string cannot be null then
2652 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002653 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002654
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002655 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002656 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002657 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002658 // The expression is a literal if both sub-expressions were, and it was
2659 // completely checked only if both sub-expressions were checked.
2660 const AbstractConditionalOperator *C =
2661 cast<AbstractConditionalOperator>(E);
2662 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002663 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002664 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002665 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002666 if (Left == SLCT_NotALiteral)
2667 return SLCT_NotALiteral;
2668 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002669 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002670 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002671 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002672 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002673 }
2674
2675 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002676 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2677 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002678 }
2679
John McCallc07a0c72011-02-17 10:25:35 +00002680 case Stmt::OpaqueValueExprClass:
2681 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2682 E = src;
2683 goto tryAgain;
2684 }
Richard Smith55ce3522012-06-25 20:30:08 +00002685 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002686
Ted Kremeneka8890832011-02-24 23:03:04 +00002687 case Stmt::PredefinedExprClass:
2688 // While __func__, etc., are technically not string literals, they
2689 // cannot contain format specifiers and thus are not a security
2690 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002691 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002692
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002693 case Stmt::DeclRefExprClass: {
2694 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002695
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002696 // As an exception, do not flag errors for variables binding to
2697 // const string literals.
2698 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2699 bool isConstant = false;
2700 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002701
Richard Smithd7293d72013-08-05 18:49:43 +00002702 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2703 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002704 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002705 isConstant = T.isConstant(S.Context) &&
2706 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002707 } else if (T->isObjCObjectPointerType()) {
2708 // In ObjC, there is usually no "const ObjectPointer" type,
2709 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002710 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002711 }
Mike Stump11289f42009-09-09 15:08:12 +00002712
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002713 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002714 if (const Expr *Init = VD->getAnyInitializer()) {
2715 // Look through initializers like const char c[] = { "foo" }
2716 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2717 if (InitList->isStringLiteralInit())
2718 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2719 }
Richard Smithd7293d72013-08-05 18:49:43 +00002720 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002721 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002722 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002723 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002724 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002725 }
Mike Stump11289f42009-09-09 15:08:12 +00002726
Anders Carlssonb012ca92009-06-28 19:55:58 +00002727 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2728 // special check to see if the format string is a function parameter
2729 // of the function calling the printf function. If the function
2730 // has an attribute indicating it is a printf-like function, then we
2731 // should suppress warnings concerning non-literals being used in a call
2732 // to a vprintf function. For example:
2733 //
2734 // void
2735 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2736 // va_list ap;
2737 // va_start(ap, fmt);
2738 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2739 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002740 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002741 if (HasVAListArg) {
2742 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2743 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2744 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002745 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002746 // adjust for implicit parameter
2747 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2748 if (MD->isInstance())
2749 ++PVIndex;
2750 // We also check if the formats are compatible.
2751 // We can't pass a 'scanf' string to a 'printf' function.
2752 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002753 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002754 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002755 }
2756 }
2757 }
2758 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002759 }
Mike Stump11289f42009-09-09 15:08:12 +00002760
Richard Smith55ce3522012-06-25 20:30:08 +00002761 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002762 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002763
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002764 case Stmt::CallExprClass:
2765 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002766 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002767 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2768 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2769 unsigned ArgIndex = FA->getFormatIdx();
2770 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2771 if (MD->isInstance())
2772 --ArgIndex;
2773 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002774
Richard Smithd7293d72013-08-05 18:49:43 +00002775 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002776 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002777 Type, CallType, InFunctionCall,
2778 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002779 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2780 unsigned BuiltinID = FD->getBuiltinID();
2781 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2782 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2783 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002784 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002785 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002786 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002787 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002788 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002789 }
2790 }
Mike Stump11289f42009-09-09 15:08:12 +00002791
Richard Smith55ce3522012-06-25 20:30:08 +00002792 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002793 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002794 case Stmt::ObjCStringLiteralClass:
2795 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002796 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002797
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002798 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002799 StrE = ObjCFExpr->getString();
2800 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002801 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002802
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002803 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002804 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2805 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002806 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
Richard Smith55ce3522012-06-25 20:30:08 +00002809 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002810 }
Mike Stump11289f42009-09-09 15:08:12 +00002811
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002812 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002813 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002814 }
2815}
2816
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002817Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002818 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002819 .Case("scanf", FST_Scanf)
2820 .Cases("printf", "printf0", FST_Printf)
2821 .Cases("NSString", "CFString", FST_NSString)
2822 .Case("strftime", FST_Strftime)
2823 .Case("strfmon", FST_Strfmon)
2824 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002825 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002826 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002827 .Default(FST_Unknown);
2828}
2829
Jordan Rose3e0ec582012-07-19 18:10:23 +00002830/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002831/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002832/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002833bool Sema::CheckFormatArguments(const FormatAttr *Format,
2834 ArrayRef<const Expr *> Args,
2835 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002836 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002837 SourceLocation Loc, SourceRange Range,
2838 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002839 FormatStringInfo FSI;
2840 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002841 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002842 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002843 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002844 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002845}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002846
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002847bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002848 bool HasVAListArg, unsigned format_idx,
2849 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002850 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002851 SourceLocation Loc, SourceRange Range,
2852 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002853 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002854 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002855 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002856 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002857 }
Mike Stump11289f42009-09-09 15:08:12 +00002858
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002859 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002860
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002861 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002862 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002863 // Dynamically generated format strings are difficult to
2864 // automatically vet at compile time. Requiring that format strings
2865 // are string literals: (1) permits the checking of format strings by
2866 // the compiler and thereby (2) can practically remove the source of
2867 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002868
Mike Stump11289f42009-09-09 15:08:12 +00002869 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002870 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002871 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002872 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002873 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002874 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2875 format_idx, firstDataArg, Type, CallType,
2876 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002877 if (CT != SLCT_NotALiteral)
2878 // Literal format string found, check done!
2879 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002880
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002881 // Strftime is particular as it always uses a single 'time' argument,
2882 // so it is safe to pass a non-literal string.
2883 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002884 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002885
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002886 // Do not emit diag when the string param is a macro expansion and the
2887 // format is either NSString or CFString. This is a hack to prevent
2888 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2889 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002890 if (Type == FST_NSString &&
2891 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002892 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002893
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002894 // If there are no arguments specified, warn with -Wformat-security, otherwise
2895 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002896 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002897 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002898 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002899 << OrigFormatExpr->getSourceRange();
2900 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002901 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002902 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002903 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002904 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002905}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002906
Ted Kremenekab278de2010-01-28 23:39:18 +00002907namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002908class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2909protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002910 Sema &S;
2911 const StringLiteral *FExpr;
2912 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002913 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002914 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002915 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002916 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002917 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002918 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002919 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002920 bool usesPositionalArgs;
2921 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002922 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002923 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002924 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002925public:
Ted Kremenek02087932010-07-16 02:11:22 +00002926 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002927 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002928 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002929 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002930 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002931 Sema::VariadicCallType callType,
2932 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002933 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002934 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2935 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002936 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002937 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002938 inFunctionCall(inFunctionCall), CallType(callType),
2939 CheckedVarArgs(CheckedVarArgs) {
2940 CoveredArgs.resize(numDataArgs);
2941 CoveredArgs.reset();
2942 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002943
Ted Kremenek019d2242010-01-29 01:50:07 +00002944 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002945
Ted Kremenek02087932010-07-16 02:11:22 +00002946 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002947 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002948
Jordan Rose92303592012-09-08 04:00:03 +00002949 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002950 const analyze_format_string::FormatSpecifier &FS,
2951 const analyze_format_string::ConversionSpecifier &CS,
2952 const char *startSpecifier, unsigned specifierLen,
2953 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002954
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002955 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002956 const analyze_format_string::FormatSpecifier &FS,
2957 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002958
2959 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002960 const analyze_format_string::ConversionSpecifier &CS,
2961 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002962
Craig Toppere14c0f82014-03-12 04:55:44 +00002963 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002964
Craig Toppere14c0f82014-03-12 04:55:44 +00002965 void HandleInvalidPosition(const char *startSpecifier,
2966 unsigned specifierLen,
2967 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002968
Craig Toppere14c0f82014-03-12 04:55:44 +00002969 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002970
Craig Toppere14c0f82014-03-12 04:55:44 +00002971 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002972
Richard Trieu03cf7b72011-10-28 00:41:25 +00002973 template <typename Range>
2974 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2975 const Expr *ArgumentExpr,
2976 PartialDiagnostic PDiag,
2977 SourceLocation StringLoc,
2978 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002979 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002980
Ted Kremenek02087932010-07-16 02:11:22 +00002981protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002982 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2983 const char *startSpec,
2984 unsigned specifierLen,
2985 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002986
2987 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2988 const char *startSpec,
2989 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002990
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002991 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002992 CharSourceRange getSpecifierRange(const char *startSpecifier,
2993 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002994 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002995
Ted Kremenek5739de72010-01-29 01:06:55 +00002996 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002997
2998 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2999 const analyze_format_string::ConversionSpecifier &CS,
3000 const char *startSpecifier, unsigned specifierLen,
3001 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003002
3003 template <typename Range>
3004 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3005 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003006 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003007};
3008}
3009
Ted Kremenek02087932010-07-16 02:11:22 +00003010SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003011 return OrigFormatExpr->getSourceRange();
3012}
3013
Ted Kremenek02087932010-07-16 02:11:22 +00003014CharSourceRange CheckFormatHandler::
3015getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003016 SourceLocation Start = getLocationOfByte(startSpecifier);
3017 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3018
3019 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003020 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003021
3022 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003023}
3024
Ted Kremenek02087932010-07-16 02:11:22 +00003025SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003026 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003027}
3028
Ted Kremenek02087932010-07-16 02:11:22 +00003029void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3030 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003031 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3032 getLocationOfByte(startSpecifier),
3033 /*IsStringLocation*/true,
3034 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003035}
3036
Jordan Rose92303592012-09-08 04:00:03 +00003037void CheckFormatHandler::HandleInvalidLengthModifier(
3038 const analyze_format_string::FormatSpecifier &FS,
3039 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003040 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003041 using namespace analyze_format_string;
3042
3043 const LengthModifier &LM = FS.getLengthModifier();
3044 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3045
3046 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003047 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003048 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003049 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003050 getLocationOfByte(LM.getStart()),
3051 /*IsStringLocation*/true,
3052 getSpecifierRange(startSpecifier, specifierLen));
3053
3054 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3055 << FixedLM->toString()
3056 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3057
3058 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003059 FixItHint Hint;
3060 if (DiagID == diag::warn_format_nonsensical_length)
3061 Hint = FixItHint::CreateRemoval(LMRange);
3062
3063 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003064 getLocationOfByte(LM.getStart()),
3065 /*IsStringLocation*/true,
3066 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003067 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003068 }
3069}
3070
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003071void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003072 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003073 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003074 using namespace analyze_format_string;
3075
3076 const LengthModifier &LM = FS.getLengthModifier();
3077 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3078
3079 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003080 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003081 if (FixedLM) {
3082 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3083 << LM.toString() << 0,
3084 getLocationOfByte(LM.getStart()),
3085 /*IsStringLocation*/true,
3086 getSpecifierRange(startSpecifier, specifierLen));
3087
3088 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3089 << FixedLM->toString()
3090 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3091
3092 } else {
3093 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3094 << LM.toString() << 0,
3095 getLocationOfByte(LM.getStart()),
3096 /*IsStringLocation*/true,
3097 getSpecifierRange(startSpecifier, specifierLen));
3098 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003099}
3100
3101void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3102 const analyze_format_string::ConversionSpecifier &CS,
3103 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003104 using namespace analyze_format_string;
3105
3106 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003107 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003108 if (FixedCS) {
3109 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3110 << CS.toString() << /*conversion specifier*/1,
3111 getLocationOfByte(CS.getStart()),
3112 /*IsStringLocation*/true,
3113 getSpecifierRange(startSpecifier, specifierLen));
3114
3115 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3116 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3117 << FixedCS->toString()
3118 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3119 } else {
3120 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3121 << CS.toString() << /*conversion specifier*/1,
3122 getLocationOfByte(CS.getStart()),
3123 /*IsStringLocation*/true,
3124 getSpecifierRange(startSpecifier, specifierLen));
3125 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003126}
3127
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003128void CheckFormatHandler::HandlePosition(const char *startPos,
3129 unsigned posLen) {
3130 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3131 getLocationOfByte(startPos),
3132 /*IsStringLocation*/true,
3133 getSpecifierRange(startPos, posLen));
3134}
3135
Ted Kremenekd1668192010-02-27 01:41:03 +00003136void
Ted Kremenek02087932010-07-16 02:11:22 +00003137CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3138 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003139 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3140 << (unsigned) p,
3141 getLocationOfByte(startPos), /*IsStringLocation*/true,
3142 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003143}
3144
Ted Kremenek02087932010-07-16 02:11:22 +00003145void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003146 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003147 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3148 getLocationOfByte(startPos),
3149 /*IsStringLocation*/true,
3150 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003151}
3152
Ted Kremenek02087932010-07-16 02:11:22 +00003153void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003154 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003155 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003156 EmitFormatDiagnostic(
3157 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3158 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3159 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003160 }
Ted Kremenek02087932010-07-16 02:11:22 +00003161}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003162
Jordan Rose58bbe422012-07-19 18:10:08 +00003163// Note that this may return NULL if there was an error parsing or building
3164// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003165const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003166 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003167}
3168
3169void CheckFormatHandler::DoneProcessing() {
3170 // Does the number of data arguments exceed the number of
3171 // format conversions in the format string?
3172 if (!HasVAListArg) {
3173 // Find any arguments that weren't covered.
3174 CoveredArgs.flip();
3175 signed notCoveredArg = CoveredArgs.find_first();
3176 if (notCoveredArg >= 0) {
3177 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003178 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3179 SourceLocation Loc = E->getLocStart();
3180 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3181 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3182 Loc, /*IsStringLocation*/false,
3183 getFormatStringRange());
3184 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003185 }
Ted Kremenek02087932010-07-16 02:11:22 +00003186 }
3187 }
3188}
3189
Ted Kremenekce815422010-07-19 21:25:57 +00003190bool
3191CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3192 SourceLocation Loc,
3193 const char *startSpec,
3194 unsigned specifierLen,
3195 const char *csStart,
3196 unsigned csLen) {
3197
3198 bool keepGoing = true;
3199 if (argIndex < NumDataArgs) {
3200 // Consider the argument coverered, even though the specifier doesn't
3201 // make sense.
3202 CoveredArgs.set(argIndex);
3203 }
3204 else {
3205 // If argIndex exceeds the number of data arguments we
3206 // don't issue a warning because that is just a cascade of warnings (and
3207 // they may have intended '%%' anyway). We don't want to continue processing
3208 // the format string after this point, however, as we will like just get
3209 // gibberish when trying to match arguments.
3210 keepGoing = false;
3211 }
3212
Richard Trieu03cf7b72011-10-28 00:41:25 +00003213 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3214 << StringRef(csStart, csLen),
3215 Loc, /*IsStringLocation*/true,
3216 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003217
3218 return keepGoing;
3219}
3220
Richard Trieu03cf7b72011-10-28 00:41:25 +00003221void
3222CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3223 const char *startSpec,
3224 unsigned specifierLen) {
3225 EmitFormatDiagnostic(
3226 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3227 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3228}
3229
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003230bool
3231CheckFormatHandler::CheckNumArgs(
3232 const analyze_format_string::FormatSpecifier &FS,
3233 const analyze_format_string::ConversionSpecifier &CS,
3234 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3235
3236 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003237 PartialDiagnostic PDiag = FS.usesPositionalArg()
3238 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3239 << (argIndex+1) << NumDataArgs)
3240 : S.PDiag(diag::warn_printf_insufficient_data_args);
3241 EmitFormatDiagnostic(
3242 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3243 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003244 return false;
3245 }
3246 return true;
3247}
3248
Richard Trieu03cf7b72011-10-28 00:41:25 +00003249template<typename Range>
3250void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3251 SourceLocation Loc,
3252 bool IsStringLocation,
3253 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003254 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003255 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003256 Loc, IsStringLocation, StringRange, FixIt);
3257}
3258
3259/// \brief If the format string is not within the funcion call, emit a note
3260/// so that the function call and string are in diagnostic messages.
3261///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003262/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003263/// call and only one diagnostic message will be produced. Otherwise, an
3264/// extra note will be emitted pointing to location of the format string.
3265///
3266/// \param ArgumentExpr the expression that is passed as the format string
3267/// argument in the function call. Used for getting locations when two
3268/// diagnostics are emitted.
3269///
3270/// \param PDiag the callee should already have provided any strings for the
3271/// diagnostic message. This function only adds locations and fixits
3272/// to diagnostics.
3273///
3274/// \param Loc primary location for diagnostic. If two diagnostics are
3275/// required, one will be at Loc and a new SourceLocation will be created for
3276/// the other one.
3277///
3278/// \param IsStringLocation if true, Loc points to the format string should be
3279/// used for the note. Otherwise, Loc points to the argument list and will
3280/// be used with PDiag.
3281///
3282/// \param StringRange some or all of the string to highlight. This is
3283/// templated so it can accept either a CharSourceRange or a SourceRange.
3284///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003285/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003286template<typename Range>
3287void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3288 const Expr *ArgumentExpr,
3289 PartialDiagnostic PDiag,
3290 SourceLocation Loc,
3291 bool IsStringLocation,
3292 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003293 ArrayRef<FixItHint> FixIt) {
3294 if (InFunctionCall) {
3295 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3296 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003297 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003298 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003299 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3300 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003301
3302 const Sema::SemaDiagnosticBuilder &Note =
3303 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3304 diag::note_format_string_defined);
3305
3306 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003307 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003308 }
3309}
3310
Ted Kremenek02087932010-07-16 02:11:22 +00003311//===--- CHECK: Printf format string checking ------------------------------===//
3312
3313namespace {
3314class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003315 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003316public:
3317 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3318 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003319 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003320 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003321 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003322 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003323 Sema::VariadicCallType CallType,
3324 llvm::SmallBitVector &CheckedVarArgs)
3325 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3326 numDataArgs, beg, hasVAListArg, Args,
3327 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3328 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003329 {}
3330
Craig Toppere14c0f82014-03-12 04:55:44 +00003331
Ted Kremenek02087932010-07-16 02:11:22 +00003332 bool HandleInvalidPrintfConversionSpecifier(
3333 const analyze_printf::PrintfSpecifier &FS,
3334 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003335 unsigned specifierLen) override;
3336
Ted Kremenek02087932010-07-16 02:11:22 +00003337 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3338 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003339 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003340 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3341 const char *StartSpecifier,
3342 unsigned SpecifierLen,
3343 const Expr *E);
3344
Ted Kremenek02087932010-07-16 02:11:22 +00003345 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3346 const char *startSpecifier, unsigned specifierLen);
3347 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3348 const analyze_printf::OptionalAmount &Amt,
3349 unsigned type,
3350 const char *startSpecifier, unsigned specifierLen);
3351 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3352 const analyze_printf::OptionalFlag &flag,
3353 const char *startSpecifier, unsigned specifierLen);
3354 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3355 const analyze_printf::OptionalFlag &ignoredFlag,
3356 const analyze_printf::OptionalFlag &flag,
3357 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003358 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003359 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003360
Ted Kremenek02087932010-07-16 02:11:22 +00003361};
3362}
3363
3364bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3365 const analyze_printf::PrintfSpecifier &FS,
3366 const char *startSpecifier,
3367 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003368 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003369 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003370
Ted Kremenekce815422010-07-19 21:25:57 +00003371 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3372 getLocationOfByte(CS.getStart()),
3373 startSpecifier, specifierLen,
3374 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003375}
3376
Ted Kremenek02087932010-07-16 02:11:22 +00003377bool CheckPrintfHandler::HandleAmount(
3378 const analyze_format_string::OptionalAmount &Amt,
3379 unsigned k, const char *startSpecifier,
3380 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003381
3382 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003383 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003384 unsigned argIndex = Amt.getArgIndex();
3385 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003386 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3387 << k,
3388 getLocationOfByte(Amt.getStart()),
3389 /*IsStringLocation*/true,
3390 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003391 // Don't do any more checking. We will just emit
3392 // spurious errors.
3393 return false;
3394 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003395
Ted Kremenek5739de72010-01-29 01:06:55 +00003396 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003397 // Although not in conformance with C99, we also allow the argument to be
3398 // an 'unsigned int' as that is a reasonably safe case. GCC also
3399 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003400 CoveredArgs.set(argIndex);
3401 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003402 if (!Arg)
3403 return false;
3404
Ted Kremenek5739de72010-01-29 01:06:55 +00003405 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003406
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003407 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3408 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003409
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003410 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003411 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003412 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003413 << T << Arg->getSourceRange(),
3414 getLocationOfByte(Amt.getStart()),
3415 /*IsStringLocation*/true,
3416 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003417 // Don't do any more checking. We will just emit
3418 // spurious errors.
3419 return false;
3420 }
3421 }
3422 }
3423 return true;
3424}
Ted Kremenek5739de72010-01-29 01:06:55 +00003425
Tom Careb49ec692010-06-17 19:00:27 +00003426void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003427 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003428 const analyze_printf::OptionalAmount &Amt,
3429 unsigned type,
3430 const char *startSpecifier,
3431 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003432 const analyze_printf::PrintfConversionSpecifier &CS =
3433 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003434
Richard Trieu03cf7b72011-10-28 00:41:25 +00003435 FixItHint fixit =
3436 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3437 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3438 Amt.getConstantLength()))
3439 : FixItHint();
3440
3441 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3442 << type << CS.toString(),
3443 getLocationOfByte(Amt.getStart()),
3444 /*IsStringLocation*/true,
3445 getSpecifierRange(startSpecifier, specifierLen),
3446 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003447}
3448
Ted Kremenek02087932010-07-16 02:11:22 +00003449void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003450 const analyze_printf::OptionalFlag &flag,
3451 const char *startSpecifier,
3452 unsigned specifierLen) {
3453 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003454 const analyze_printf::PrintfConversionSpecifier &CS =
3455 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003456 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3457 << flag.toString() << CS.toString(),
3458 getLocationOfByte(flag.getPosition()),
3459 /*IsStringLocation*/true,
3460 getSpecifierRange(startSpecifier, specifierLen),
3461 FixItHint::CreateRemoval(
3462 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003463}
3464
3465void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003466 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003467 const analyze_printf::OptionalFlag &ignoredFlag,
3468 const analyze_printf::OptionalFlag &flag,
3469 const char *startSpecifier,
3470 unsigned specifierLen) {
3471 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003472 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3473 << ignoredFlag.toString() << flag.toString(),
3474 getLocationOfByte(ignoredFlag.getPosition()),
3475 /*IsStringLocation*/true,
3476 getSpecifierRange(startSpecifier, specifierLen),
3477 FixItHint::CreateRemoval(
3478 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003479}
3480
Richard Smith55ce3522012-06-25 20:30:08 +00003481// Determines if the specified is a C++ class or struct containing
3482// a member with the specified name and kind (e.g. a CXXMethodDecl named
3483// "c_str()").
3484template<typename MemberKind>
3485static llvm::SmallPtrSet<MemberKind*, 1>
3486CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3487 const RecordType *RT = Ty->getAs<RecordType>();
3488 llvm::SmallPtrSet<MemberKind*, 1> Results;
3489
3490 if (!RT)
3491 return Results;
3492 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003493 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003494 return Results;
3495
Alp Tokerb6cc5922014-05-03 03:45:55 +00003496 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003497 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003498 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003499
3500 // We just need to include all members of the right kind turned up by the
3501 // filter, at this point.
3502 if (S.LookupQualifiedName(R, RT->getDecl()))
3503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3504 NamedDecl *decl = (*I)->getUnderlyingDecl();
3505 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3506 Results.insert(FK);
3507 }
3508 return Results;
3509}
3510
Richard Smith2868a732014-02-28 01:36:39 +00003511/// Check if we could call '.c_str()' on an object.
3512///
3513/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3514/// allow the call, or if it would be ambiguous).
3515bool Sema::hasCStrMethod(const Expr *E) {
3516 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3517 MethodSet Results =
3518 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3519 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3520 MI != ME; ++MI)
3521 if ((*MI)->getMinRequiredArguments() == 0)
3522 return true;
3523 return false;
3524}
3525
Richard Smith55ce3522012-06-25 20:30:08 +00003526// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003527// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003528// Returns true when a c_str() conversion method is found.
3529bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003530 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003531 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3532
3533 MethodSet Results =
3534 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3535
3536 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3537 MI != ME; ++MI) {
3538 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003539 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003540 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003541 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003542 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003543 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3544 << "c_str()"
3545 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3546 return true;
3547 }
3548 }
3549
3550 return false;
3551}
3552
Ted Kremenekab278de2010-01-28 23:39:18 +00003553bool
Ted Kremenek02087932010-07-16 02:11:22 +00003554CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003555 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003556 const char *startSpecifier,
3557 unsigned specifierLen) {
3558
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003559 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003560 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003561 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003562
Ted Kremenek6cd69422010-07-19 22:01:06 +00003563 if (FS.consumesDataArgument()) {
3564 if (atFirstArg) {
3565 atFirstArg = false;
3566 usesPositionalArgs = FS.usesPositionalArg();
3567 }
3568 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003569 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3570 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003571 return false;
3572 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003573 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003574
Ted Kremenekd1668192010-02-27 01:41:03 +00003575 // First check if the field width, precision, and conversion specifier
3576 // have matching data arguments.
3577 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3578 startSpecifier, specifierLen)) {
3579 return false;
3580 }
3581
3582 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3583 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003584 return false;
3585 }
3586
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003587 if (!CS.consumesDataArgument()) {
3588 // FIXME: Technically specifying a precision or field width here
3589 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003590 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003591 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003592
Ted Kremenek4a49d982010-02-26 19:18:41 +00003593 // Consume the argument.
3594 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003595 if (argIndex < NumDataArgs) {
3596 // The check to see if the argIndex is valid will come later.
3597 // We set the bit here because we may exit early from this
3598 // function if we encounter some other error.
3599 CoveredArgs.set(argIndex);
3600 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003601
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003602 // FreeBSD kernel extensions.
3603 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3604 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3605 // We need at least two arguments.
3606 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3607 return false;
3608
3609 // Claim the second argument.
3610 CoveredArgs.set(argIndex + 1);
3611
3612 // Type check the first argument (int for %b, pointer for %D)
3613 const Expr *Ex = getDataArg(argIndex);
3614 const analyze_printf::ArgType &AT =
3615 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3616 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3617 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3618 EmitFormatDiagnostic(
3619 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3620 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3621 << false << Ex->getSourceRange(),
3622 Ex->getLocStart(), /*IsStringLocation*/false,
3623 getSpecifierRange(startSpecifier, specifierLen));
3624
3625 // Type check the second argument (char * for both %b and %D)
3626 Ex = getDataArg(argIndex + 1);
3627 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3628 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3629 EmitFormatDiagnostic(
3630 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3631 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3632 << false << Ex->getSourceRange(),
3633 Ex->getLocStart(), /*IsStringLocation*/false,
3634 getSpecifierRange(startSpecifier, specifierLen));
3635
3636 return true;
3637 }
3638
Ted Kremenek4a49d982010-02-26 19:18:41 +00003639 // Check for using an Objective-C specific conversion specifier
3640 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003641 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003642 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3643 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003644 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003645
Tom Careb49ec692010-06-17 19:00:27 +00003646 // Check for invalid use of field width
3647 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003648 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003649 startSpecifier, specifierLen);
3650 }
3651
3652 // Check for invalid use of precision
3653 if (!FS.hasValidPrecision()) {
3654 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3655 startSpecifier, specifierLen);
3656 }
3657
3658 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003659 if (!FS.hasValidThousandsGroupingPrefix())
3660 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003661 if (!FS.hasValidLeadingZeros())
3662 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3663 if (!FS.hasValidPlusPrefix())
3664 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003665 if (!FS.hasValidSpacePrefix())
3666 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003667 if (!FS.hasValidAlternativeForm())
3668 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3669 if (!FS.hasValidLeftJustified())
3670 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3671
3672 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003673 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3674 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3675 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003676 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3677 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3678 startSpecifier, specifierLen);
3679
3680 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003681 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003682 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3683 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003684 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003685 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003686 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003687 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3688 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003689
Jordan Rose92303592012-09-08 04:00:03 +00003690 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3691 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3692
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003693 // The remaining checks depend on the data arguments.
3694 if (HasVAListArg)
3695 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003696
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003697 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003698 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003699
Jordan Rose58bbe422012-07-19 18:10:08 +00003700 const Expr *Arg = getDataArg(argIndex);
3701 if (!Arg)
3702 return true;
3703
3704 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003705}
3706
Jordan Roseaee34382012-09-05 22:56:26 +00003707static bool requiresParensToAddCast(const Expr *E) {
3708 // FIXME: We should have a general way to reason about operator
3709 // precedence and whether parens are actually needed here.
3710 // Take care of a few common cases where they aren't.
3711 const Expr *Inside = E->IgnoreImpCasts();
3712 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3713 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3714
3715 switch (Inside->getStmtClass()) {
3716 case Stmt::ArraySubscriptExprClass:
3717 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003718 case Stmt::CharacterLiteralClass:
3719 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003720 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003721 case Stmt::FloatingLiteralClass:
3722 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003723 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003724 case Stmt::ObjCArrayLiteralClass:
3725 case Stmt::ObjCBoolLiteralExprClass:
3726 case Stmt::ObjCBoxedExprClass:
3727 case Stmt::ObjCDictionaryLiteralClass:
3728 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003729 case Stmt::ObjCIvarRefExprClass:
3730 case Stmt::ObjCMessageExprClass:
3731 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003732 case Stmt::ObjCStringLiteralClass:
3733 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003734 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003735 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003736 case Stmt::UnaryOperatorClass:
3737 return false;
3738 default:
3739 return true;
3740 }
3741}
3742
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003743static std::pair<QualType, StringRef>
3744shouldNotPrintDirectly(const ASTContext &Context,
3745 QualType IntendedTy,
3746 const Expr *E) {
3747 // Use a 'while' to peel off layers of typedefs.
3748 QualType TyTy = IntendedTy;
3749 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3750 StringRef Name = UserTy->getDecl()->getName();
3751 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3752 .Case("NSInteger", Context.LongTy)
3753 .Case("NSUInteger", Context.UnsignedLongTy)
3754 .Case("SInt32", Context.IntTy)
3755 .Case("UInt32", Context.UnsignedIntTy)
3756 .Default(QualType());
3757
3758 if (!CastTy.isNull())
3759 return std::make_pair(CastTy, Name);
3760
3761 TyTy = UserTy->desugar();
3762 }
3763
3764 // Strip parens if necessary.
3765 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3766 return shouldNotPrintDirectly(Context,
3767 PE->getSubExpr()->getType(),
3768 PE->getSubExpr());
3769
3770 // If this is a conditional expression, then its result type is constructed
3771 // via usual arithmetic conversions and thus there might be no necessary
3772 // typedef sugar there. Recurse to operands to check for NSInteger &
3773 // Co. usage condition.
3774 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3775 QualType TrueTy, FalseTy;
3776 StringRef TrueName, FalseName;
3777
3778 std::tie(TrueTy, TrueName) =
3779 shouldNotPrintDirectly(Context,
3780 CO->getTrueExpr()->getType(),
3781 CO->getTrueExpr());
3782 std::tie(FalseTy, FalseName) =
3783 shouldNotPrintDirectly(Context,
3784 CO->getFalseExpr()->getType(),
3785 CO->getFalseExpr());
3786
3787 if (TrueTy == FalseTy)
3788 return std::make_pair(TrueTy, TrueName);
3789 else if (TrueTy.isNull())
3790 return std::make_pair(FalseTy, FalseName);
3791 else if (FalseTy.isNull())
3792 return std::make_pair(TrueTy, TrueName);
3793 }
3794
3795 return std::make_pair(QualType(), StringRef());
3796}
3797
Richard Smith55ce3522012-06-25 20:30:08 +00003798bool
3799CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3800 const char *StartSpecifier,
3801 unsigned SpecifierLen,
3802 const Expr *E) {
3803 using namespace analyze_format_string;
3804 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003805 // Now type check the data expression that matches the
3806 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003807 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3808 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003809 if (!AT.isValid())
3810 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003811
Jordan Rose598ec092012-12-05 18:44:40 +00003812 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003813 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3814 ExprTy = TET->getUnderlyingExpr()->getType();
3815 }
3816
Seth Cantrellb4802962015-03-04 03:12:10 +00003817 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3818
3819 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003820 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003821 }
Jordan Rose98709982012-06-04 22:48:57 +00003822
Jordan Rose22b74712012-09-05 22:56:19 +00003823 // Look through argument promotions for our error message's reported type.
3824 // This includes the integral and floating promotions, but excludes array
3825 // and function pointer decay; seeing that an argument intended to be a
3826 // string has type 'char [6]' is probably more confusing than 'char *'.
3827 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3828 if (ICE->getCastKind() == CK_IntegralCast ||
3829 ICE->getCastKind() == CK_FloatingCast) {
3830 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003831 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003832
3833 // Check if we didn't match because of an implicit cast from a 'char'
3834 // or 'short' to an 'int'. This is done because printf is a varargs
3835 // function.
3836 if (ICE->getType() == S.Context.IntTy ||
3837 ICE->getType() == S.Context.UnsignedIntTy) {
3838 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003839 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003840 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003841 }
Jordan Rose98709982012-06-04 22:48:57 +00003842 }
Jordan Rose598ec092012-12-05 18:44:40 +00003843 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3844 // Special case for 'a', which has type 'int' in C.
3845 // Note, however, that we do /not/ want to treat multibyte constants like
3846 // 'MooV' as characters! This form is deprecated but still exists.
3847 if (ExprTy == S.Context.IntTy)
3848 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3849 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003850 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003851
Jordan Rosebc53ed12014-05-31 04:12:14 +00003852 // Look through enums to their underlying type.
3853 bool IsEnum = false;
3854 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3855 ExprTy = EnumTy->getDecl()->getIntegerType();
3856 IsEnum = true;
3857 }
3858
Jordan Rose0e5badd2012-12-05 18:44:49 +00003859 // %C in an Objective-C context prints a unichar, not a wchar_t.
3860 // If the argument is an integer of some kind, believe the %C and suggest
3861 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003862 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003863 if (ObjCContext &&
3864 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3865 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3866 !ExprTy->isCharType()) {
3867 // 'unichar' is defined as a typedef of unsigned short, but we should
3868 // prefer using the typedef if it is visible.
3869 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003870
3871 // While we are here, check if the value is an IntegerLiteral that happens
3872 // to be within the valid range.
3873 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3874 const llvm::APInt &V = IL->getValue();
3875 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3876 return true;
3877 }
3878
Jordan Rose0e5badd2012-12-05 18:44:49 +00003879 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3880 Sema::LookupOrdinaryName);
3881 if (S.LookupName(Result, S.getCurScope())) {
3882 NamedDecl *ND = Result.getFoundDecl();
3883 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3884 if (TD->getUnderlyingType() == IntendedTy)
3885 IntendedTy = S.Context.getTypedefType(TD);
3886 }
3887 }
3888 }
3889
3890 // Special-case some of Darwin's platform-independence types by suggesting
3891 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003892 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003893 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003894 QualType CastTy;
3895 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3896 if (!CastTy.isNull()) {
3897 IntendedTy = CastTy;
3898 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003899 }
3900 }
3901
Jordan Rose22b74712012-09-05 22:56:19 +00003902 // We may be able to offer a FixItHint if it is a supported type.
3903 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003904 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003905 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003906
Jordan Rose22b74712012-09-05 22:56:19 +00003907 if (success) {
3908 // Get the fix string from the fixed format specifier
3909 SmallString<16> buf;
3910 llvm::raw_svector_ostream os(buf);
3911 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003912
Jordan Roseaee34382012-09-05 22:56:26 +00003913 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3914
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003915 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003916 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3917 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3918 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3919 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003920 // In this case, the specifier is wrong and should be changed to match
3921 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003922 EmitFormatDiagnostic(S.PDiag(diag)
3923 << AT.getRepresentativeTypeName(S.Context)
3924 << IntendedTy << IsEnum << E->getSourceRange(),
3925 E->getLocStart(),
3926 /*IsStringLocation*/ false, SpecRange,
3927 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003928
3929 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003930 // The canonical type for formatting this value is different from the
3931 // actual type of the expression. (This occurs, for example, with Darwin's
3932 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3933 // should be printed as 'long' for 64-bit compatibility.)
3934 // Rather than emitting a normal format/argument mismatch, we want to
3935 // add a cast to the recommended type (and correct the format string
3936 // if necessary).
3937 SmallString<16> CastBuf;
3938 llvm::raw_svector_ostream CastFix(CastBuf);
3939 CastFix << "(";
3940 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3941 CastFix << ")";
3942
3943 SmallVector<FixItHint,4> Hints;
3944 if (!AT.matchesType(S.Context, IntendedTy))
3945 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3946
3947 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3948 // If there's already a cast present, just replace it.
3949 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3950 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3951
3952 } else if (!requiresParensToAddCast(E)) {
3953 // If the expression has high enough precedence,
3954 // just write the C-style cast.
3955 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3956 CastFix.str()));
3957 } else {
3958 // Otherwise, add parens around the expression as well as the cast.
3959 CastFix << "(";
3960 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3961 CastFix.str()));
3962
Alp Tokerb6cc5922014-05-03 03:45:55 +00003963 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003964 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3965 }
3966
Jordan Rose0e5badd2012-12-05 18:44:49 +00003967 if (ShouldNotPrintDirectly) {
3968 // The expression has a type that should not be printed directly.
3969 // We extract the name from the typedef because we don't want to show
3970 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003971 StringRef Name;
3972 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3973 Name = TypedefTy->getDecl()->getName();
3974 else
3975 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003976 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003977 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003978 << E->getSourceRange(),
3979 E->getLocStart(), /*IsStringLocation=*/false,
3980 SpecRange, Hints);
3981 } else {
3982 // In this case, the expression could be printed using a different
3983 // specifier, but we've decided that the specifier is probably correct
3984 // and we should cast instead. Just use the normal warning message.
3985 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003986 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3987 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003988 << E->getSourceRange(),
3989 E->getLocStart(), /*IsStringLocation*/false,
3990 SpecRange, Hints);
3991 }
Jordan Roseaee34382012-09-05 22:56:26 +00003992 }
Jordan Rose22b74712012-09-05 22:56:19 +00003993 } else {
3994 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3995 SpecifierLen);
3996 // Since the warning for passing non-POD types to variadic functions
3997 // was deferred until now, we emit a warning for non-POD
3998 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003999 switch (S.isValidVarArgType(ExprTy)) {
4000 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004001 case Sema::VAK_ValidInCXX11: {
4002 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4003 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4004 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4005 }
Richard Smithd7293d72013-08-05 18:49:43 +00004006
Seth Cantrellb4802962015-03-04 03:12:10 +00004007 EmitFormatDiagnostic(
4008 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4009 << IsEnum << CSR << E->getSourceRange(),
4010 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4011 break;
4012 }
Richard Smithd7293d72013-08-05 18:49:43 +00004013 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004014 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004015 EmitFormatDiagnostic(
4016 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004017 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004018 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004019 << CallType
4020 << AT.getRepresentativeTypeName(S.Context)
4021 << CSR
4022 << E->getSourceRange(),
4023 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004024 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004025 break;
4026
4027 case Sema::VAK_Invalid:
4028 if (ExprTy->isObjCObjectType())
4029 EmitFormatDiagnostic(
4030 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4031 << S.getLangOpts().CPlusPlus11
4032 << ExprTy
4033 << CallType
4034 << AT.getRepresentativeTypeName(S.Context)
4035 << CSR
4036 << E->getSourceRange(),
4037 E->getLocStart(), /*IsStringLocation*/false, CSR);
4038 else
4039 // FIXME: If this is an initializer list, suggest removing the braces
4040 // or inserting a cast to the target type.
4041 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4042 << isa<InitListExpr>(E) << ExprTy << CallType
4043 << AT.getRepresentativeTypeName(S.Context)
4044 << E->getSourceRange();
4045 break;
4046 }
4047
4048 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4049 "format string specifier index out of range");
4050 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004051 }
4052
Ted Kremenekab278de2010-01-28 23:39:18 +00004053 return true;
4054}
4055
Ted Kremenek02087932010-07-16 02:11:22 +00004056//===--- CHECK: Scanf format string checking ------------------------------===//
4057
4058namespace {
4059class CheckScanfHandler : public CheckFormatHandler {
4060public:
4061 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4062 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004063 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004064 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004065 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004066 Sema::VariadicCallType CallType,
4067 llvm::SmallBitVector &CheckedVarArgs)
4068 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4069 numDataArgs, beg, hasVAListArg,
4070 Args, formatIdx, inFunctionCall, CallType,
4071 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004072 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004073
4074 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4075 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004076 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004077
4078 bool HandleInvalidScanfConversionSpecifier(
4079 const analyze_scanf::ScanfSpecifier &FS,
4080 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004081 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004082
Craig Toppere14c0f82014-03-12 04:55:44 +00004083 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004084};
Ted Kremenek019d2242010-01-29 01:50:07 +00004085}
Ted Kremenekab278de2010-01-28 23:39:18 +00004086
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004087void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4088 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004089 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4090 getLocationOfByte(end), /*IsStringLocation*/true,
4091 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004092}
4093
Ted Kremenekce815422010-07-19 21:25:57 +00004094bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4095 const analyze_scanf::ScanfSpecifier &FS,
4096 const char *startSpecifier,
4097 unsigned specifierLen) {
4098
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004099 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004100 FS.getConversionSpecifier();
4101
4102 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4103 getLocationOfByte(CS.getStart()),
4104 startSpecifier, specifierLen,
4105 CS.getStart(), CS.getLength());
4106}
4107
Ted Kremenek02087932010-07-16 02:11:22 +00004108bool CheckScanfHandler::HandleScanfSpecifier(
4109 const analyze_scanf::ScanfSpecifier &FS,
4110 const char *startSpecifier,
4111 unsigned specifierLen) {
4112
4113 using namespace analyze_scanf;
4114 using namespace analyze_format_string;
4115
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004116 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004117
Ted Kremenek6cd69422010-07-19 22:01:06 +00004118 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4119 // be used to decide if we are using positional arguments consistently.
4120 if (FS.consumesDataArgument()) {
4121 if (atFirstArg) {
4122 atFirstArg = false;
4123 usesPositionalArgs = FS.usesPositionalArg();
4124 }
4125 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004126 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4127 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004128 return false;
4129 }
Ted Kremenek02087932010-07-16 02:11:22 +00004130 }
4131
4132 // Check if the field with is non-zero.
4133 const OptionalAmount &Amt = FS.getFieldWidth();
4134 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4135 if (Amt.getConstantAmount() == 0) {
4136 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4137 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004138 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4139 getLocationOfByte(Amt.getStart()),
4140 /*IsStringLocation*/true, R,
4141 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004142 }
4143 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004144
Ted Kremenek02087932010-07-16 02:11:22 +00004145 if (!FS.consumesDataArgument()) {
4146 // FIXME: Technically specifying a precision or field width here
4147 // makes no sense. Worth issuing a warning at some point.
4148 return true;
4149 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004150
Ted Kremenek02087932010-07-16 02:11:22 +00004151 // Consume the argument.
4152 unsigned argIndex = FS.getArgIndex();
4153 if (argIndex < NumDataArgs) {
4154 // The check to see if the argIndex is valid will come later.
4155 // We set the bit here because we may exit early from this
4156 // function if we encounter some other error.
4157 CoveredArgs.set(argIndex);
4158 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004159
Ted Kremenek4407ea42010-07-20 20:04:47 +00004160 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004161 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004162 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4163 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004164 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004165 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004166 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004167 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4168 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004169
Jordan Rose92303592012-09-08 04:00:03 +00004170 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4171 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4172
Ted Kremenek02087932010-07-16 02:11:22 +00004173 // The remaining checks depend on the data arguments.
4174 if (HasVAListArg)
4175 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004176
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004177 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004178 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004179
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004180 // Check that the argument type matches the format specifier.
4181 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004182 if (!Ex)
4183 return true;
4184
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004185 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004186
4187 if (!AT.isValid()) {
4188 return true;
4189 }
4190
Seth Cantrellb4802962015-03-04 03:12:10 +00004191 analyze_format_string::ArgType::MatchKind match =
4192 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004193 if (match == analyze_format_string::ArgType::Match) {
4194 return true;
4195 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004196
Seth Cantrell79340072015-03-04 05:58:08 +00004197 ScanfSpecifier fixedFS = FS;
4198 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4199 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004200
Seth Cantrell79340072015-03-04 05:58:08 +00004201 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4202 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4203 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4204 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004205
Seth Cantrell79340072015-03-04 05:58:08 +00004206 if (success) {
4207 // Get the fix string from the fixed format specifier.
4208 SmallString<128> buf;
4209 llvm::raw_svector_ostream os(buf);
4210 fixedFS.toString(os);
4211
4212 EmitFormatDiagnostic(
4213 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4214 << Ex->getType() << false << Ex->getSourceRange(),
4215 Ex->getLocStart(),
4216 /*IsStringLocation*/ false,
4217 getSpecifierRange(startSpecifier, specifierLen),
4218 FixItHint::CreateReplacement(
4219 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4220 } else {
4221 EmitFormatDiagnostic(S.PDiag(diag)
4222 << AT.getRepresentativeTypeName(S.Context)
4223 << Ex->getType() << false << Ex->getSourceRange(),
4224 Ex->getLocStart(),
4225 /*IsStringLocation*/ false,
4226 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004227 }
4228
Ted Kremenek02087932010-07-16 02:11:22 +00004229 return true;
4230}
4231
4232void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004233 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004234 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004235 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004236 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004237 bool inFunctionCall, VariadicCallType CallType,
4238 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004239
Ted Kremenekab278de2010-01-28 23:39:18 +00004240 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004241 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004242 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004243 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004244 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4245 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004246 return;
4247 }
Ted Kremenek02087932010-07-16 02:11:22 +00004248
Ted Kremenekab278de2010-01-28 23:39:18 +00004249 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004250 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004251 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004252 // Account for cases where the string literal is truncated in a declaration.
4253 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4254 assert(T && "String literal not of constant array type!");
4255 size_t TypeSize = T->getSize().getZExtValue();
4256 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004257 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004258
4259 // Emit a warning if the string literal is truncated and does not contain an
4260 // embedded null character.
4261 if (TypeSize <= StrRef.size() &&
4262 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4263 CheckFormatHandler::EmitFormatDiagnostic(
4264 *this, inFunctionCall, Args[format_idx],
4265 PDiag(diag::warn_printf_format_string_not_null_terminated),
4266 FExpr->getLocStart(),
4267 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4268 return;
4269 }
4270
Ted Kremenekab278de2010-01-28 23:39:18 +00004271 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004272 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004273 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004274 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004275 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4276 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004277 return;
4278 }
Ted Kremenek02087932010-07-16 02:11:22 +00004279
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004280 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004281 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004282 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004283 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004284 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004285 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004286
Hans Wennborg23926bd2011-12-15 10:25:47 +00004287 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004288 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004289 Context.getTargetInfo(),
4290 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004291 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004292 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004293 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004294 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004295 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004296
Hans Wennborg23926bd2011-12-15 10:25:47 +00004297 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004298 getLangOpts(),
4299 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004300 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004301 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004302}
4303
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004304bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4305 // Str - The format string. NOTE: this is NOT null-terminated!
4306 StringRef StrRef = FExpr->getString();
4307 const char *Str = StrRef.data();
4308 // Account for cases where the string literal is truncated in a declaration.
4309 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4310 assert(T && "String literal not of constant array type!");
4311 size_t TypeSize = T->getSize().getZExtValue();
4312 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4313 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4314 getLangOpts(),
4315 Context.getTargetInfo());
4316}
4317
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004318//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4319
4320// Returns the related absolute value function that is larger, of 0 if one
4321// does not exist.
4322static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4323 switch (AbsFunction) {
4324 default:
4325 return 0;
4326
4327 case Builtin::BI__builtin_abs:
4328 return Builtin::BI__builtin_labs;
4329 case Builtin::BI__builtin_labs:
4330 return Builtin::BI__builtin_llabs;
4331 case Builtin::BI__builtin_llabs:
4332 return 0;
4333
4334 case Builtin::BI__builtin_fabsf:
4335 return Builtin::BI__builtin_fabs;
4336 case Builtin::BI__builtin_fabs:
4337 return Builtin::BI__builtin_fabsl;
4338 case Builtin::BI__builtin_fabsl:
4339 return 0;
4340
4341 case Builtin::BI__builtin_cabsf:
4342 return Builtin::BI__builtin_cabs;
4343 case Builtin::BI__builtin_cabs:
4344 return Builtin::BI__builtin_cabsl;
4345 case Builtin::BI__builtin_cabsl:
4346 return 0;
4347
4348 case Builtin::BIabs:
4349 return Builtin::BIlabs;
4350 case Builtin::BIlabs:
4351 return Builtin::BIllabs;
4352 case Builtin::BIllabs:
4353 return 0;
4354
4355 case Builtin::BIfabsf:
4356 return Builtin::BIfabs;
4357 case Builtin::BIfabs:
4358 return Builtin::BIfabsl;
4359 case Builtin::BIfabsl:
4360 return 0;
4361
4362 case Builtin::BIcabsf:
4363 return Builtin::BIcabs;
4364 case Builtin::BIcabs:
4365 return Builtin::BIcabsl;
4366 case Builtin::BIcabsl:
4367 return 0;
4368 }
4369}
4370
4371// Returns the argument type of the absolute value function.
4372static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4373 unsigned AbsType) {
4374 if (AbsType == 0)
4375 return QualType();
4376
4377 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4378 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4379 if (Error != ASTContext::GE_None)
4380 return QualType();
4381
4382 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4383 if (!FT)
4384 return QualType();
4385
4386 if (FT->getNumParams() != 1)
4387 return QualType();
4388
4389 return FT->getParamType(0);
4390}
4391
4392// Returns the best absolute value function, or zero, based on type and
4393// current absolute value function.
4394static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4395 unsigned AbsFunctionKind) {
4396 unsigned BestKind = 0;
4397 uint64_t ArgSize = Context.getTypeSize(ArgType);
4398 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4399 Kind = getLargerAbsoluteValueFunction(Kind)) {
4400 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4401 if (Context.getTypeSize(ParamType) >= ArgSize) {
4402 if (BestKind == 0)
4403 BestKind = Kind;
4404 else if (Context.hasSameType(ParamType, ArgType)) {
4405 BestKind = Kind;
4406 break;
4407 }
4408 }
4409 }
4410 return BestKind;
4411}
4412
4413enum AbsoluteValueKind {
4414 AVK_Integer,
4415 AVK_Floating,
4416 AVK_Complex
4417};
4418
4419static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4420 if (T->isIntegralOrEnumerationType())
4421 return AVK_Integer;
4422 if (T->isRealFloatingType())
4423 return AVK_Floating;
4424 if (T->isAnyComplexType())
4425 return AVK_Complex;
4426
4427 llvm_unreachable("Type not integer, floating, or complex");
4428}
4429
4430// Changes the absolute value function to a different type. Preserves whether
4431// the function is a builtin.
4432static unsigned changeAbsFunction(unsigned AbsKind,
4433 AbsoluteValueKind ValueKind) {
4434 switch (ValueKind) {
4435 case AVK_Integer:
4436 switch (AbsKind) {
4437 default:
4438 return 0;
4439 case Builtin::BI__builtin_fabsf:
4440 case Builtin::BI__builtin_fabs:
4441 case Builtin::BI__builtin_fabsl:
4442 case Builtin::BI__builtin_cabsf:
4443 case Builtin::BI__builtin_cabs:
4444 case Builtin::BI__builtin_cabsl:
4445 return Builtin::BI__builtin_abs;
4446 case Builtin::BIfabsf:
4447 case Builtin::BIfabs:
4448 case Builtin::BIfabsl:
4449 case Builtin::BIcabsf:
4450 case Builtin::BIcabs:
4451 case Builtin::BIcabsl:
4452 return Builtin::BIabs;
4453 }
4454 case AVK_Floating:
4455 switch (AbsKind) {
4456 default:
4457 return 0;
4458 case Builtin::BI__builtin_abs:
4459 case Builtin::BI__builtin_labs:
4460 case Builtin::BI__builtin_llabs:
4461 case Builtin::BI__builtin_cabsf:
4462 case Builtin::BI__builtin_cabs:
4463 case Builtin::BI__builtin_cabsl:
4464 return Builtin::BI__builtin_fabsf;
4465 case Builtin::BIabs:
4466 case Builtin::BIlabs:
4467 case Builtin::BIllabs:
4468 case Builtin::BIcabsf:
4469 case Builtin::BIcabs:
4470 case Builtin::BIcabsl:
4471 return Builtin::BIfabsf;
4472 }
4473 case AVK_Complex:
4474 switch (AbsKind) {
4475 default:
4476 return 0;
4477 case Builtin::BI__builtin_abs:
4478 case Builtin::BI__builtin_labs:
4479 case Builtin::BI__builtin_llabs:
4480 case Builtin::BI__builtin_fabsf:
4481 case Builtin::BI__builtin_fabs:
4482 case Builtin::BI__builtin_fabsl:
4483 return Builtin::BI__builtin_cabsf;
4484 case Builtin::BIabs:
4485 case Builtin::BIlabs:
4486 case Builtin::BIllabs:
4487 case Builtin::BIfabsf:
4488 case Builtin::BIfabs:
4489 case Builtin::BIfabsl:
4490 return Builtin::BIcabsf;
4491 }
4492 }
4493 llvm_unreachable("Unable to convert function");
4494}
4495
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004496static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004497 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4498 if (!FnInfo)
4499 return 0;
4500
4501 switch (FDecl->getBuiltinID()) {
4502 default:
4503 return 0;
4504 case Builtin::BI__builtin_abs:
4505 case Builtin::BI__builtin_fabs:
4506 case Builtin::BI__builtin_fabsf:
4507 case Builtin::BI__builtin_fabsl:
4508 case Builtin::BI__builtin_labs:
4509 case Builtin::BI__builtin_llabs:
4510 case Builtin::BI__builtin_cabs:
4511 case Builtin::BI__builtin_cabsf:
4512 case Builtin::BI__builtin_cabsl:
4513 case Builtin::BIabs:
4514 case Builtin::BIlabs:
4515 case Builtin::BIllabs:
4516 case Builtin::BIfabs:
4517 case Builtin::BIfabsf:
4518 case Builtin::BIfabsl:
4519 case Builtin::BIcabs:
4520 case Builtin::BIcabsf:
4521 case Builtin::BIcabsl:
4522 return FDecl->getBuiltinID();
4523 }
4524 llvm_unreachable("Unknown Builtin type");
4525}
4526
4527// If the replacement is valid, emit a note with replacement function.
4528// Additionally, suggest including the proper header if not already included.
4529static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004530 unsigned AbsKind, QualType ArgType) {
4531 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 const char *HeaderName = nullptr;
4533 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004534 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4535 FunctionName = "std::abs";
4536 if (ArgType->isIntegralOrEnumerationType()) {
4537 HeaderName = "cstdlib";
4538 } else if (ArgType->isRealFloatingType()) {
4539 HeaderName = "cmath";
4540 } else {
4541 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004542 }
Richard Trieubeffb832014-04-15 23:47:53 +00004543
4544 // Lookup all std::abs
4545 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004546 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004547 R.suppressDiagnostics();
4548 S.LookupQualifiedName(R, Std);
4549
4550 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004551 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004552 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4553 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4554 } else {
4555 FDecl = dyn_cast<FunctionDecl>(I);
4556 }
4557 if (!FDecl)
4558 continue;
4559
4560 // Found std::abs(), check that they are the right ones.
4561 if (FDecl->getNumParams() != 1)
4562 continue;
4563
4564 // Check that the parameter type can handle the argument.
4565 QualType ParamType = FDecl->getParamDecl(0)->getType();
4566 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4567 S.Context.getTypeSize(ArgType) <=
4568 S.Context.getTypeSize(ParamType)) {
4569 // Found a function, don't need the header hint.
4570 EmitHeaderHint = false;
4571 break;
4572 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004573 }
Richard Trieubeffb832014-04-15 23:47:53 +00004574 }
4575 } else {
4576 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4577 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4578
4579 if (HeaderName) {
4580 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4581 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4582 R.suppressDiagnostics();
4583 S.LookupName(R, S.getCurScope());
4584
4585 if (R.isSingleResult()) {
4586 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4587 if (FD && FD->getBuiltinID() == AbsKind) {
4588 EmitHeaderHint = false;
4589 } else {
4590 return;
4591 }
4592 } else if (!R.empty()) {
4593 return;
4594 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004595 }
4596 }
4597
4598 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004599 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004600
Richard Trieubeffb832014-04-15 23:47:53 +00004601 if (!HeaderName)
4602 return;
4603
4604 if (!EmitHeaderHint)
4605 return;
4606
Alp Toker5d96e0a2014-07-11 20:53:51 +00004607 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4608 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004609}
4610
4611static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4612 if (!FDecl)
4613 return false;
4614
4615 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4616 return false;
4617
4618 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4619
4620 while (ND && ND->isInlineNamespace()) {
4621 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004622 }
Richard Trieubeffb832014-04-15 23:47:53 +00004623
4624 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4625 return false;
4626
4627 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4628 return false;
4629
4630 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004631}
4632
4633// Warn when using the wrong abs() function.
4634void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4635 const FunctionDecl *FDecl,
4636 IdentifierInfo *FnInfo) {
4637 if (Call->getNumArgs() != 1)
4638 return;
4639
4640 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004641 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4642 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004643 return;
4644
4645 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4646 QualType ParamType = Call->getArg(0)->getType();
4647
Alp Toker5d96e0a2014-07-11 20:53:51 +00004648 // Unsigned types cannot be negative. Suggest removing the absolute value
4649 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004650 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004651 const char *FunctionName =
4652 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004653 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4654 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004655 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004656 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4657 return;
4658 }
4659
Richard Trieubeffb832014-04-15 23:47:53 +00004660 // std::abs has overloads which prevent most of the absolute value problems
4661 // from occurring.
4662 if (IsStdAbs)
4663 return;
4664
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004665 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4666 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4667
4668 // The argument and parameter are the same kind. Check if they are the right
4669 // size.
4670 if (ArgValueKind == ParamValueKind) {
4671 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4672 return;
4673
4674 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4675 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4676 << FDecl << ArgType << ParamType;
4677
4678 if (NewAbsKind == 0)
4679 return;
4680
4681 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004682 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004683 return;
4684 }
4685
4686 // ArgValueKind != ParamValueKind
4687 // The wrong type of absolute value function was used. Attempt to find the
4688 // proper one.
4689 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4690 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4691 if (NewAbsKind == 0)
4692 return;
4693
4694 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4695 << FDecl << ParamValueKind << ArgValueKind;
4696
4697 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004698 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004699 return;
4700}
4701
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004702//===--- CHECK: Standard memory functions ---------------------------------===//
4703
Nico Weber0e6daef2013-12-26 23:38:39 +00004704/// \brief Takes the expression passed to the size_t parameter of functions
4705/// such as memcmp, strncat, etc and warns if it's a comparison.
4706///
4707/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4708static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4709 IdentifierInfo *FnName,
4710 SourceLocation FnLoc,
4711 SourceLocation RParenLoc) {
4712 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4713 if (!Size)
4714 return false;
4715
4716 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4717 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4718 return false;
4719
Nico Weber0e6daef2013-12-26 23:38:39 +00004720 SourceRange SizeRange = Size->getSourceRange();
4721 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4722 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004723 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004724 << FnName << FixItHint::CreateInsertion(
4725 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004726 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004727 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004728 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004729 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4730 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004731
4732 return true;
4733}
4734
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004735/// \brief Determine whether the given type is or contains a dynamic class type
4736/// (e.g., whether it has a vtable).
4737static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4738 bool &IsContained) {
4739 // Look through array types while ignoring qualifiers.
4740 const Type *Ty = T->getBaseElementTypeUnsafe();
4741 IsContained = false;
4742
4743 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4744 RD = RD ? RD->getDefinition() : nullptr;
4745 if (!RD)
4746 return nullptr;
4747
4748 if (RD->isDynamicClass())
4749 return RD;
4750
4751 // Check all the fields. If any bases were dynamic, the class is dynamic.
4752 // It's impossible for a class to transitively contain itself by value, so
4753 // infinite recursion is impossible.
4754 for (auto *FD : RD->fields()) {
4755 bool SubContained;
4756 if (const CXXRecordDecl *ContainedRD =
4757 getContainedDynamicClass(FD->getType(), SubContained)) {
4758 IsContained = true;
4759 return ContainedRD;
4760 }
4761 }
4762
4763 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004764}
4765
Chandler Carruth889ed862011-06-21 23:04:20 +00004766/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004767/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00004768static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004769 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004770 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4771 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4772 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004773
Craig Topperc3ec1492014-05-26 06:22:03 +00004774 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004775}
4776
Chandler Carruth889ed862011-06-21 23:04:20 +00004777/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00004778static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004779 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4780 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4781 if (SizeOf->getKind() == clang::UETT_SizeOf)
4782 return SizeOf->getTypeOfArgument();
4783
4784 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004785}
4786
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004787/// \brief Check for dangerous or invalid arguments to memset().
4788///
Chandler Carruthac687262011-06-03 06:23:57 +00004789/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004790/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4791/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004792///
4793/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004794void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004795 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004796 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004797 assert(BId != 0);
4798
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004799 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004800 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004801 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004802 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004803 return;
4804
Anna Zaks22122702012-01-17 00:37:07 +00004805 unsigned LastArg = (BId == Builtin::BImemset ||
4806 BId == Builtin::BIstrndup ? 1 : 2);
4807 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004808 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004809
Nico Weber0e6daef2013-12-26 23:38:39 +00004810 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4811 Call->getLocStart(), Call->getRParenLoc()))
4812 return;
4813
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004814 // We have special checking when the length is a sizeof expression.
4815 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4816 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4817 llvm::FoldingSetNodeID SizeOfArgID;
4818
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004819 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4820 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004821 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004822
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004823 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00004824 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004825 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00004826 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004827
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004828 // Never warn about void type pointers. This can be used to suppress
4829 // false positives.
4830 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004831 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004832
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004833 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4834 // actually comparing the expressions for equality. Because computing the
4835 // expression IDs can be expensive, we only do this if the diagnostic is
4836 // enabled.
4837 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004838 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4839 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004840 // We only compute IDs for expressions if the warning is enabled, and
4841 // cache the sizeof arg's ID.
4842 if (SizeOfArgID == llvm::FoldingSetNodeID())
4843 SizeOfArg->Profile(SizeOfArgID, Context, true);
4844 llvm::FoldingSetNodeID DestID;
4845 Dest->Profile(DestID, Context, true);
4846 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004847 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4848 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004849 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004850 StringRef ReadableName = FnName->getName();
4851
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004852 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004853 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004854 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004855 if (!PointeeTy->isIncompleteType() &&
4856 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004857 ActionIdx = 2; // If the pointee's size is sizeof(char),
4858 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004859
4860 // If the function is defined as a builtin macro, do not show macro
4861 // expansion.
4862 SourceLocation SL = SizeOfArg->getExprLoc();
4863 SourceRange DSR = Dest->getSourceRange();
4864 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004865 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004866
4867 if (SM.isMacroArgExpansion(SL)) {
4868 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4869 SL = SM.getSpellingLoc(SL);
4870 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4871 SM.getSpellingLoc(DSR.getEnd()));
4872 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4873 SM.getSpellingLoc(SSR.getEnd()));
4874 }
4875
Anna Zaksd08d9152012-05-30 23:14:52 +00004876 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004877 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004878 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004879 << PointeeTy
4880 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004881 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004882 << SSR);
4883 DiagRuntimeBehavior(SL, SizeOfArg,
4884 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4885 << ActionIdx
4886 << SSR);
4887
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004888 break;
4889 }
4890 }
4891
4892 // Also check for cases where the sizeof argument is the exact same
4893 // type as the memory argument, and where it points to a user-defined
4894 // record type.
4895 if (SizeOfArgTy != QualType()) {
4896 if (PointeeTy->isRecordType() &&
4897 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4898 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4899 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4900 << FnName << SizeOfArgTy << ArgIdx
4901 << PointeeTy << Dest->getSourceRange()
4902 << LenExpr->getSourceRange());
4903 break;
4904 }
Nico Weberc5e73862011-06-14 16:14:58 +00004905 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00004906 } else if (DestTy->isArrayType()) {
4907 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00004908 }
Nico Weberc5e73862011-06-14 16:14:58 +00004909
Nico Weberc44b35e2015-03-21 17:37:46 +00004910 if (PointeeTy == QualType())
4911 continue;
Anna Zaks22122702012-01-17 00:37:07 +00004912
Nico Weberc44b35e2015-03-21 17:37:46 +00004913 // Always complain about dynamic classes.
4914 bool IsContained;
4915 if (const CXXRecordDecl *ContainedRD =
4916 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00004917
Nico Weberc44b35e2015-03-21 17:37:46 +00004918 unsigned OperationType = 0;
4919 // "overwritten" if we're warning about the destination for any call
4920 // but memcmp; otherwise a verb appropriate to the call.
4921 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4922 if (BId == Builtin::BImemcpy)
4923 OperationType = 1;
4924 else if(BId == Builtin::BImemmove)
4925 OperationType = 2;
4926 else if (BId == Builtin::BImemcmp)
4927 OperationType = 3;
4928 }
4929
John McCall31168b02011-06-15 23:02:42 +00004930 DiagRuntimeBehavior(
4931 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00004932 PDiag(diag::warn_dyn_class_memaccess)
4933 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4934 << FnName << IsContained << ContainedRD << OperationType
4935 << Call->getCallee()->getSourceRange());
4936 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4937 BId != Builtin::BImemset)
4938 DiagRuntimeBehavior(
4939 Dest->getExprLoc(), Dest,
4940 PDiag(diag::warn_arc_object_memaccess)
4941 << ArgIdx << FnName << PointeeTy
4942 << Call->getCallee()->getSourceRange());
4943 else
4944 continue;
4945
4946 DiagRuntimeBehavior(
4947 Dest->getExprLoc(), Dest,
4948 PDiag(diag::note_bad_memaccess_silence)
4949 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4950 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004951 }
Nico Weberc44b35e2015-03-21 17:37:46 +00004952
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004953}
4954
Ted Kremenek6865f772011-08-18 20:55:45 +00004955// A little helper routine: ignore addition and subtraction of integer literals.
4956// This intentionally does not ignore all integer constant expressions because
4957// we don't want to remove sizeof().
4958static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4959 Ex = Ex->IgnoreParenCasts();
4960
4961 for (;;) {
4962 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4963 if (!BO || !BO->isAdditiveOp())
4964 break;
4965
4966 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4967 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4968
4969 if (isa<IntegerLiteral>(RHS))
4970 Ex = LHS;
4971 else if (isa<IntegerLiteral>(LHS))
4972 Ex = RHS;
4973 else
4974 break;
4975 }
4976
4977 return Ex;
4978}
4979
Anna Zaks13b08572012-08-08 21:42:23 +00004980static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4981 ASTContext &Context) {
4982 // Only handle constant-sized or VLAs, but not flexible members.
4983 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4984 // Only issue the FIXIT for arrays of size > 1.
4985 if (CAT->getSize().getSExtValue() <= 1)
4986 return false;
4987 } else if (!Ty->isVariableArrayType()) {
4988 return false;
4989 }
4990 return true;
4991}
4992
Ted Kremenek6865f772011-08-18 20:55:45 +00004993// Warn if the user has made the 'size' argument to strlcpy or strlcat
4994// be the size of the source, instead of the destination.
4995void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4996 IdentifierInfo *FnName) {
4997
4998 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004999 unsigned NumArgs = Call->getNumArgs();
5000 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005001 return;
5002
5003 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5004 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005005 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005006
5007 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5008 Call->getLocStart(), Call->getRParenLoc()))
5009 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005010
5011 // Look for 'strlcpy(dst, x, sizeof(x))'
5012 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5013 CompareWithSrc = Ex;
5014 else {
5015 // Look for 'strlcpy(dst, x, strlen(x))'
5016 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005017 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5018 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005019 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5020 }
5021 }
5022
5023 if (!CompareWithSrc)
5024 return;
5025
5026 // Determine if the argument to sizeof/strlen is equal to the source
5027 // argument. In principle there's all kinds of things you could do
5028 // here, for instance creating an == expression and evaluating it with
5029 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5030 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5031 if (!SrcArgDRE)
5032 return;
5033
5034 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5035 if (!CompareWithSrcDRE ||
5036 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5037 return;
5038
5039 const Expr *OriginalSizeArg = Call->getArg(2);
5040 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5041 << OriginalSizeArg->getSourceRange() << FnName;
5042
5043 // Output a FIXIT hint if the destination is an array (rather than a
5044 // pointer to an array). This could be enhanced to handle some
5045 // pointers if we know the actual size, like if DstArg is 'array+2'
5046 // we could say 'sizeof(array)-2'.
5047 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005048 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005049 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005050
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005051 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005052 llvm::raw_svector_ostream OS(sizeString);
5053 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005054 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005055 OS << ")";
5056
5057 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5058 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5059 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005060}
5061
Anna Zaks314cd092012-02-01 19:08:57 +00005062/// Check if two expressions refer to the same declaration.
5063static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5064 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5065 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5066 return D1->getDecl() == D2->getDecl();
5067 return false;
5068}
5069
5070static const Expr *getStrlenExprArg(const Expr *E) {
5071 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5072 const FunctionDecl *FD = CE->getDirectCallee();
5073 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005074 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005075 return CE->getArg(0)->IgnoreParenCasts();
5076 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005077 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005078}
5079
5080// Warn on anti-patterns as the 'size' argument to strncat.
5081// The correct size argument should look like following:
5082// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5083void Sema::CheckStrncatArguments(const CallExpr *CE,
5084 IdentifierInfo *FnName) {
5085 // Don't crash if the user has the wrong number of arguments.
5086 if (CE->getNumArgs() < 3)
5087 return;
5088 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5089 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5090 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5091
Nico Weber0e6daef2013-12-26 23:38:39 +00005092 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5093 CE->getRParenLoc()))
5094 return;
5095
Anna Zaks314cd092012-02-01 19:08:57 +00005096 // Identify common expressions, which are wrongly used as the size argument
5097 // to strncat and may lead to buffer overflows.
5098 unsigned PatternType = 0;
5099 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5100 // - sizeof(dst)
5101 if (referToTheSameDecl(SizeOfArg, DstArg))
5102 PatternType = 1;
5103 // - sizeof(src)
5104 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5105 PatternType = 2;
5106 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5107 if (BE->getOpcode() == BO_Sub) {
5108 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5109 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5110 // - sizeof(dst) - strlen(dst)
5111 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5112 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5113 PatternType = 1;
5114 // - sizeof(src) - (anything)
5115 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5116 PatternType = 2;
5117 }
5118 }
5119
5120 if (PatternType == 0)
5121 return;
5122
Anna Zaks5069aa32012-02-03 01:27:37 +00005123 // Generate the diagnostic.
5124 SourceLocation SL = LenArg->getLocStart();
5125 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005126 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005127
5128 // If the function is defined as a builtin macro, do not show macro expansion.
5129 if (SM.isMacroArgExpansion(SL)) {
5130 SL = SM.getSpellingLoc(SL);
5131 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5132 SM.getSpellingLoc(SR.getEnd()));
5133 }
5134
Anna Zaks13b08572012-08-08 21:42:23 +00005135 // Check if the destination is an array (rather than a pointer to an array).
5136 QualType DstTy = DstArg->getType();
5137 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5138 Context);
5139 if (!isKnownSizeArray) {
5140 if (PatternType == 1)
5141 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5142 else
5143 Diag(SL, diag::warn_strncat_src_size) << SR;
5144 return;
5145 }
5146
Anna Zaks314cd092012-02-01 19:08:57 +00005147 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005148 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005149 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005150 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005151
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005152 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005153 llvm::raw_svector_ostream OS(sizeString);
5154 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005156 OS << ") - ";
5157 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005158 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005159 OS << ") - 1";
5160
Anna Zaks5069aa32012-02-03 01:27:37 +00005161 Diag(SL, diag::note_strncat_wrong_size)
5162 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005163}
5164
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005165//===--- CHECK: Return Address of Stack Variable --------------------------===//
5166
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005167static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5168 Decl *ParentDecl);
5169static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5170 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005171
5172/// CheckReturnStackAddr - Check if a return statement returns the address
5173/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005174static void
5175CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5176 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005177
Craig Topperc3ec1492014-05-26 06:22:03 +00005178 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005179 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005180
5181 // Perform checking for returned stack addresses, local blocks,
5182 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005183 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005184 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005185 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005186 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005187 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005188 }
5189
Craig Topperc3ec1492014-05-26 06:22:03 +00005190 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005191 return; // Nothing suspicious was found.
5192
5193 SourceLocation diagLoc;
5194 SourceRange diagRange;
5195 if (refVars.empty()) {
5196 diagLoc = stackE->getLocStart();
5197 diagRange = stackE->getSourceRange();
5198 } else {
5199 // We followed through a reference variable. 'stackE' contains the
5200 // problematic expression but we will warn at the return statement pointing
5201 // at the reference variable. We will later display the "trail" of
5202 // reference variables using notes.
5203 diagLoc = refVars[0]->getLocStart();
5204 diagRange = refVars[0]->getSourceRange();
5205 }
5206
5207 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005208 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005209 : diag::warn_ret_stack_addr)
5210 << DR->getDecl()->getDeclName() << diagRange;
5211 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005212 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005213 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005214 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005215 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005216 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5217 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005218 << diagRange;
5219 }
5220
5221 // Display the "trail" of reference variables that we followed until we
5222 // found the problematic expression using notes.
5223 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5224 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5225 // If this var binds to another reference var, show the range of the next
5226 // var, otherwise the var binds to the problematic expression, in which case
5227 // show the range of the expression.
5228 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5229 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005230 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5231 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005232 }
5233}
5234
5235/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5236/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005237/// to a location on the stack, a local block, an address of a label, or a
5238/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005239/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005240/// encounter a subexpression that (1) clearly does not lead to one of the
5241/// above problematic expressions (2) is something we cannot determine leads to
5242/// a problematic expression based on such local checking.
5243///
5244/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5245/// the expression that they point to. Such variables are added to the
5246/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005247///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005248/// EvalAddr processes expressions that are pointers that are used as
5249/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005250/// At the base case of the recursion is a check for the above problematic
5251/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005252///
5253/// This implementation handles:
5254///
5255/// * pointer-to-pointer casts
5256/// * implicit conversions from array references to pointers
5257/// * taking the address of fields
5258/// * arbitrary interplay between "&" and "*" operators
5259/// * pointer arithmetic from an address of a stack variable
5260/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005261static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5262 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005263 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005264 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005265
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005266 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005267 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005268 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005269 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005270 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005271
Peter Collingbourne91147592011-04-15 00:35:48 +00005272 E = E->IgnoreParens();
5273
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005274 // Our "symbolic interpreter" is just a dispatch off the currently
5275 // viewed AST node. We then recursively traverse the AST by calling
5276 // EvalAddr and EvalVal appropriately.
5277 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005278 case Stmt::DeclRefExprClass: {
5279 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5280
Richard Smith40f08eb2014-01-30 22:05:38 +00005281 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005282 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005283 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005284
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005285 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5286 // If this is a reference variable, follow through to the expression that
5287 // it points to.
5288 if (V->hasLocalStorage() &&
5289 V->getType()->isReferenceType() && V->hasInit()) {
5290 // Add the reference variable to the "trail".
5291 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005292 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005293 }
5294
Craig Topperc3ec1492014-05-26 06:22:03 +00005295 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005296 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005297
Chris Lattner934edb22007-12-28 05:31:15 +00005298 case Stmt::UnaryOperatorClass: {
5299 // The only unary operator that make sense to handle here
5300 // is AddrOf. All others don't make sense as pointers.
5301 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005302
John McCalle3027922010-08-25 11:45:40 +00005303 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005304 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005305 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005306 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005307 }
Mike Stump11289f42009-09-09 15:08:12 +00005308
Chris Lattner934edb22007-12-28 05:31:15 +00005309 case Stmt::BinaryOperatorClass: {
5310 // Handle pointer arithmetic. All other binary operators are not valid
5311 // in this context.
5312 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005313 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005314
John McCalle3027922010-08-25 11:45:40 +00005315 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005316 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005317
Chris Lattner934edb22007-12-28 05:31:15 +00005318 Expr *Base = B->getLHS();
5319
5320 // Determine which argument is the real pointer base. It could be
5321 // the RHS argument instead of the LHS.
5322 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005323
Chris Lattner934edb22007-12-28 05:31:15 +00005324 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005325 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005326 }
Steve Naroff2752a172008-09-10 19:17:48 +00005327
Chris Lattner934edb22007-12-28 05:31:15 +00005328 // For conditional operators we need to see if either the LHS or RHS are
5329 // valid DeclRefExpr*s. If one of them is valid, we return it.
5330 case Stmt::ConditionalOperatorClass: {
5331 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005332
Chris Lattner934edb22007-12-28 05:31:15 +00005333 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005334 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5335 if (Expr *LHSExpr = C->getLHS()) {
5336 // In C++, we can have a throw-expression, which has 'void' type.
5337 if (!LHSExpr->getType()->isVoidType())
5338 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005339 return LHS;
5340 }
Chris Lattner934edb22007-12-28 05:31:15 +00005341
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005342 // In C++, we can have a throw-expression, which has 'void' type.
5343 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005344 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005345
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005346 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005347 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005348
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005349 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005350 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005351 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005352 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005353
5354 case Stmt::AddrLabelExprClass:
5355 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005356
John McCall28fc7092011-11-10 05:35:25 +00005357 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005358 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5359 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005360
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005361 // For casts, we need to handle conversions from arrays to
5362 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005363 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005364 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005365 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005366 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005367 case Stmt::CXXStaticCastExprClass:
5368 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005369 case Stmt::CXXConstCastExprClass:
5370 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005371 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5372 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005373 case CK_LValueToRValue:
5374 case CK_NoOp:
5375 case CK_BaseToDerived:
5376 case CK_DerivedToBase:
5377 case CK_UncheckedDerivedToBase:
5378 case CK_Dynamic:
5379 case CK_CPointerToObjCPointerCast:
5380 case CK_BlockPointerToObjCPointerCast:
5381 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005382 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005383
5384 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005385 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005386
Richard Trieudadefde2014-07-02 04:39:38 +00005387 case CK_BitCast:
5388 if (SubExpr->getType()->isAnyPointerType() ||
5389 SubExpr->getType()->isBlockPointerType() ||
5390 SubExpr->getType()->isObjCQualifiedIdType())
5391 return EvalAddr(SubExpr, refVars, ParentDecl);
5392 else
5393 return nullptr;
5394
Eli Friedman8195ad72012-02-23 23:04:32 +00005395 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005396 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005397 }
Chris Lattner934edb22007-12-28 05:31:15 +00005398 }
Mike Stump11289f42009-09-09 15:08:12 +00005399
Douglas Gregorfe314812011-06-21 17:03:29 +00005400 case Stmt::MaterializeTemporaryExprClass:
5401 if (Expr *Result = EvalAddr(
5402 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005403 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005404 return Result;
5405
5406 return E;
5407
Chris Lattner934edb22007-12-28 05:31:15 +00005408 // Everything else: we simply don't reason about them.
5409 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005410 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005411 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005412}
Mike Stump11289f42009-09-09 15:08:12 +00005413
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005414
5415/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5416/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005417static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5418 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005419do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005420 // We should only be called for evaluating non-pointer expressions, or
5421 // expressions with a pointer type that are not used as references but instead
5422 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005423
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005424 // Our "symbolic interpreter" is just a dispatch off the currently
5425 // viewed AST node. We then recursively traverse the AST by calling
5426 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005427
5428 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005429 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005430 case Stmt::ImplicitCastExprClass: {
5431 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005432 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005433 E = IE->getSubExpr();
5434 continue;
5435 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005436 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005437 }
5438
John McCall28fc7092011-11-10 05:35:25 +00005439 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005440 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005441
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005442 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005443 // When we hit a DeclRefExpr we are looking at code that refers to a
5444 // variable's name. If it's not a reference variable we check if it has
5445 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005446 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005447
Richard Smith40f08eb2014-01-30 22:05:38 +00005448 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005449 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005450 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005451
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005452 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5453 // Check if it refers to itself, e.g. "int& i = i;".
5454 if (V == ParentDecl)
5455 return DR;
5456
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005457 if (V->hasLocalStorage()) {
5458 if (!V->getType()->isReferenceType())
5459 return DR;
5460
5461 // Reference variable, follow through to the expression that
5462 // it points to.
5463 if (V->hasInit()) {
5464 // Add the reference variable to the "trail".
5465 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005466 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005467 }
5468 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005469 }
Mike Stump11289f42009-09-09 15:08:12 +00005470
Craig Topperc3ec1492014-05-26 06:22:03 +00005471 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005472 }
Mike Stump11289f42009-09-09 15:08:12 +00005473
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005474 case Stmt::UnaryOperatorClass: {
5475 // The only unary operator that make sense to handle here
5476 // is Deref. All others don't resolve to a "name." This includes
5477 // handling all sorts of rvalues passed to a unary operator.
5478 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005479
John McCalle3027922010-08-25 11:45:40 +00005480 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005481 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005482
Craig Topperc3ec1492014-05-26 06:22:03 +00005483 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005484 }
Mike Stump11289f42009-09-09 15:08:12 +00005485
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005486 case Stmt::ArraySubscriptExprClass: {
5487 // Array subscripts are potential references to data on the stack. We
5488 // retrieve the DeclRefExpr* for the array variable if it indeed
5489 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005490 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005491 }
Mike Stump11289f42009-09-09 15:08:12 +00005492
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005493 case Stmt::ConditionalOperatorClass: {
5494 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005495 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005496 ConditionalOperator *C = cast<ConditionalOperator>(E);
5497
Anders Carlsson801c5c72007-11-30 19:04:31 +00005498 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005499 if (Expr *LHSExpr = C->getLHS()) {
5500 // In C++, we can have a throw-expression, which has 'void' type.
5501 if (!LHSExpr->getType()->isVoidType())
5502 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5503 return LHS;
5504 }
5505
5506 // In C++, we can have a throw-expression, which has 'void' type.
5507 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005508 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005509
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005510 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005511 }
Mike Stump11289f42009-09-09 15:08:12 +00005512
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005513 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005514 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005515 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005516
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005517 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005518 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005519 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005520
5521 // Check whether the member type is itself a reference, in which case
5522 // we're not going to refer to the member, but to what the member refers to.
5523 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005524 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005525
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005526 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005527 }
Mike Stump11289f42009-09-09 15:08:12 +00005528
Douglas Gregorfe314812011-06-21 17:03:29 +00005529 case Stmt::MaterializeTemporaryExprClass:
5530 if (Expr *Result = EvalVal(
5531 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005532 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005533 return Result;
5534
5535 return E;
5536
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005537 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005538 // Check that we don't return or take the address of a reference to a
5539 // temporary. This is only useful in C++.
5540 if (!E->isTypeDependent() && E->isRValue())
5541 return E;
5542
5543 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005544 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005545 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005546} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005547}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005548
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005549void
5550Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5551 SourceLocation ReturnLoc,
5552 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005553 const AttrVec *Attrs,
5554 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005555 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5556
5557 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005558 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5559 CheckNonNullExpr(*this, RetValExp))
5560 Diag(ReturnLoc, diag::warn_null_ret)
5561 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005562
5563 // C++11 [basic.stc.dynamic.allocation]p4:
5564 // If an allocation function declared with a non-throwing
5565 // exception-specification fails to allocate storage, it shall return
5566 // a null pointer. Any other allocation function that fails to allocate
5567 // storage shall indicate failure only by throwing an exception [...]
5568 if (FD) {
5569 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5570 if (Op == OO_New || Op == OO_Array_New) {
5571 const FunctionProtoType *Proto
5572 = FD->getType()->castAs<FunctionProtoType>();
5573 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5574 CheckNonNullExpr(*this, RetValExp))
5575 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5576 << FD << getLangOpts().CPlusPlus11;
5577 }
5578 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005579}
5580
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005581//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5582
5583/// Check for comparisons of floating point operands using != and ==.
5584/// Issue a warning if these are no self-comparisons, as they are not likely
5585/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005586void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005587 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5588 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005589
5590 // Special case: check for x == x (which is OK).
5591 // Do not emit warnings for such cases.
5592 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5593 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5594 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005595 return;
Mike Stump11289f42009-09-09 15:08:12 +00005596
5597
Ted Kremenekeda40e22007-11-29 00:59:04 +00005598 // Special case: check for comparisons against literals that can be exactly
5599 // represented by APFloat. In such cases, do not emit a warning. This
5600 // is a heuristic: often comparison against such literals are used to
5601 // detect if a value in a variable has not changed. This clearly can
5602 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005603 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5604 if (FLL->isExact())
5605 return;
5606 } else
5607 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5608 if (FLR->isExact())
5609 return;
Mike Stump11289f42009-09-09 15:08:12 +00005610
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005611 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005612 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005613 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005614 return;
Mike Stump11289f42009-09-09 15:08:12 +00005615
David Blaikie1f4ff152012-07-16 20:47:22 +00005616 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005617 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005618 return;
Mike Stump11289f42009-09-09 15:08:12 +00005619
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005620 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005621 Diag(Loc, diag::warn_floatingpoint_eq)
5622 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005623}
John McCallca01b222010-01-04 23:21:16 +00005624
John McCall70aa5392010-01-06 05:24:50 +00005625//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5626//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005627
John McCall70aa5392010-01-06 05:24:50 +00005628namespace {
John McCallca01b222010-01-04 23:21:16 +00005629
John McCall70aa5392010-01-06 05:24:50 +00005630/// Structure recording the 'active' range of an integer-valued
5631/// expression.
5632struct IntRange {
5633 /// The number of bits active in the int.
5634 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005635
John McCall70aa5392010-01-06 05:24:50 +00005636 /// True if the int is known not to have negative values.
5637 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005638
John McCall70aa5392010-01-06 05:24:50 +00005639 IntRange(unsigned Width, bool NonNegative)
5640 : Width(Width), NonNegative(NonNegative)
5641 {}
John McCallca01b222010-01-04 23:21:16 +00005642
John McCall817d4af2010-11-10 23:38:19 +00005643 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005644 static IntRange forBoolType() {
5645 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005646 }
5647
John McCall817d4af2010-11-10 23:38:19 +00005648 /// Returns the range of an opaque value of the given integral type.
5649 static IntRange forValueOfType(ASTContext &C, QualType T) {
5650 return forValueOfCanonicalType(C,
5651 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005652 }
5653
John McCall817d4af2010-11-10 23:38:19 +00005654 /// Returns the range of an opaque value of a canonical integral type.
5655 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005656 assert(T->isCanonicalUnqualified());
5657
5658 if (const VectorType *VT = dyn_cast<VectorType>(T))
5659 T = VT->getElementType().getTypePtr();
5660 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5661 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005662 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5663 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005664
David Majnemer6a426652013-06-07 22:07:20 +00005665 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005666 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005667 EnumDecl *Enum = ET->getDecl();
5668 if (!Enum->isCompleteDefinition())
5669 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005670
David Majnemer6a426652013-06-07 22:07:20 +00005671 unsigned NumPositive = Enum->getNumPositiveBits();
5672 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005673
David Majnemer6a426652013-06-07 22:07:20 +00005674 if (NumNegative == 0)
5675 return IntRange(NumPositive, true/*NonNegative*/);
5676 else
5677 return IntRange(std::max(NumPositive + 1, NumNegative),
5678 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005679 }
John McCall70aa5392010-01-06 05:24:50 +00005680
5681 const BuiltinType *BT = cast<BuiltinType>(T);
5682 assert(BT->isInteger());
5683
5684 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5685 }
5686
John McCall817d4af2010-11-10 23:38:19 +00005687 /// Returns the "target" range of a canonical integral type, i.e.
5688 /// the range of values expressible in the type.
5689 ///
5690 /// This matches forValueOfCanonicalType except that enums have the
5691 /// full range of their type, not the range of their enumerators.
5692 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5693 assert(T->isCanonicalUnqualified());
5694
5695 if (const VectorType *VT = dyn_cast<VectorType>(T))
5696 T = VT->getElementType().getTypePtr();
5697 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5698 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005699 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5700 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005701 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005702 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005703
5704 const BuiltinType *BT = cast<BuiltinType>(T);
5705 assert(BT->isInteger());
5706
5707 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5708 }
5709
5710 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005711 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005712 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005713 L.NonNegative && R.NonNegative);
5714 }
5715
John McCall817d4af2010-11-10 23:38:19 +00005716 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005717 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005718 return IntRange(std::min(L.Width, R.Width),
5719 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005720 }
5721};
5722
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005723static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5724 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005725 if (value.isSigned() && value.isNegative())
5726 return IntRange(value.getMinSignedBits(), false);
5727
5728 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005729 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005730
5731 // isNonNegative() just checks the sign bit without considering
5732 // signedness.
5733 return IntRange(value.getActiveBits(), true);
5734}
5735
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005736static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5737 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005738 if (result.isInt())
5739 return GetValueRange(C, result.getInt(), MaxWidth);
5740
5741 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005742 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5743 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5744 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5745 R = IntRange::join(R, El);
5746 }
John McCall70aa5392010-01-06 05:24:50 +00005747 return R;
5748 }
5749
5750 if (result.isComplexInt()) {
5751 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5752 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5753 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005754 }
5755
5756 // This can happen with lossless casts to intptr_t of "based" lvalues.
5757 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005758 // FIXME: The only reason we need to pass the type in here is to get
5759 // the sign right on this one case. It would be nice if APValue
5760 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005761 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005762 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005763}
John McCall70aa5392010-01-06 05:24:50 +00005764
Eli Friedmane6d33952013-07-08 20:20:06 +00005765static QualType GetExprType(Expr *E) {
5766 QualType Ty = E->getType();
5767 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5768 Ty = AtomicRHS->getValueType();
5769 return Ty;
5770}
5771
John McCall70aa5392010-01-06 05:24:50 +00005772/// Pseudo-evaluate the given integer expression, estimating the
5773/// range of values it might take.
5774///
5775/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005776static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005777 E = E->IgnoreParens();
5778
5779 // Try a full evaluation first.
5780 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005781 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005782 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005783
5784 // I think we only want to look through implicit casts here; if the
5785 // user has an explicit widening cast, we should treat the value as
5786 // being of the new, wider type.
5787 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005788 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005789 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5790
Eli Friedmane6d33952013-07-08 20:20:06 +00005791 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005792
John McCalle3027922010-08-25 11:45:40 +00005793 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005794
John McCall70aa5392010-01-06 05:24:50 +00005795 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005796 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005797 return OutputTypeRange;
5798
5799 IntRange SubRange
5800 = GetExprRange(C, CE->getSubExpr(),
5801 std::min(MaxWidth, OutputTypeRange.Width));
5802
5803 // Bail out if the subexpr's range is as wide as the cast type.
5804 if (SubRange.Width >= OutputTypeRange.Width)
5805 return OutputTypeRange;
5806
5807 // Otherwise, we take the smaller width, and we're non-negative if
5808 // either the output type or the subexpr is.
5809 return IntRange(SubRange.Width,
5810 SubRange.NonNegative || OutputTypeRange.NonNegative);
5811 }
5812
5813 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5814 // If we can fold the condition, just take that operand.
5815 bool CondResult;
5816 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5817 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5818 : CO->getFalseExpr(),
5819 MaxWidth);
5820
5821 // Otherwise, conservatively merge.
5822 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5823 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5824 return IntRange::join(L, R);
5825 }
5826
5827 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5828 switch (BO->getOpcode()) {
5829
5830 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005831 case BO_LAnd:
5832 case BO_LOr:
5833 case BO_LT:
5834 case BO_GT:
5835 case BO_LE:
5836 case BO_GE:
5837 case BO_EQ:
5838 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005839 return IntRange::forBoolType();
5840
John McCallc3688382011-07-13 06:35:24 +00005841 // The type of the assignments is the type of the LHS, so the RHS
5842 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005843 case BO_MulAssign:
5844 case BO_DivAssign:
5845 case BO_RemAssign:
5846 case BO_AddAssign:
5847 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005848 case BO_XorAssign:
5849 case BO_OrAssign:
5850 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005851 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005852
John McCallc3688382011-07-13 06:35:24 +00005853 // Simple assignments just pass through the RHS, which will have
5854 // been coerced to the LHS type.
5855 case BO_Assign:
5856 // TODO: bitfields?
5857 return GetExprRange(C, BO->getRHS(), MaxWidth);
5858
John McCall70aa5392010-01-06 05:24:50 +00005859 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005860 case BO_PtrMemD:
5861 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005862 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005863
John McCall2ce81ad2010-01-06 22:07:33 +00005864 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005865 case BO_And:
5866 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005867 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5868 GetExprRange(C, BO->getRHS(), MaxWidth));
5869
John McCall70aa5392010-01-06 05:24:50 +00005870 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005871 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005872 // ...except that we want to treat '1 << (blah)' as logically
5873 // positive. It's an important idiom.
5874 if (IntegerLiteral *I
5875 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5876 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005877 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005878 return IntRange(R.Width, /*NonNegative*/ true);
5879 }
5880 }
5881 // fallthrough
5882
John McCalle3027922010-08-25 11:45:40 +00005883 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005884 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005885
John McCall2ce81ad2010-01-06 22:07:33 +00005886 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005887 case BO_Shr:
5888 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005889 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5890
5891 // If the shift amount is a positive constant, drop the width by
5892 // that much.
5893 llvm::APSInt shift;
5894 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5895 shift.isNonNegative()) {
5896 unsigned zext = shift.getZExtValue();
5897 if (zext >= L.Width)
5898 L.Width = (L.NonNegative ? 0 : 1);
5899 else
5900 L.Width -= zext;
5901 }
5902
5903 return L;
5904 }
5905
5906 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005907 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005908 return GetExprRange(C, BO->getRHS(), MaxWidth);
5909
John McCall2ce81ad2010-01-06 22:07:33 +00005910 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005911 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005912 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005913 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005914 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005915
John McCall51431812011-07-14 22:39:48 +00005916 // The width of a division result is mostly determined by the size
5917 // of the LHS.
5918 case BO_Div: {
5919 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005920 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005921 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5922
5923 // If the divisor is constant, use that.
5924 llvm::APSInt divisor;
5925 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5926 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5927 if (log2 >= L.Width)
5928 L.Width = (L.NonNegative ? 0 : 1);
5929 else
5930 L.Width = std::min(L.Width - log2, MaxWidth);
5931 return L;
5932 }
5933
5934 // Otherwise, just use the LHS's width.
5935 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5936 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5937 }
5938
5939 // The result of a remainder can't be larger than the result of
5940 // either side.
5941 case BO_Rem: {
5942 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005943 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005944 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5945 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5946
5947 IntRange meet = IntRange::meet(L, R);
5948 meet.Width = std::min(meet.Width, MaxWidth);
5949 return meet;
5950 }
5951
5952 // The default behavior is okay for these.
5953 case BO_Mul:
5954 case BO_Add:
5955 case BO_Xor:
5956 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005957 break;
5958 }
5959
John McCall51431812011-07-14 22:39:48 +00005960 // The default case is to treat the operation as if it were closed
5961 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005962 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5963 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5964 return IntRange::join(L, R);
5965 }
5966
5967 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5968 switch (UO->getOpcode()) {
5969 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005970 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005971 return IntRange::forBoolType();
5972
5973 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005974 case UO_Deref:
5975 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005976 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005977
5978 default:
5979 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5980 }
5981 }
5982
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005983 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5984 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5985
John McCalld25db7e2013-05-06 21:39:12 +00005986 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005987 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005988 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005989
Eli Friedmane6d33952013-07-08 20:20:06 +00005990 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005991}
John McCall263a48b2010-01-04 23:31:57 +00005992
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005993static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005994 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005995}
5996
John McCall263a48b2010-01-04 23:31:57 +00005997/// Checks whether the given value, which currently has the given
5998/// source semantics, has the same value when coerced through the
5999/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006000static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6001 const llvm::fltSemantics &Src,
6002 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006003 llvm::APFloat truncated = value;
6004
6005 bool ignored;
6006 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6007 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6008
6009 return truncated.bitwiseIsEqual(value);
6010}
6011
6012/// Checks whether the given value, which currently has the given
6013/// source semantics, has the same value when coerced through the
6014/// target semantics.
6015///
6016/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006017static bool IsSameFloatAfterCast(const APValue &value,
6018 const llvm::fltSemantics &Src,
6019 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006020 if (value.isFloat())
6021 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6022
6023 if (value.isVector()) {
6024 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6025 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6026 return false;
6027 return true;
6028 }
6029
6030 assert(value.isComplexFloat());
6031 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6032 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6033}
6034
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006035static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006036
Ted Kremenek6274be42010-09-23 21:43:44 +00006037static bool IsZero(Sema &S, Expr *E) {
6038 // Suppress cases where we are comparing against an enum constant.
6039 if (const DeclRefExpr *DR =
6040 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6041 if (isa<EnumConstantDecl>(DR->getDecl()))
6042 return false;
6043
6044 // Suppress cases where the '0' value is expanded from a macro.
6045 if (E->getLocStart().isMacroID())
6046 return false;
6047
John McCallcc7e5bf2010-05-06 08:58:33 +00006048 llvm::APSInt Value;
6049 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6050}
6051
John McCall2551c1b2010-10-06 00:25:24 +00006052static bool HasEnumType(Expr *E) {
6053 // Strip off implicit integral promotions.
6054 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006055 if (ICE->getCastKind() != CK_IntegralCast &&
6056 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006057 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006058 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006059 }
6060
6061 return E->getType()->isEnumeralType();
6062}
6063
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006064static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006065 // Disable warning in template instantiations.
6066 if (!S.ActiveTemplateInstantiations.empty())
6067 return;
6068
John McCalle3027922010-08-25 11:45:40 +00006069 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006070 if (E->isValueDependent())
6071 return;
6072
John McCalle3027922010-08-25 11:45:40 +00006073 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006074 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006075 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006076 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006077 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006078 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006079 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006080 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006081 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006082 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006083 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006084 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006085 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006086 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006087 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006088 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6089 }
6090}
6091
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006092static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006093 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006094 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006095 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006096 // Disable warning in template instantiations.
6097 if (!S.ActiveTemplateInstantiations.empty())
6098 return;
6099
Richard Trieu0f097742014-04-04 04:13:47 +00006100 // TODO: Investigate using GetExprRange() to get tighter bounds
6101 // on the bit ranges.
6102 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00006103 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
6104 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006105 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6106 unsigned OtherWidth = OtherRange.Width;
6107
6108 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6109
Richard Trieu560910c2012-11-14 22:50:24 +00006110 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006111 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006112 return;
6113
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006114 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006115 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006116
Richard Trieu0f097742014-04-04 04:13:47 +00006117 // Used for diagnostic printout.
6118 enum {
6119 LiteralConstant = 0,
6120 CXXBoolLiteralTrue,
6121 CXXBoolLiteralFalse
6122 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006123
Richard Trieu0f097742014-04-04 04:13:47 +00006124 if (!OtherIsBooleanType) {
6125 QualType ConstantT = Constant->getType();
6126 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006127
Richard Trieu0f097742014-04-04 04:13:47 +00006128 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6129 return;
6130 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6131 "comparison with non-integer type");
6132
6133 bool ConstantSigned = ConstantT->isSignedIntegerType();
6134 bool CommonSigned = CommonT->isSignedIntegerType();
6135
6136 bool EqualityOnly = false;
6137
6138 if (CommonSigned) {
6139 // The common type is signed, therefore no signed to unsigned conversion.
6140 if (!OtherRange.NonNegative) {
6141 // Check that the constant is representable in type OtherT.
6142 if (ConstantSigned) {
6143 if (OtherWidth >= Value.getMinSignedBits())
6144 return;
6145 } else { // !ConstantSigned
6146 if (OtherWidth >= Value.getActiveBits() + 1)
6147 return;
6148 }
6149 } else { // !OtherSigned
6150 // Check that the constant is representable in type OtherT.
6151 // Negative values are out of range.
6152 if (ConstantSigned) {
6153 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6154 return;
6155 } else { // !ConstantSigned
6156 if (OtherWidth >= Value.getActiveBits())
6157 return;
6158 }
Richard Trieu560910c2012-11-14 22:50:24 +00006159 }
Richard Trieu0f097742014-04-04 04:13:47 +00006160 } else { // !CommonSigned
6161 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006162 if (OtherWidth >= Value.getActiveBits())
6163 return;
Craig Toppercf360162014-06-18 05:13:11 +00006164 } else { // OtherSigned
6165 assert(!ConstantSigned &&
6166 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006167 // Check to see if the constant is representable in OtherT.
6168 if (OtherWidth > Value.getActiveBits())
6169 return;
6170 // Check to see if the constant is equivalent to a negative value
6171 // cast to CommonT.
6172 if (S.Context.getIntWidth(ConstantT) ==
6173 S.Context.getIntWidth(CommonT) &&
6174 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6175 return;
6176 // The constant value rests between values that OtherT can represent
6177 // after conversion. Relational comparison still works, but equality
6178 // comparisons will be tautological.
6179 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006180 }
6181 }
Richard Trieu0f097742014-04-04 04:13:47 +00006182
6183 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6184
6185 if (op == BO_EQ || op == BO_NE) {
6186 IsTrue = op == BO_NE;
6187 } else if (EqualityOnly) {
6188 return;
6189 } else if (RhsConstant) {
6190 if (op == BO_GT || op == BO_GE)
6191 IsTrue = !PositiveConstant;
6192 else // op == BO_LT || op == BO_LE
6193 IsTrue = PositiveConstant;
6194 } else {
6195 if (op == BO_LT || op == BO_LE)
6196 IsTrue = !PositiveConstant;
6197 else // op == BO_GT || op == BO_GE
6198 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006199 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006200 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006201 // Other isKnownToHaveBooleanValue
6202 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6203 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6204 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6205
6206 static const struct LinkedConditions {
6207 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6208 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6209 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6210 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6211 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6212 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6213
6214 } TruthTable = {
6215 // Constant on LHS. | Constant on RHS. |
6216 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6217 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6218 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6219 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6220 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6221 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6222 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6223 };
6224
6225 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6226
6227 enum ConstantValue ConstVal = Zero;
6228 if (Value.isUnsigned() || Value.isNonNegative()) {
6229 if (Value == 0) {
6230 LiteralOrBoolConstant =
6231 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6232 ConstVal = Zero;
6233 } else if (Value == 1) {
6234 LiteralOrBoolConstant =
6235 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6236 ConstVal = One;
6237 } else {
6238 LiteralOrBoolConstant = LiteralConstant;
6239 ConstVal = GT_One;
6240 }
6241 } else {
6242 ConstVal = LT_Zero;
6243 }
6244
6245 CompareBoolWithConstantResult CmpRes;
6246
6247 switch (op) {
6248 case BO_LT:
6249 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6250 break;
6251 case BO_GT:
6252 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6253 break;
6254 case BO_LE:
6255 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6256 break;
6257 case BO_GE:
6258 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6259 break;
6260 case BO_EQ:
6261 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6262 break;
6263 case BO_NE:
6264 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6265 break;
6266 default:
6267 CmpRes = Unkwn;
6268 break;
6269 }
6270
6271 if (CmpRes == AFals) {
6272 IsTrue = false;
6273 } else if (CmpRes == ATrue) {
6274 IsTrue = true;
6275 } else {
6276 return;
6277 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006278 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006279
6280 // If this is a comparison to an enum constant, include that
6281 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006282 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006283 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6284 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6285
6286 SmallString<64> PrettySourceValue;
6287 llvm::raw_svector_ostream OS(PrettySourceValue);
6288 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006289 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006290 else
6291 OS << Value;
6292
Richard Trieu0f097742014-04-04 04:13:47 +00006293 S.DiagRuntimeBehavior(
6294 E->getOperatorLoc(), E,
6295 S.PDiag(diag::warn_out_of_range_compare)
6296 << OS.str() << LiteralOrBoolConstant
6297 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6298 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006299}
6300
John McCallcc7e5bf2010-05-06 08:58:33 +00006301/// Analyze the operands of the given comparison. Implements the
6302/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006303static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006304 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6305 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006306}
John McCall263a48b2010-01-04 23:31:57 +00006307
John McCallca01b222010-01-04 23:21:16 +00006308/// \brief Implements -Wsign-compare.
6309///
Richard Trieu82402a02011-09-15 21:56:47 +00006310/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006311static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006312 // The type the comparison is being performed in.
6313 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006314
6315 // Only analyze comparison operators where both sides have been converted to
6316 // the same type.
6317 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6318 return AnalyzeImpConvsInComparison(S, E);
6319
6320 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006321 if (E->isValueDependent())
6322 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006323
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006324 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6325 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006326
6327 bool IsComparisonConstant = false;
6328
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006329 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006330 // of 'true' or 'false'.
6331 if (T->isIntegralType(S.Context)) {
6332 llvm::APSInt RHSValue;
6333 bool IsRHSIntegralLiteral =
6334 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6335 llvm::APSInt LHSValue;
6336 bool IsLHSIntegralLiteral =
6337 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6338 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6339 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6340 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6341 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6342 else
6343 IsComparisonConstant =
6344 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006345 } else if (!T->hasUnsignedIntegerRepresentation())
6346 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006347
John McCallcc7e5bf2010-05-06 08:58:33 +00006348 // We don't do anything special if this isn't an unsigned integral
6349 // comparison: we're only interested in integral comparisons, and
6350 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006351 //
6352 // We also don't care about value-dependent expressions or expressions
6353 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006354 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006355 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006356
John McCallcc7e5bf2010-05-06 08:58:33 +00006357 // Check to see if one of the (unmodified) operands is of different
6358 // signedness.
6359 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006360 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6361 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006362 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006363 signedOperand = LHS;
6364 unsignedOperand = RHS;
6365 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6366 signedOperand = RHS;
6367 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006368 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006369 CheckTrivialUnsignedComparison(S, E);
6370 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006371 }
6372
John McCallcc7e5bf2010-05-06 08:58:33 +00006373 // Otherwise, calculate the effective range of the signed operand.
6374 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006375
John McCallcc7e5bf2010-05-06 08:58:33 +00006376 // Go ahead and analyze implicit conversions in the operands. Note
6377 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006378 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6379 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006380
John McCallcc7e5bf2010-05-06 08:58:33 +00006381 // If the signed range is non-negative, -Wsign-compare won't fire,
6382 // but we should still check for comparisons which are always true
6383 // or false.
6384 if (signedRange.NonNegative)
6385 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006386
6387 // For (in)equality comparisons, if the unsigned operand is a
6388 // constant which cannot collide with a overflowed signed operand,
6389 // then reinterpreting the signed operand as unsigned will not
6390 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006391 if (E->isEqualityOp()) {
6392 unsigned comparisonWidth = S.Context.getIntWidth(T);
6393 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006394
John McCallcc7e5bf2010-05-06 08:58:33 +00006395 // We should never be unable to prove that the unsigned operand is
6396 // non-negative.
6397 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6398
6399 if (unsignedRange.Width < comparisonWidth)
6400 return;
6401 }
6402
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006403 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6404 S.PDiag(diag::warn_mixed_sign_comparison)
6405 << LHS->getType() << RHS->getType()
6406 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006407}
6408
John McCall1f425642010-11-11 03:21:53 +00006409/// Analyzes an attempt to assign the given value to a bitfield.
6410///
6411/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006412static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6413 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006414 assert(Bitfield->isBitField());
6415 if (Bitfield->isInvalidDecl())
6416 return false;
6417
John McCalldeebbcf2010-11-11 05:33:51 +00006418 // White-list bool bitfields.
6419 if (Bitfield->getType()->isBooleanType())
6420 return false;
6421
Douglas Gregor789adec2011-02-04 13:09:01 +00006422 // Ignore value- or type-dependent expressions.
6423 if (Bitfield->getBitWidth()->isValueDependent() ||
6424 Bitfield->getBitWidth()->isTypeDependent() ||
6425 Init->isValueDependent() ||
6426 Init->isTypeDependent())
6427 return false;
6428
John McCall1f425642010-11-11 03:21:53 +00006429 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6430
Richard Smith5fab0c92011-12-28 19:48:30 +00006431 llvm::APSInt Value;
6432 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006433 return false;
6434
John McCall1f425642010-11-11 03:21:53 +00006435 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006436 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006437
6438 if (OriginalWidth <= FieldWidth)
6439 return false;
6440
Eli Friedmanc267a322012-01-26 23:11:39 +00006441 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006442 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006443 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006444
Eli Friedmanc267a322012-01-26 23:11:39 +00006445 // Check whether the stored value is equal to the original value.
6446 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006447 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006448 return false;
6449
Eli Friedmanc267a322012-01-26 23:11:39 +00006450 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006451 // therefore don't strictly fit into a signed bitfield of width 1.
6452 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006453 return false;
6454
John McCall1f425642010-11-11 03:21:53 +00006455 std::string PrettyValue = Value.toString(10);
6456 std::string PrettyTrunc = TruncatedValue.toString(10);
6457
6458 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6459 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6460 << Init->getSourceRange();
6461
6462 return true;
6463}
6464
John McCalld2a53122010-11-09 23:24:47 +00006465/// Analyze the given simple or compound assignment for warning-worthy
6466/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006467static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006468 // Just recurse on the LHS.
6469 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6470
6471 // We want to recurse on the RHS as normal unless we're assigning to
6472 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006473 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006474 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006475 E->getOperatorLoc())) {
6476 // Recurse, ignoring any implicit conversions on the RHS.
6477 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6478 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006479 }
6480 }
6481
6482 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6483}
6484
John McCall263a48b2010-01-04 23:31:57 +00006485/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006486static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006487 SourceLocation CContext, unsigned diag,
6488 bool pruneControlFlow = false) {
6489 if (pruneControlFlow) {
6490 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6491 S.PDiag(diag)
6492 << SourceType << T << E->getSourceRange()
6493 << SourceRange(CContext));
6494 return;
6495 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006496 S.Diag(E->getExprLoc(), diag)
6497 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6498}
6499
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006500/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006501static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006502 SourceLocation CContext, unsigned diag,
6503 bool pruneControlFlow = false) {
6504 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006505}
6506
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006507/// Diagnose an implicit cast from a literal expression. Does not warn when the
6508/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006509void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6510 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006511 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006512 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006513 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006514 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6515 T->hasUnsignedIntegerRepresentation());
6516 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006517 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006518 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006519 return;
6520
Eli Friedman07185912013-08-29 23:44:43 +00006521 // FIXME: Force the precision of the source value down so we don't print
6522 // digits which are usually useless (we don't really care here if we
6523 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6524 // would automatically print the shortest representation, but it's a bit
6525 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006526 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006527 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6528 precision = (precision * 59 + 195) / 196;
6529 Value.toString(PrettySourceValue, precision);
6530
David Blaikie9b88cc02012-05-15 17:18:27 +00006531 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006532 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6533 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6534 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006535 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006536
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006537 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006538 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6539 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006540}
6541
John McCall18a2c2c2010-11-09 22:22:12 +00006542std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6543 if (!Range.Width) return "0";
6544
6545 llvm::APSInt ValueInRange = Value;
6546 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006547 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006548 return ValueInRange.toString(10);
6549}
6550
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006551static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6552 if (!isa<ImplicitCastExpr>(Ex))
6553 return false;
6554
6555 Expr *InnerE = Ex->IgnoreParenImpCasts();
6556 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6557 const Type *Source =
6558 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6559 if (Target->isDependentType())
6560 return false;
6561
6562 const BuiltinType *FloatCandidateBT =
6563 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6564 const Type *BoolCandidateType = ToBool ? Target : Source;
6565
6566 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6567 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6568}
6569
6570void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6571 SourceLocation CC) {
6572 unsigned NumArgs = TheCall->getNumArgs();
6573 for (unsigned i = 0; i < NumArgs; ++i) {
6574 Expr *CurrA = TheCall->getArg(i);
6575 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6576 continue;
6577
6578 bool IsSwapped = ((i > 0) &&
6579 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6580 IsSwapped |= ((i < (NumArgs - 1)) &&
6581 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6582 if (IsSwapped) {
6583 // Warn on this floating-point to bool conversion.
6584 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6585 CurrA->getType(), CC,
6586 diag::warn_impcast_floating_point_to_bool);
6587 }
6588 }
6589}
6590
Richard Trieu5b993502014-10-15 03:42:06 +00006591static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6592 SourceLocation CC) {
6593 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6594 E->getExprLoc()))
6595 return;
6596
6597 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6598 const Expr::NullPointerConstantKind NullKind =
6599 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6600 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6601 return;
6602
6603 // Return if target type is a safe conversion.
6604 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6605 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6606 return;
6607
6608 SourceLocation Loc = E->getSourceRange().getBegin();
6609
6610 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6611 if (NullKind == Expr::NPCK_GNUNull) {
6612 if (Loc.isMacroID())
6613 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6614 }
6615
6616 // Only warn if the null and context location are in the same macro expansion.
6617 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6618 return;
6619
6620 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6621 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6622 << FixItHint::CreateReplacement(Loc,
6623 S.getFixItZeroLiteralForType(T, Loc));
6624}
6625
John McCallcc7e5bf2010-05-06 08:58:33 +00006626void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006627 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006628 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006629
John McCallcc7e5bf2010-05-06 08:58:33 +00006630 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6631 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6632 if (Source == Target) return;
6633 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006634
Chandler Carruthc22845a2011-07-26 05:40:03 +00006635 // If the conversion context location is invalid don't complain. We also
6636 // don't want to emit a warning if the issue occurs from the expansion of
6637 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6638 // delay this check as long as possible. Once we detect we are in that
6639 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006640 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006641 return;
6642
Richard Trieu021baa32011-09-23 20:10:00 +00006643 // Diagnose implicit casts to bool.
6644 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6645 if (isa<StringLiteral>(E))
6646 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006647 // and expressions, for instance, assert(0 && "error here"), are
6648 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006649 return DiagnoseImpCast(S, E, T, CC,
6650 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006651 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6652 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6653 // This covers the literal expressions that evaluate to Objective-C
6654 // objects.
6655 return DiagnoseImpCast(S, E, T, CC,
6656 diag::warn_impcast_objective_c_literal_to_bool);
6657 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006658 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6659 // Warn on pointer to bool conversion that is always true.
6660 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6661 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006662 }
Richard Trieu021baa32011-09-23 20:10:00 +00006663 }
John McCall263a48b2010-01-04 23:31:57 +00006664
6665 // Strip vector types.
6666 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006667 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006668 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006669 return;
John McCallacf0ee52010-10-08 02:01:28 +00006670 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006671 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006672
6673 // If the vector cast is cast between two vectors of the same size, it is
6674 // a bitcast, not a conversion.
6675 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6676 return;
John McCall263a48b2010-01-04 23:31:57 +00006677
6678 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6679 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6680 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006681 if (auto VecTy = dyn_cast<VectorType>(Target))
6682 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006683
6684 // Strip complex types.
6685 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006686 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006687 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006688 return;
6689
John McCallacf0ee52010-10-08 02:01:28 +00006690 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006691 }
John McCall263a48b2010-01-04 23:31:57 +00006692
6693 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6694 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6695 }
6696
6697 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6698 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6699
6700 // If the source is floating point...
6701 if (SourceBT && SourceBT->isFloatingPoint()) {
6702 // ...and the target is floating point...
6703 if (TargetBT && TargetBT->isFloatingPoint()) {
6704 // ...then warn if we're dropping FP rank.
6705
6706 // Builtin FP kinds are ordered by increasing FP rank.
6707 if (SourceBT->getKind() > TargetBT->getKind()) {
6708 // Don't warn about float constants that are precisely
6709 // representable in the target type.
6710 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006711 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006712 // Value might be a float, a float vector, or a float complex.
6713 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006714 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6715 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006716 return;
6717 }
6718
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006719 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006720 return;
6721
John McCallacf0ee52010-10-08 02:01:28 +00006722 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006723 }
6724 return;
6725 }
6726
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006727 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006728 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006729 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006730 return;
6731
Chandler Carruth22c7a792011-02-17 11:05:49 +00006732 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006733 // We also want to warn on, e.g., "int i = -1.234"
6734 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6735 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6736 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6737
Chandler Carruth016ef402011-04-10 08:36:24 +00006738 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6739 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006740 } else {
6741 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6742 }
6743 }
John McCall263a48b2010-01-04 23:31:57 +00006744
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006745 // If the target is bool, warn if expr is a function or method call.
6746 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6747 isa<CallExpr>(E)) {
6748 // Check last argument of function call to see if it is an
6749 // implicit cast from a type matching the type the result
6750 // is being cast to.
6751 CallExpr *CEx = cast<CallExpr>(E);
6752 unsigned NumArgs = CEx->getNumArgs();
6753 if (NumArgs > 0) {
6754 Expr *LastA = CEx->getArg(NumArgs - 1);
6755 Expr *InnerE = LastA->IgnoreParenImpCasts();
6756 const Type *InnerType =
6757 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6758 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6759 // Warn on this floating-point to bool conversion
6760 DiagnoseImpCast(S, E, T, CC,
6761 diag::warn_impcast_floating_point_to_bool);
6762 }
6763 }
6764 }
John McCall263a48b2010-01-04 23:31:57 +00006765 return;
6766 }
6767
Richard Trieu5b993502014-10-15 03:42:06 +00006768 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006769
David Blaikie9366d2b2012-06-19 21:19:06 +00006770 if (!Source->isIntegerType() || !Target->isIntegerType())
6771 return;
6772
David Blaikie7555b6a2012-05-15 16:56:36 +00006773 // TODO: remove this early return once the false positives for constant->bool
6774 // in templates, macros, etc, are reduced or removed.
6775 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6776 return;
6777
John McCallcc7e5bf2010-05-06 08:58:33 +00006778 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006779 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006780
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006781 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006782 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006783 // TODO: this should happen for bitfield stores, too.
6784 llvm::APSInt Value(32);
6785 if (E->isIntegerConstantExpr(Value, S.Context)) {
6786 if (S.SourceMgr.isInSystemMacro(CC))
6787 return;
6788
John McCall18a2c2c2010-11-09 22:22:12 +00006789 std::string PrettySourceValue = Value.toString(10);
6790 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006791
Ted Kremenek33ba9952011-10-22 02:37:33 +00006792 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6793 S.PDiag(diag::warn_impcast_integer_precision_constant)
6794 << PrettySourceValue << PrettyTargetValue
6795 << E->getType() << T << E->getSourceRange()
6796 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006797 return;
6798 }
6799
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006800 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6801 if (S.SourceMgr.isInSystemMacro(CC))
6802 return;
6803
David Blaikie9455da02012-04-12 22:40:54 +00006804 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006805 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6806 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006807 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006808 }
6809
6810 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6811 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6812 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006813
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006814 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006815 return;
6816
John McCallcc7e5bf2010-05-06 08:58:33 +00006817 unsigned DiagID = diag::warn_impcast_integer_sign;
6818
6819 // Traditionally, gcc has warned about this under -Wsign-compare.
6820 // We also want to warn about it in -Wconversion.
6821 // So if -Wconversion is off, use a completely identical diagnostic
6822 // in the sign-compare group.
6823 // The conditional-checking code will
6824 if (ICContext) {
6825 DiagID = diag::warn_impcast_integer_sign_conditional;
6826 *ICContext = true;
6827 }
6828
John McCallacf0ee52010-10-08 02:01:28 +00006829 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006830 }
6831
Douglas Gregora78f1932011-02-22 02:45:07 +00006832 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006833 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6834 // type, to give us better diagnostics.
6835 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006836 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006837 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6838 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6839 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6840 SourceType = S.Context.getTypeDeclType(Enum);
6841 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6842 }
6843 }
6844
Douglas Gregora78f1932011-02-22 02:45:07 +00006845 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6846 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006847 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6848 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006849 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006850 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006851 return;
6852
Douglas Gregor364f7db2011-03-12 00:14:31 +00006853 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006854 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006855 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006856
John McCall263a48b2010-01-04 23:31:57 +00006857 return;
6858}
6859
David Blaikie18e9ac72012-05-15 21:57:38 +00006860void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6861 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006862
6863void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006864 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006865 E = E->IgnoreParenImpCasts();
6866
6867 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006868 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006869
John McCallacf0ee52010-10-08 02:01:28 +00006870 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006871 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006872 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006873 return;
6874}
6875
David Blaikie18e9ac72012-05-15 21:57:38 +00006876void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6877 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006878 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006879
6880 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006881 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6882 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006883
6884 // If -Wconversion would have warned about either of the candidates
6885 // for a signedness conversion to the context type...
6886 if (!Suspicious) return;
6887
6888 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006889 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006890 return;
6891
John McCallcc7e5bf2010-05-06 08:58:33 +00006892 // ...then check whether it would have warned about either of the
6893 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006894 if (E->getType() == T) return;
6895
6896 Suspicious = false;
6897 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6898 E->getType(), CC, &Suspicious);
6899 if (!Suspicious)
6900 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006901 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006902}
6903
Richard Trieu65724892014-11-15 06:37:39 +00006904/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6905/// Input argument E is a logical expression.
6906static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6907 if (S.getLangOpts().Bool)
6908 return;
6909 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6910}
6911
John McCallcc7e5bf2010-05-06 08:58:33 +00006912/// AnalyzeImplicitConversions - Find and report any interesting
6913/// implicit conversions in the given expression. There are a couple
6914/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006915void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006916 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006917 Expr *E = OrigE->IgnoreParenImpCasts();
6918
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006919 if (E->isTypeDependent() || E->isValueDependent())
6920 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006921
John McCallcc7e5bf2010-05-06 08:58:33 +00006922 // For conditional operators, we analyze the arguments as if they
6923 // were being fed directly into the output.
6924 if (isa<ConditionalOperator>(E)) {
6925 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006926 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006927 return;
6928 }
6929
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006930 // Check implicit argument conversions for function calls.
6931 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6932 CheckImplicitArgumentConversions(S, Call, CC);
6933
John McCallcc7e5bf2010-05-06 08:58:33 +00006934 // Go ahead and check any implicit conversions we might have skipped.
6935 // The non-canonical typecheck is just an optimization;
6936 // CheckImplicitConversion will filter out dead implicit conversions.
6937 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006938 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006939
6940 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006941
6942 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006943 if (POE->getResultExpr())
6944 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006945 }
6946
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006947 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6948 if (OVE->getSourceExpr())
6949 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6950 return;
6951 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006952
John McCallcc7e5bf2010-05-06 08:58:33 +00006953 // Skip past explicit casts.
6954 if (isa<ExplicitCastExpr>(E)) {
6955 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006956 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006957 }
6958
John McCalld2a53122010-11-09 23:24:47 +00006959 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6960 // Do a somewhat different check with comparison operators.
6961 if (BO->isComparisonOp())
6962 return AnalyzeComparison(S, BO);
6963
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006964 // And with simple assignments.
6965 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006966 return AnalyzeAssignment(S, BO);
6967 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006968
6969 // These break the otherwise-useful invariant below. Fortunately,
6970 // we don't really need to recurse into them, because any internal
6971 // expressions should have been analyzed already when they were
6972 // built into statements.
6973 if (isa<StmtExpr>(E)) return;
6974
6975 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006976 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006977
6978 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006979 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006980 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006981 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006982 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006983 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006984 if (!ChildExpr)
6985 continue;
6986
Richard Trieu955231d2014-01-25 01:10:35 +00006987 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006988 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006989 // Ignore checking string literals that are in logical and operators.
6990 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006991 continue;
6992 AnalyzeImplicitConversions(S, ChildExpr, CC);
6993 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006994
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006995 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006996 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6997 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006998 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006999
7000 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7001 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007002 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007003 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007004
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007005 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7006 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007007 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007008}
7009
7010} // end anonymous namespace
7011
Richard Trieu3bb8b562014-02-26 02:36:06 +00007012enum {
7013 AddressOf,
7014 FunctionPointer,
7015 ArrayPointer
7016};
7017
Richard Trieuc1888e02014-06-28 23:25:37 +00007018// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7019// Returns true when emitting a warning about taking the address of a reference.
7020static bool CheckForReference(Sema &SemaRef, const Expr *E,
7021 PartialDiagnostic PD) {
7022 E = E->IgnoreParenImpCasts();
7023
7024 const FunctionDecl *FD = nullptr;
7025
7026 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7027 if (!DRE->getDecl()->getType()->isReferenceType())
7028 return false;
7029 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7030 if (!M->getMemberDecl()->getType()->isReferenceType())
7031 return false;
7032 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007033 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007034 return false;
7035 FD = Call->getDirectCallee();
7036 } else {
7037 return false;
7038 }
7039
7040 SemaRef.Diag(E->getExprLoc(), PD);
7041
7042 // If possible, point to location of function.
7043 if (FD) {
7044 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7045 }
7046
7047 return true;
7048}
7049
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007050// Returns true if the SourceLocation is expanded from any macro body.
7051// Returns false if the SourceLocation is invalid, is from not in a macro
7052// expansion, or is from expanded from a top-level macro argument.
7053static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7054 if (Loc.isInvalid())
7055 return false;
7056
7057 while (Loc.isMacroID()) {
7058 if (SM.isMacroBodyExpansion(Loc))
7059 return true;
7060 Loc = SM.getImmediateMacroCallerLoc(Loc);
7061 }
7062
7063 return false;
7064}
7065
Richard Trieu3bb8b562014-02-26 02:36:06 +00007066/// \brief Diagnose pointers that are always non-null.
7067/// \param E the expression containing the pointer
7068/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7069/// compared to a null pointer
7070/// \param IsEqual True when the comparison is equal to a null pointer
7071/// \param Range Extra SourceRange to highlight in the diagnostic
7072void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7073 Expr::NullPointerConstantKind NullKind,
7074 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007075 if (!E)
7076 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007077
7078 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007079 if (E->getExprLoc().isMacroID()) {
7080 const SourceManager &SM = getSourceManager();
7081 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7082 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007083 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007084 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007085 E = E->IgnoreImpCasts();
7086
7087 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7088
Richard Trieuf7432752014-06-06 21:39:26 +00007089 if (isa<CXXThisExpr>(E)) {
7090 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7091 : diag::warn_this_bool_conversion;
7092 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7093 return;
7094 }
7095
Richard Trieu3bb8b562014-02-26 02:36:06 +00007096 bool IsAddressOf = false;
7097
7098 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7099 if (UO->getOpcode() != UO_AddrOf)
7100 return;
7101 IsAddressOf = true;
7102 E = UO->getSubExpr();
7103 }
7104
Richard Trieuc1888e02014-06-28 23:25:37 +00007105 if (IsAddressOf) {
7106 unsigned DiagID = IsCompare
7107 ? diag::warn_address_of_reference_null_compare
7108 : diag::warn_address_of_reference_bool_conversion;
7109 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7110 << IsEqual;
7111 if (CheckForReference(*this, E, PD)) {
7112 return;
7113 }
7114 }
7115
Richard Trieu3bb8b562014-02-26 02:36:06 +00007116 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007117 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007118 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7119 D = R->getDecl();
7120 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7121 D = M->getMemberDecl();
7122 }
7123
7124 // Weak Decls can be null.
7125 if (!D || D->isWeak())
7126 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007127
7128 // Check for parameter decl with nonnull attribute
7129 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7130 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7131 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7132 unsigned NumArgs = FD->getNumParams();
7133 llvm::SmallBitVector AttrNonNull(NumArgs);
7134 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7135 if (!NonNull->args_size()) {
7136 AttrNonNull.set(0, NumArgs);
7137 break;
7138 }
7139 for (unsigned Val : NonNull->args()) {
7140 if (Val >= NumArgs)
7141 continue;
7142 AttrNonNull.set(Val);
7143 }
7144 }
7145 if (!AttrNonNull.empty())
7146 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007147 if (FD->getParamDecl(i) == PV &&
7148 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007149 std::string Str;
7150 llvm::raw_string_ostream S(Str);
7151 E->printPretty(S, nullptr, getPrintingPolicy());
7152 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7153 : diag::warn_cast_nonnull_to_bool;
7154 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7155 << Range << IsEqual;
7156 return;
7157 }
7158 }
7159 }
7160
Richard Trieu3bb8b562014-02-26 02:36:06 +00007161 QualType T = D->getType();
7162 const bool IsArray = T->isArrayType();
7163 const bool IsFunction = T->isFunctionType();
7164
Richard Trieuc1888e02014-06-28 23:25:37 +00007165 // Address of function is used to silence the function warning.
7166 if (IsAddressOf && IsFunction) {
7167 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007168 }
7169
7170 // Found nothing.
7171 if (!IsAddressOf && !IsFunction && !IsArray)
7172 return;
7173
7174 // Pretty print the expression for the diagnostic.
7175 std::string Str;
7176 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007177 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007178
7179 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7180 : diag::warn_impcast_pointer_to_bool;
7181 unsigned DiagType;
7182 if (IsAddressOf)
7183 DiagType = AddressOf;
7184 else if (IsFunction)
7185 DiagType = FunctionPointer;
7186 else if (IsArray)
7187 DiagType = ArrayPointer;
7188 else
7189 llvm_unreachable("Could not determine diagnostic.");
7190 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7191 << Range << IsEqual;
7192
7193 if (!IsFunction)
7194 return;
7195
7196 // Suggest '&' to silence the function warning.
7197 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7198 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7199
7200 // Check to see if '()' fixit should be emitted.
7201 QualType ReturnType;
7202 UnresolvedSet<4> NonTemplateOverloads;
7203 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7204 if (ReturnType.isNull())
7205 return;
7206
7207 if (IsCompare) {
7208 // There are two cases here. If there is null constant, the only suggest
7209 // for a pointer return type. If the null is 0, then suggest if the return
7210 // type is a pointer or an integer type.
7211 if (!ReturnType->isPointerType()) {
7212 if (NullKind == Expr::NPCK_ZeroExpression ||
7213 NullKind == Expr::NPCK_ZeroLiteral) {
7214 if (!ReturnType->isIntegerType())
7215 return;
7216 } else {
7217 return;
7218 }
7219 }
7220 } else { // !IsCompare
7221 // For function to bool, only suggest if the function pointer has bool
7222 // return type.
7223 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7224 return;
7225 }
7226 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007227 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007228}
7229
7230
John McCallcc7e5bf2010-05-06 08:58:33 +00007231/// Diagnoses "dangerous" implicit conversions within the given
7232/// expression (which is a full expression). Implements -Wconversion
7233/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007234///
7235/// \param CC the "context" location of the implicit conversion, i.e.
7236/// the most location of the syntactic entity requiring the implicit
7237/// conversion
7238void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007239 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007240 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007241 return;
7242
7243 // Don't diagnose for value- or type-dependent expressions.
7244 if (E->isTypeDependent() || E->isValueDependent())
7245 return;
7246
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007247 // Check for array bounds violations in cases where the check isn't triggered
7248 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7249 // ArraySubscriptExpr is on the RHS of a variable initialization.
7250 CheckArrayAccess(E);
7251
John McCallacf0ee52010-10-08 02:01:28 +00007252 // This is not the right CC for (e.g.) a variable initialization.
7253 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007254}
7255
Richard Trieu65724892014-11-15 06:37:39 +00007256/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7257/// Input argument E is a logical expression.
7258void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7259 ::CheckBoolLikeConversion(*this, E, CC);
7260}
7261
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007262/// Diagnose when expression is an integer constant expression and its evaluation
7263/// results in integer overflow
7264void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007265 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7266 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007267}
7268
Richard Smithc406cb72013-01-17 01:17:56 +00007269namespace {
7270/// \brief Visitor for expressions which looks for unsequenced operations on the
7271/// same object.
7272class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007273 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7274
Richard Smithc406cb72013-01-17 01:17:56 +00007275 /// \brief A tree of sequenced regions within an expression. Two regions are
7276 /// unsequenced if one is an ancestor or a descendent of the other. When we
7277 /// finish processing an expression with sequencing, such as a comma
7278 /// expression, we fold its tree nodes into its parent, since they are
7279 /// unsequenced with respect to nodes we will visit later.
7280 class SequenceTree {
7281 struct Value {
7282 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7283 unsigned Parent : 31;
7284 bool Merged : 1;
7285 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007286 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007287
7288 public:
7289 /// \brief A region within an expression which may be sequenced with respect
7290 /// to some other region.
7291 class Seq {
7292 explicit Seq(unsigned N) : Index(N) {}
7293 unsigned Index;
7294 friend class SequenceTree;
7295 public:
7296 Seq() : Index(0) {}
7297 };
7298
7299 SequenceTree() { Values.push_back(Value(0)); }
7300 Seq root() const { return Seq(0); }
7301
7302 /// \brief Create a new sequence of operations, which is an unsequenced
7303 /// subset of \p Parent. This sequence of operations is sequenced with
7304 /// respect to other children of \p Parent.
7305 Seq allocate(Seq Parent) {
7306 Values.push_back(Value(Parent.Index));
7307 return Seq(Values.size() - 1);
7308 }
7309
7310 /// \brief Merge a sequence of operations into its parent.
7311 void merge(Seq S) {
7312 Values[S.Index].Merged = true;
7313 }
7314
7315 /// \brief Determine whether two operations are unsequenced. This operation
7316 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7317 /// should have been merged into its parent as appropriate.
7318 bool isUnsequenced(Seq Cur, Seq Old) {
7319 unsigned C = representative(Cur.Index);
7320 unsigned Target = representative(Old.Index);
7321 while (C >= Target) {
7322 if (C == Target)
7323 return true;
7324 C = Values[C].Parent;
7325 }
7326 return false;
7327 }
7328
7329 private:
7330 /// \brief Pick a representative for a sequence.
7331 unsigned representative(unsigned K) {
7332 if (Values[K].Merged)
7333 // Perform path compression as we go.
7334 return Values[K].Parent = representative(Values[K].Parent);
7335 return K;
7336 }
7337 };
7338
7339 /// An object for which we can track unsequenced uses.
7340 typedef NamedDecl *Object;
7341
7342 /// Different flavors of object usage which we track. We only track the
7343 /// least-sequenced usage of each kind.
7344 enum UsageKind {
7345 /// A read of an object. Multiple unsequenced reads are OK.
7346 UK_Use,
7347 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007348 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007349 UK_ModAsValue,
7350 /// A modification of an object which is not sequenced before the value
7351 /// computation of the expression, such as n++.
7352 UK_ModAsSideEffect,
7353
7354 UK_Count = UK_ModAsSideEffect + 1
7355 };
7356
7357 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007358 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007359 Expr *Use;
7360 SequenceTree::Seq Seq;
7361 };
7362
7363 struct UsageInfo {
7364 UsageInfo() : Diagnosed(false) {}
7365 Usage Uses[UK_Count];
7366 /// Have we issued a diagnostic for this variable already?
7367 bool Diagnosed;
7368 };
7369 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7370
7371 Sema &SemaRef;
7372 /// Sequenced regions within the expression.
7373 SequenceTree Tree;
7374 /// Declaration modifications and references which we have seen.
7375 UsageInfoMap UsageMap;
7376 /// The region we are currently within.
7377 SequenceTree::Seq Region;
7378 /// Filled in with declarations which were modified as a side-effect
7379 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007380 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007381 /// Expressions to check later. We defer checking these to reduce
7382 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007383 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007384
7385 /// RAII object wrapping the visitation of a sequenced subexpression of an
7386 /// expression. At the end of this process, the side-effects of the evaluation
7387 /// become sequenced with respect to the value computation of the result, so
7388 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7389 /// UK_ModAsValue.
7390 struct SequencedSubexpression {
7391 SequencedSubexpression(SequenceChecker &Self)
7392 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7393 Self.ModAsSideEffect = &ModAsSideEffect;
7394 }
7395 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007396 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7397 MI != ME; ++MI) {
7398 UsageInfo &U = Self.UsageMap[MI->first];
7399 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7400 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7401 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007402 }
7403 Self.ModAsSideEffect = OldModAsSideEffect;
7404 }
7405
7406 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007407 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7408 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007409 };
7410
Richard Smith40238f02013-06-20 22:21:56 +00007411 /// RAII object wrapping the visitation of a subexpression which we might
7412 /// choose to evaluate as a constant. If any subexpression is evaluated and
7413 /// found to be non-constant, this allows us to suppress the evaluation of
7414 /// the outer expression.
7415 class EvaluationTracker {
7416 public:
7417 EvaluationTracker(SequenceChecker &Self)
7418 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7419 Self.EvalTracker = this;
7420 }
7421 ~EvaluationTracker() {
7422 Self.EvalTracker = Prev;
7423 if (Prev)
7424 Prev->EvalOK &= EvalOK;
7425 }
7426
7427 bool evaluate(const Expr *E, bool &Result) {
7428 if (!EvalOK || E->isValueDependent())
7429 return false;
7430 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7431 return EvalOK;
7432 }
7433
7434 private:
7435 SequenceChecker &Self;
7436 EvaluationTracker *Prev;
7437 bool EvalOK;
7438 } *EvalTracker;
7439
Richard Smithc406cb72013-01-17 01:17:56 +00007440 /// \brief Find the object which is produced by the specified expression,
7441 /// if any.
7442 Object getObject(Expr *E, bool Mod) const {
7443 E = E->IgnoreParenCasts();
7444 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7445 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7446 return getObject(UO->getSubExpr(), Mod);
7447 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7448 if (BO->getOpcode() == BO_Comma)
7449 return getObject(BO->getRHS(), Mod);
7450 if (Mod && BO->isAssignmentOp())
7451 return getObject(BO->getLHS(), Mod);
7452 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7453 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7454 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7455 return ME->getMemberDecl();
7456 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7457 // FIXME: If this is a reference, map through to its value.
7458 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007459 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007460 }
7461
7462 /// \brief Note that an object was modified or used by an expression.
7463 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7464 Usage &U = UI.Uses[UK];
7465 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7466 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7467 ModAsSideEffect->push_back(std::make_pair(O, U));
7468 U.Use = Ref;
7469 U.Seq = Region;
7470 }
7471 }
7472 /// \brief Check whether a modification or use conflicts with a prior usage.
7473 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7474 bool IsModMod) {
7475 if (UI.Diagnosed)
7476 return;
7477
7478 const Usage &U = UI.Uses[OtherKind];
7479 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7480 return;
7481
7482 Expr *Mod = U.Use;
7483 Expr *ModOrUse = Ref;
7484 if (OtherKind == UK_Use)
7485 std::swap(Mod, ModOrUse);
7486
7487 SemaRef.Diag(Mod->getExprLoc(),
7488 IsModMod ? diag::warn_unsequenced_mod_mod
7489 : diag::warn_unsequenced_mod_use)
7490 << O << SourceRange(ModOrUse->getExprLoc());
7491 UI.Diagnosed = true;
7492 }
7493
7494 void notePreUse(Object O, Expr *Use) {
7495 UsageInfo &U = UsageMap[O];
7496 // Uses conflict with other modifications.
7497 checkUsage(O, U, Use, UK_ModAsValue, false);
7498 }
7499 void notePostUse(Object O, Expr *Use) {
7500 UsageInfo &U = UsageMap[O];
7501 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7502 addUsage(U, O, Use, UK_Use);
7503 }
7504
7505 void notePreMod(Object O, Expr *Mod) {
7506 UsageInfo &U = UsageMap[O];
7507 // Modifications conflict with other modifications and with uses.
7508 checkUsage(O, U, Mod, UK_ModAsValue, true);
7509 checkUsage(O, U, Mod, UK_Use, false);
7510 }
7511 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7512 UsageInfo &U = UsageMap[O];
7513 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7514 addUsage(U, O, Use, UK);
7515 }
7516
7517public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007518 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007519 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7520 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007521 Visit(E);
7522 }
7523
7524 void VisitStmt(Stmt *S) {
7525 // Skip all statements which aren't expressions for now.
7526 }
7527
7528 void VisitExpr(Expr *E) {
7529 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007530 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007531 }
7532
7533 void VisitCastExpr(CastExpr *E) {
7534 Object O = Object();
7535 if (E->getCastKind() == CK_LValueToRValue)
7536 O = getObject(E->getSubExpr(), false);
7537
7538 if (O)
7539 notePreUse(O, E);
7540 VisitExpr(E);
7541 if (O)
7542 notePostUse(O, E);
7543 }
7544
7545 void VisitBinComma(BinaryOperator *BO) {
7546 // C++11 [expr.comma]p1:
7547 // Every value computation and side effect associated with the left
7548 // expression is sequenced before every value computation and side
7549 // effect associated with the right expression.
7550 SequenceTree::Seq LHS = Tree.allocate(Region);
7551 SequenceTree::Seq RHS = Tree.allocate(Region);
7552 SequenceTree::Seq OldRegion = Region;
7553
7554 {
7555 SequencedSubexpression SeqLHS(*this);
7556 Region = LHS;
7557 Visit(BO->getLHS());
7558 }
7559
7560 Region = RHS;
7561 Visit(BO->getRHS());
7562
7563 Region = OldRegion;
7564
7565 // Forget that LHS and RHS are sequenced. They are both unsequenced
7566 // with respect to other stuff.
7567 Tree.merge(LHS);
7568 Tree.merge(RHS);
7569 }
7570
7571 void VisitBinAssign(BinaryOperator *BO) {
7572 // The modification is sequenced after the value computation of the LHS
7573 // and RHS, so check it before inspecting the operands and update the
7574 // map afterwards.
7575 Object O = getObject(BO->getLHS(), true);
7576 if (!O)
7577 return VisitExpr(BO);
7578
7579 notePreMod(O, BO);
7580
7581 // C++11 [expr.ass]p7:
7582 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7583 // only once.
7584 //
7585 // Therefore, for a compound assignment operator, O is considered used
7586 // everywhere except within the evaluation of E1 itself.
7587 if (isa<CompoundAssignOperator>(BO))
7588 notePreUse(O, BO);
7589
7590 Visit(BO->getLHS());
7591
7592 if (isa<CompoundAssignOperator>(BO))
7593 notePostUse(O, BO);
7594
7595 Visit(BO->getRHS());
7596
Richard Smith83e37bee2013-06-26 23:16:51 +00007597 // C++11 [expr.ass]p1:
7598 // the assignment is sequenced [...] before the value computation of the
7599 // assignment expression.
7600 // C11 6.5.16/3 has no such rule.
7601 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7602 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007603 }
7604 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7605 VisitBinAssign(CAO);
7606 }
7607
7608 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7609 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7610 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7611 Object O = getObject(UO->getSubExpr(), true);
7612 if (!O)
7613 return VisitExpr(UO);
7614
7615 notePreMod(O, UO);
7616 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007617 // C++11 [expr.pre.incr]p1:
7618 // the expression ++x is equivalent to x+=1
7619 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7620 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007621 }
7622
7623 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7624 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7625 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7626 Object O = getObject(UO->getSubExpr(), true);
7627 if (!O)
7628 return VisitExpr(UO);
7629
7630 notePreMod(O, UO);
7631 Visit(UO->getSubExpr());
7632 notePostMod(O, UO, UK_ModAsSideEffect);
7633 }
7634
7635 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7636 void VisitBinLOr(BinaryOperator *BO) {
7637 // The side-effects of the LHS of an '&&' are sequenced before the
7638 // value computation of the RHS, and hence before the value computation
7639 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7640 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007641 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007642 {
7643 SequencedSubexpression Sequenced(*this);
7644 Visit(BO->getLHS());
7645 }
7646
7647 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007648 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007649 if (!Result)
7650 Visit(BO->getRHS());
7651 } else {
7652 // Check for unsequenced operations in the RHS, treating it as an
7653 // entirely separate evaluation.
7654 //
7655 // FIXME: If there are operations in the RHS which are unsequenced
7656 // with respect to operations outside the RHS, and those operations
7657 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007658 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007659 }
Richard Smithc406cb72013-01-17 01:17:56 +00007660 }
7661 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007662 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007663 {
7664 SequencedSubexpression Sequenced(*this);
7665 Visit(BO->getLHS());
7666 }
7667
7668 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007669 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007670 if (Result)
7671 Visit(BO->getRHS());
7672 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007673 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007674 }
Richard Smithc406cb72013-01-17 01:17:56 +00007675 }
7676
7677 // Only visit the condition, unless we can be sure which subexpression will
7678 // be chosen.
7679 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007680 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007681 {
7682 SequencedSubexpression Sequenced(*this);
7683 Visit(CO->getCond());
7684 }
Richard Smithc406cb72013-01-17 01:17:56 +00007685
7686 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007687 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007688 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007689 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007690 WorkList.push_back(CO->getTrueExpr());
7691 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007692 }
Richard Smithc406cb72013-01-17 01:17:56 +00007693 }
7694
Richard Smithe3dbfe02013-06-30 10:40:20 +00007695 void VisitCallExpr(CallExpr *CE) {
7696 // C++11 [intro.execution]p15:
7697 // When calling a function [...], every value computation and side effect
7698 // associated with any argument expression, or with the postfix expression
7699 // designating the called function, is sequenced before execution of every
7700 // expression or statement in the body of the function [and thus before
7701 // the value computation of its result].
7702 SequencedSubexpression Sequenced(*this);
7703 Base::VisitCallExpr(CE);
7704
7705 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7706 }
7707
Richard Smithc406cb72013-01-17 01:17:56 +00007708 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007709 // This is a call, so all subexpressions are sequenced before the result.
7710 SequencedSubexpression Sequenced(*this);
7711
Richard Smithc406cb72013-01-17 01:17:56 +00007712 if (!CCE->isListInitialization())
7713 return VisitExpr(CCE);
7714
7715 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007716 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007717 SequenceTree::Seq Parent = Region;
7718 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7719 E = CCE->arg_end();
7720 I != E; ++I) {
7721 Region = Tree.allocate(Parent);
7722 Elts.push_back(Region);
7723 Visit(*I);
7724 }
7725
7726 // Forget that the initializers are sequenced.
7727 Region = Parent;
7728 for (unsigned I = 0; I < Elts.size(); ++I)
7729 Tree.merge(Elts[I]);
7730 }
7731
7732 void VisitInitListExpr(InitListExpr *ILE) {
7733 if (!SemaRef.getLangOpts().CPlusPlus11)
7734 return VisitExpr(ILE);
7735
7736 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007737 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007738 SequenceTree::Seq Parent = Region;
7739 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7740 Expr *E = ILE->getInit(I);
7741 if (!E) continue;
7742 Region = Tree.allocate(Parent);
7743 Elts.push_back(Region);
7744 Visit(E);
7745 }
7746
7747 // Forget that the initializers are sequenced.
7748 Region = Parent;
7749 for (unsigned I = 0; I < Elts.size(); ++I)
7750 Tree.merge(Elts[I]);
7751 }
7752};
7753}
7754
7755void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007756 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007757 WorkList.push_back(E);
7758 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007759 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007760 SequenceChecker(*this, Item, WorkList);
7761 }
Richard Smithc406cb72013-01-17 01:17:56 +00007762}
7763
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007764void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7765 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007766 CheckImplicitConversions(E, CheckLoc);
7767 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007768 if (!IsConstexpr && !E->isValueDependent())
7769 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007770}
7771
John McCall1f425642010-11-11 03:21:53 +00007772void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7773 FieldDecl *BitField,
7774 Expr *Init) {
7775 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7776}
7777
David Majnemer61a5bbf2015-04-07 22:08:51 +00007778static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7779 SourceLocation Loc) {
7780 if (!PType->isVariablyModifiedType())
7781 return;
7782 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7783 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7784 return;
7785 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00007786 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7787 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7788 return;
7789 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00007790 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7791 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7792 return;
7793 }
7794
7795 const ArrayType *AT = S.Context.getAsArrayType(PType);
7796 if (!AT)
7797 return;
7798
7799 if (AT->getSizeModifier() != ArrayType::Star) {
7800 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7801 return;
7802 }
7803
7804 S.Diag(Loc, diag::err_array_star_in_function_definition);
7805}
7806
Mike Stump0c2ec772010-01-21 03:59:47 +00007807/// CheckParmsForFunctionDef - Check that the parameters of the given
7808/// function are appropriate for the definition of a function. This
7809/// takes care of any checks that cannot be performed on the
7810/// declaration itself, e.g., that the types of each of the function
7811/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007812bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7813 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007814 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007815 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007816 for (; P != PEnd; ++P) {
7817 ParmVarDecl *Param = *P;
7818
Mike Stump0c2ec772010-01-21 03:59:47 +00007819 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7820 // function declarator that is part of a function definition of
7821 // that function shall not have incomplete type.
7822 //
7823 // This is also C++ [dcl.fct]p6.
7824 if (!Param->isInvalidDecl() &&
7825 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007826 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007827 Param->setInvalidDecl();
7828 HasInvalidParm = true;
7829 }
7830
7831 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7832 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007833 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007834 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007835 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007836 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007837 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007838
7839 // C99 6.7.5.3p12:
7840 // If the function declarator is not part of a definition of that
7841 // function, parameters may have incomplete type and may use the [*]
7842 // notation in their sequences of declarator specifiers to specify
7843 // variable length array types.
7844 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00007845 // FIXME: This diagnostic should point the '[*]' if source-location
7846 // information is added for it.
7847 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007848
7849 // MSVC destroys objects passed by value in the callee. Therefore a
7850 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007851 // object's destructor. However, we don't perform any direct access check
7852 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007853 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7854 .getCXXABI()
7855 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007856 if (!Param->isInvalidDecl()) {
7857 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7858 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7859 if (!ClassDecl->isInvalidDecl() &&
7860 !ClassDecl->hasIrrelevantDestructor() &&
7861 !ClassDecl->isDependentContext()) {
7862 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7863 MarkFunctionReferenced(Param->getLocation(), Destructor);
7864 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7865 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007866 }
7867 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007868 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007869 }
7870
7871 return HasInvalidParm;
7872}
John McCall2b5c1b22010-08-12 21:44:57 +00007873
7874/// CheckCastAlign - Implements -Wcast-align, which warns when a
7875/// pointer cast increases the alignment requirements.
7876void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7877 // This is actually a lot of work to potentially be doing on every
7878 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007879 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007880 return;
7881
7882 // Ignore dependent types.
7883 if (T->isDependentType() || Op->getType()->isDependentType())
7884 return;
7885
7886 // Require that the destination be a pointer type.
7887 const PointerType *DestPtr = T->getAs<PointerType>();
7888 if (!DestPtr) return;
7889
7890 // If the destination has alignment 1, we're done.
7891 QualType DestPointee = DestPtr->getPointeeType();
7892 if (DestPointee->isIncompleteType()) return;
7893 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7894 if (DestAlign.isOne()) return;
7895
7896 // Require that the source be a pointer type.
7897 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7898 if (!SrcPtr) return;
7899 QualType SrcPointee = SrcPtr->getPointeeType();
7900
7901 // Whitelist casts from cv void*. We already implicitly
7902 // whitelisted casts to cv void*, since they have alignment 1.
7903 // Also whitelist casts involving incomplete types, which implicitly
7904 // includes 'void'.
7905 if (SrcPointee->isIncompleteType()) return;
7906
7907 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7908 if (SrcAlign >= DestAlign) return;
7909
7910 Diag(TRange.getBegin(), diag::warn_cast_align)
7911 << Op->getType() << T
7912 << static_cast<unsigned>(SrcAlign.getQuantity())
7913 << static_cast<unsigned>(DestAlign.getQuantity())
7914 << TRange << Op->getSourceRange();
7915}
7916
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007917static const Type* getElementType(const Expr *BaseExpr) {
7918 const Type* EltType = BaseExpr->getType().getTypePtr();
7919 if (EltType->isAnyPointerType())
7920 return EltType->getPointeeType().getTypePtr();
7921 else if (EltType->isArrayType())
7922 return EltType->getBaseElementTypeUnsafe();
7923 return EltType;
7924}
7925
Chandler Carruth28389f02011-08-05 09:10:50 +00007926/// \brief Check whether this array fits the idiom of a size-one tail padded
7927/// array member of a struct.
7928///
7929/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7930/// commonly used to emulate flexible arrays in C89 code.
7931static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7932 const NamedDecl *ND) {
7933 if (Size != 1 || !ND) return false;
7934
7935 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7936 if (!FD) return false;
7937
7938 // Don't consider sizes resulting from macro expansions or template argument
7939 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007940
7941 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007942 while (TInfo) {
7943 TypeLoc TL = TInfo->getTypeLoc();
7944 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007945 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7946 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007947 TInfo = TDL->getTypeSourceInfo();
7948 continue;
7949 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007950 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7951 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007952 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7953 return false;
7954 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007955 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007956 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007957
7958 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007959 if (!RD) return false;
7960 if (RD->isUnion()) return false;
7961 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7962 if (!CRD->isStandardLayout()) return false;
7963 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007964
Benjamin Kramer8c543672011-08-06 03:04:42 +00007965 // See if this is the last field decl in the record.
7966 const Decl *D = FD;
7967 while ((D = D->getNextDeclInContext()))
7968 if (isa<FieldDecl>(D))
7969 return false;
7970 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007971}
7972
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007973void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007974 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007975 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007976 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007977 if (IndexExpr->isValueDependent())
7978 return;
7979
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007980 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007981 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007982 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007983 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007984 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007985 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007986
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007987 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007988 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007989 return;
Richard Smith13f67182011-12-16 19:31:14 +00007990 if (IndexNegated)
7991 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007992
Craig Topperc3ec1492014-05-26 06:22:03 +00007993 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007994 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7995 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007996 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007997 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007998
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007999 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008000 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008001 if (!size.isStrictlyPositive())
8002 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008003
8004 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008005 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008006 // Make sure we're comparing apples to apples when comparing index to size
8007 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8008 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008009 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008010 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008011 if (ptrarith_typesize != array_typesize) {
8012 // There's a cast to a different size type involved
8013 uint64_t ratio = array_typesize / ptrarith_typesize;
8014 // TODO: Be smarter about handling cases where array_typesize is not a
8015 // multiple of ptrarith_typesize
8016 if (ptrarith_typesize * ratio == array_typesize)
8017 size *= llvm::APInt(size.getBitWidth(), ratio);
8018 }
8019 }
8020
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008021 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008022 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008023 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008024 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008025
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008026 // For array subscripting the index must be less than size, but for pointer
8027 // arithmetic also allow the index (offset) to be equal to size since
8028 // computing the next address after the end of the array is legal and
8029 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008030 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008031 return;
8032
8033 // Also don't warn for arrays of size 1 which are members of some
8034 // structure. These are often used to approximate flexible arrays in C89
8035 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008036 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008037 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008038
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008039 // Suppress the warning if the subscript expression (as identified by the
8040 // ']' location) and the index expression are both from macro expansions
8041 // within a system header.
8042 if (ASE) {
8043 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8044 ASE->getRBracketLoc());
8045 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8046 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8047 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008048 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008049 return;
8050 }
8051 }
8052
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008053 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008054 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008055 DiagID = diag::warn_array_index_exceeds_bounds;
8056
8057 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8058 PDiag(DiagID) << index.toString(10, true)
8059 << size.toString(10, true)
8060 << (unsigned)size.getLimitedValue(~0U)
8061 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008062 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008063 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008064 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008065 DiagID = diag::warn_ptr_arith_precedes_bounds;
8066 if (index.isNegative()) index = -index;
8067 }
8068
8069 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8070 PDiag(DiagID) << index.toString(10, true)
8071 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008072 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008073
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008074 if (!ND) {
8075 // Try harder to find a NamedDecl to point at in the note.
8076 while (const ArraySubscriptExpr *ASE =
8077 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8078 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8079 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8080 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8081 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8082 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8083 }
8084
Chandler Carruth1af88f12011-02-17 21:10:52 +00008085 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008086 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8087 PDiag(diag::note_array_index_out_of_bounds)
8088 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008089}
8090
Ted Kremenekdf26df72011-03-01 18:41:00 +00008091void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008092 int AllowOnePastEnd = 0;
8093 while (expr) {
8094 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008095 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008096 case Stmt::ArraySubscriptExprClass: {
8097 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008098 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008099 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008100 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008101 }
8102 case Stmt::UnaryOperatorClass: {
8103 // Only unwrap the * and & unary operators
8104 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8105 expr = UO->getSubExpr();
8106 switch (UO->getOpcode()) {
8107 case UO_AddrOf:
8108 AllowOnePastEnd++;
8109 break;
8110 case UO_Deref:
8111 AllowOnePastEnd--;
8112 break;
8113 default:
8114 return;
8115 }
8116 break;
8117 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008118 case Stmt::ConditionalOperatorClass: {
8119 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8120 if (const Expr *lhs = cond->getLHS())
8121 CheckArrayAccess(lhs);
8122 if (const Expr *rhs = cond->getRHS())
8123 CheckArrayAccess(rhs);
8124 return;
8125 }
8126 default:
8127 return;
8128 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008129 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008130}
John McCall31168b02011-06-15 23:02:42 +00008131
8132//===--- CHECK: Objective-C retain cycles ----------------------------------//
8133
8134namespace {
8135 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008136 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008137 VarDecl *Variable;
8138 SourceRange Range;
8139 SourceLocation Loc;
8140 bool Indirect;
8141
8142 void setLocsFrom(Expr *e) {
8143 Loc = e->getExprLoc();
8144 Range = e->getSourceRange();
8145 }
8146 };
8147}
8148
8149/// Consider whether capturing the given variable can possibly lead to
8150/// a retain cycle.
8151static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008152 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008153 // lifetime. In MRR, it's captured strongly if the variable is
8154 // __block and has an appropriate type.
8155 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8156 return false;
8157
8158 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008159 if (ref)
8160 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008161 return true;
8162}
8163
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008164static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008165 while (true) {
8166 e = e->IgnoreParens();
8167 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8168 switch (cast->getCastKind()) {
8169 case CK_BitCast:
8170 case CK_LValueBitCast:
8171 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008172 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008173 e = cast->getSubExpr();
8174 continue;
8175
John McCall31168b02011-06-15 23:02:42 +00008176 default:
8177 return false;
8178 }
8179 }
8180
8181 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8182 ObjCIvarDecl *ivar = ref->getDecl();
8183 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8184 return false;
8185
8186 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008187 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008188 return false;
8189
8190 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8191 owner.Indirect = true;
8192 return true;
8193 }
8194
8195 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8196 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8197 if (!var) return false;
8198 return considerVariable(var, ref, owner);
8199 }
8200
John McCall31168b02011-06-15 23:02:42 +00008201 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8202 if (member->isArrow()) return false;
8203
8204 // Don't count this as an indirect ownership.
8205 e = member->getBase();
8206 continue;
8207 }
8208
John McCallfe96e0b2011-11-06 09:01:30 +00008209 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8210 // Only pay attention to pseudo-objects on property references.
8211 ObjCPropertyRefExpr *pre
8212 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8213 ->IgnoreParens());
8214 if (!pre) return false;
8215 if (pre->isImplicitProperty()) return false;
8216 ObjCPropertyDecl *property = pre->getExplicitProperty();
8217 if (!property->isRetaining() &&
8218 !(property->getPropertyIvarDecl() &&
8219 property->getPropertyIvarDecl()->getType()
8220 .getObjCLifetime() == Qualifiers::OCL_Strong))
8221 return false;
8222
8223 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008224 if (pre->isSuperReceiver()) {
8225 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8226 if (!owner.Variable)
8227 return false;
8228 owner.Loc = pre->getLocation();
8229 owner.Range = pre->getSourceRange();
8230 return true;
8231 }
John McCallfe96e0b2011-11-06 09:01:30 +00008232 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8233 ->getSourceExpr());
8234 continue;
8235 }
8236
John McCall31168b02011-06-15 23:02:42 +00008237 // Array ivars?
8238
8239 return false;
8240 }
8241}
8242
8243namespace {
8244 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8245 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8246 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008247 Context(Context), Variable(variable), Capturer(nullptr),
8248 VarWillBeReased(false) {}
8249 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008250 VarDecl *Variable;
8251 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008252 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008253
8254 void VisitDeclRefExpr(DeclRefExpr *ref) {
8255 if (ref->getDecl() == Variable && !Capturer)
8256 Capturer = ref;
8257 }
8258
John McCall31168b02011-06-15 23:02:42 +00008259 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8260 if (Capturer) return;
8261 Visit(ref->getBase());
8262 if (Capturer && ref->isFreeIvar())
8263 Capturer = ref;
8264 }
8265
8266 void VisitBlockExpr(BlockExpr *block) {
8267 // Look inside nested blocks
8268 if (block->getBlockDecl()->capturesVariable(Variable))
8269 Visit(block->getBlockDecl()->getBody());
8270 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008271
8272 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8273 if (Capturer) return;
8274 if (OVE->getSourceExpr())
8275 Visit(OVE->getSourceExpr());
8276 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008277 void VisitBinaryOperator(BinaryOperator *BinOp) {
8278 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8279 return;
8280 Expr *LHS = BinOp->getLHS();
8281 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8282 if (DRE->getDecl() != Variable)
8283 return;
8284 if (Expr *RHS = BinOp->getRHS()) {
8285 RHS = RHS->IgnoreParenCasts();
8286 llvm::APSInt Value;
8287 VarWillBeReased =
8288 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8289 }
8290 }
8291 }
John McCall31168b02011-06-15 23:02:42 +00008292 };
8293}
8294
8295/// Check whether the given argument is a block which captures a
8296/// variable.
8297static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8298 assert(owner.Variable && owner.Loc.isValid());
8299
8300 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008301
8302 // Look through [^{...} copy] and Block_copy(^{...}).
8303 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8304 Selector Cmd = ME->getSelector();
8305 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8306 e = ME->getInstanceReceiver();
8307 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008308 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008309 e = e->IgnoreParenCasts();
8310 }
8311 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8312 if (CE->getNumArgs() == 1) {
8313 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008314 if (Fn) {
8315 const IdentifierInfo *FnI = Fn->getIdentifier();
8316 if (FnI && FnI->isStr("_Block_copy")) {
8317 e = CE->getArg(0)->IgnoreParenCasts();
8318 }
8319 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008320 }
8321 }
8322
John McCall31168b02011-06-15 23:02:42 +00008323 BlockExpr *block = dyn_cast<BlockExpr>(e);
8324 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008325 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008326
8327 FindCaptureVisitor visitor(S.Context, owner.Variable);
8328 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008329 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008330}
8331
8332static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8333 RetainCycleOwner &owner) {
8334 assert(capturer);
8335 assert(owner.Variable && owner.Loc.isValid());
8336
8337 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8338 << owner.Variable << capturer->getSourceRange();
8339 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8340 << owner.Indirect << owner.Range;
8341}
8342
8343/// Check for a keyword selector that starts with the word 'add' or
8344/// 'set'.
8345static bool isSetterLikeSelector(Selector sel) {
8346 if (sel.isUnarySelector()) return false;
8347
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008348 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008349 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008350 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008351 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008352 else if (str.startswith("add")) {
8353 // Specially whitelist 'addOperationWithBlock:'.
8354 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8355 return false;
8356 str = str.substr(3);
8357 }
John McCall31168b02011-06-15 23:02:42 +00008358 else
8359 return false;
8360
8361 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008362 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008363}
8364
Benjamin Kramer3a743452015-03-09 15:03:32 +00008365static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8366 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008367 if (S.NSMutableArrayPointer.isNull()) {
8368 IdentifierInfo *NSMutableArrayId =
8369 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8370 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8371 Message->getLocStart(),
8372 Sema::LookupOrdinaryName);
8373 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8374 if (!InterfaceDecl) {
8375 return None;
8376 }
8377 QualType NSMutableArrayObject =
8378 S.Context.getObjCInterfaceType(InterfaceDecl);
8379 S.NSMutableArrayPointer =
8380 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8381 }
8382
8383 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8384 return None;
8385 }
8386
8387 Selector Sel = Message->getSelector();
8388
8389 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8390 S.NSAPIObj->getNSArrayMethodKind(Sel);
8391 if (!MKOpt) {
8392 return None;
8393 }
8394
8395 NSAPI::NSArrayMethodKind MK = *MKOpt;
8396
8397 switch (MK) {
8398 case NSAPI::NSMutableArr_addObject:
8399 case NSAPI::NSMutableArr_insertObjectAtIndex:
8400 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8401 return 0;
8402 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8403 return 1;
8404
8405 default:
8406 return None;
8407 }
8408
8409 return None;
8410}
8411
8412static
8413Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8414 ObjCMessageExpr *Message) {
8415
8416 if (S.NSMutableDictionaryPointer.isNull()) {
8417 IdentifierInfo *NSMutableDictionaryId =
8418 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8419 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8420 Message->getLocStart(),
8421 Sema::LookupOrdinaryName);
8422 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8423 if (!InterfaceDecl) {
8424 return None;
8425 }
8426 QualType NSMutableDictionaryObject =
8427 S.Context.getObjCInterfaceType(InterfaceDecl);
8428 S.NSMutableDictionaryPointer =
8429 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8430 }
8431
8432 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8433 return None;
8434 }
8435
8436 Selector Sel = Message->getSelector();
8437
8438 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8439 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8440 if (!MKOpt) {
8441 return None;
8442 }
8443
8444 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8445
8446 switch (MK) {
8447 case NSAPI::NSMutableDict_setObjectForKey:
8448 case NSAPI::NSMutableDict_setValueForKey:
8449 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8450 return 0;
8451
8452 default:
8453 return None;
8454 }
8455
8456 return None;
8457}
8458
8459static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8460
8461 ObjCInterfaceDecl *InterfaceDecl;
8462 if (S.NSMutableSetPointer.isNull()) {
8463 IdentifierInfo *NSMutableSetId =
8464 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8465 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8466 Message->getLocStart(),
8467 Sema::LookupOrdinaryName);
8468 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8469 if (InterfaceDecl) {
8470 QualType NSMutableSetObject =
8471 S.Context.getObjCInterfaceType(InterfaceDecl);
8472 S.NSMutableSetPointer =
8473 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8474 }
8475 }
8476
8477 if (S.NSCountedSetPointer.isNull()) {
8478 IdentifierInfo *NSCountedSetId =
8479 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8480 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8481 Message->getLocStart(),
8482 Sema::LookupOrdinaryName);
8483 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8484 if (InterfaceDecl) {
8485 QualType NSCountedSetObject =
8486 S.Context.getObjCInterfaceType(InterfaceDecl);
8487 S.NSCountedSetPointer =
8488 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8489 }
8490 }
8491
8492 if (S.NSMutableOrderedSetPointer.isNull()) {
8493 IdentifierInfo *NSOrderedSetId =
8494 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8495 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8496 Message->getLocStart(),
8497 Sema::LookupOrdinaryName);
8498 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8499 if (InterfaceDecl) {
8500 QualType NSOrderedSetObject =
8501 S.Context.getObjCInterfaceType(InterfaceDecl);
8502 S.NSMutableOrderedSetPointer =
8503 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8504 }
8505 }
8506
8507 QualType ReceiverType = Message->getReceiverType();
8508
8509 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8510 ReceiverType == S.NSMutableSetPointer;
8511 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8512 ReceiverType == S.NSMutableOrderedSetPointer;
8513 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8514 ReceiverType == S.NSCountedSetPointer;
8515
8516 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8517 return None;
8518 }
8519
8520 Selector Sel = Message->getSelector();
8521
8522 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8523 if (!MKOpt) {
8524 return None;
8525 }
8526
8527 NSAPI::NSSetMethodKind MK = *MKOpt;
8528
8529 switch (MK) {
8530 case NSAPI::NSMutableSet_addObject:
8531 case NSAPI::NSOrderedSet_setObjectAtIndex:
8532 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8533 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8534 return 0;
8535 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8536 return 1;
8537 }
8538
8539 return None;
8540}
8541
8542void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8543 if (!Message->isInstanceMessage()) {
8544 return;
8545 }
8546
8547 Optional<int> ArgOpt;
8548
8549 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8550 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8551 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8552 return;
8553 }
8554
8555 int ArgIndex = *ArgOpt;
8556
8557 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8558 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8559 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8560 }
8561
8562 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8563 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8564 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8565 }
8566
8567 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8568 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8569 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8570 ValueDecl *Decl = ReceiverRE->getDecl();
8571 Diag(Message->getSourceRange().getBegin(),
8572 diag::warn_objc_circular_container)
8573 << Decl->getName();
8574 Diag(Decl->getLocation(),
8575 diag::note_objc_circular_container_declared_here)
8576 << Decl->getName();
8577 }
8578 }
8579 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8580 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8581 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8582 ObjCIvarDecl *Decl = IvarRE->getDecl();
8583 Diag(Message->getSourceRange().getBegin(),
8584 diag::warn_objc_circular_container)
8585 << Decl->getName();
8586 Diag(Decl->getLocation(),
8587 diag::note_objc_circular_container_declared_here)
8588 << Decl->getName();
8589 }
8590 }
8591 }
8592
8593}
8594
John McCall31168b02011-06-15 23:02:42 +00008595/// Check a message send to see if it's likely to cause a retain cycle.
8596void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8597 // Only check instance methods whose selector looks like a setter.
8598 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8599 return;
8600
8601 // Try to find a variable that the receiver is strongly owned by.
8602 RetainCycleOwner owner;
8603 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008604 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008605 return;
8606 } else {
8607 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8608 owner.Variable = getCurMethodDecl()->getSelfDecl();
8609 owner.Loc = msg->getSuperLoc();
8610 owner.Range = msg->getSuperLoc();
8611 }
8612
8613 // Check whether the receiver is captured by any of the arguments.
8614 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8615 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8616 return diagnoseRetainCycle(*this, capturer, owner);
8617}
8618
8619/// Check a property assign to see if it's likely to cause a retain cycle.
8620void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8621 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008622 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008623 return;
8624
8625 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8626 diagnoseRetainCycle(*this, capturer, owner);
8627}
8628
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008629void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8630 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008631 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008632 return;
8633
8634 // Because we don't have an expression for the variable, we have to set the
8635 // location explicitly here.
8636 Owner.Loc = Var->getLocation();
8637 Owner.Range = Var->getSourceRange();
8638
8639 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8640 diagnoseRetainCycle(*this, Capturer, Owner);
8641}
8642
Ted Kremenek9304da92012-12-21 08:04:28 +00008643static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8644 Expr *RHS, bool isProperty) {
8645 // Check if RHS is an Objective-C object literal, which also can get
8646 // immediately zapped in a weak reference. Note that we explicitly
8647 // allow ObjCStringLiterals, since those are designed to never really die.
8648 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008649
Ted Kremenek64873352012-12-21 22:46:35 +00008650 // This enum needs to match with the 'select' in
8651 // warn_objc_arc_literal_assign (off-by-1).
8652 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8653 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8654 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008655
8656 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008657 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008658 << (isProperty ? 0 : 1)
8659 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008660
8661 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008662}
8663
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008664static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8665 Qualifiers::ObjCLifetime LT,
8666 Expr *RHS, bool isProperty) {
8667 // Strip off any implicit cast added to get to the one ARC-specific.
8668 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8669 if (cast->getCastKind() == CK_ARCConsumeObject) {
8670 S.Diag(Loc, diag::warn_arc_retained_assign)
8671 << (LT == Qualifiers::OCL_ExplicitNone)
8672 << (isProperty ? 0 : 1)
8673 << RHS->getSourceRange();
8674 return true;
8675 }
8676 RHS = cast->getSubExpr();
8677 }
8678
8679 if (LT == Qualifiers::OCL_Weak &&
8680 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8681 return true;
8682
8683 return false;
8684}
8685
Ted Kremenekb36234d2012-12-21 08:04:20 +00008686bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8687 QualType LHS, Expr *RHS) {
8688 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8689
8690 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8691 return false;
8692
8693 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8694 return true;
8695
8696 return false;
8697}
8698
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008699void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8700 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008701 QualType LHSType;
8702 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008703 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008704 ObjCPropertyRefExpr *PRE
8705 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8706 if (PRE && !PRE->isImplicitProperty()) {
8707 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8708 if (PD)
8709 LHSType = PD->getType();
8710 }
8711
8712 if (LHSType.isNull())
8713 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008714
8715 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8716
8717 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008718 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008719 getCurFunction()->markSafeWeakUse(LHS);
8720 }
8721
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008722 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8723 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008724
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008725 // FIXME. Check for other life times.
8726 if (LT != Qualifiers::OCL_None)
8727 return;
8728
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008729 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008730 if (PRE->isImplicitProperty())
8731 return;
8732 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8733 if (!PD)
8734 return;
8735
Bill Wendling44426052012-12-20 19:22:21 +00008736 unsigned Attributes = PD->getPropertyAttributes();
8737 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008738 // when 'assign' attribute was not explicitly specified
8739 // by user, ignore it and rely on property type itself
8740 // for lifetime info.
8741 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8742 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8743 LHSType->isObjCRetainableType())
8744 return;
8745
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008746 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008747 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008748 Diag(Loc, diag::warn_arc_retained_property_assign)
8749 << RHS->getSourceRange();
8750 return;
8751 }
8752 RHS = cast->getSubExpr();
8753 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008754 }
Bill Wendling44426052012-12-20 19:22:21 +00008755 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008756 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8757 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008758 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008759 }
8760}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008761
8762//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8763
8764namespace {
8765bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8766 SourceLocation StmtLoc,
8767 const NullStmt *Body) {
8768 // Do not warn if the body is a macro that expands to nothing, e.g:
8769 //
8770 // #define CALL(x)
8771 // if (condition)
8772 // CALL(0);
8773 //
8774 if (Body->hasLeadingEmptyMacro())
8775 return false;
8776
8777 // Get line numbers of statement and body.
8778 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008779 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008780 &StmtLineInvalid);
8781 if (StmtLineInvalid)
8782 return false;
8783
8784 bool BodyLineInvalid;
8785 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8786 &BodyLineInvalid);
8787 if (BodyLineInvalid)
8788 return false;
8789
8790 // Warn if null statement and body are on the same line.
8791 if (StmtLine != BodyLine)
8792 return false;
8793
8794 return true;
8795}
8796} // Unnamed namespace
8797
8798void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8799 const Stmt *Body,
8800 unsigned DiagID) {
8801 // Since this is a syntactic check, don't emit diagnostic for template
8802 // instantiations, this just adds noise.
8803 if (CurrentInstantiationScope)
8804 return;
8805
8806 // The body should be a null statement.
8807 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8808 if (!NBody)
8809 return;
8810
8811 // Do the usual checks.
8812 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8813 return;
8814
8815 Diag(NBody->getSemiLoc(), DiagID);
8816 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8817}
8818
8819void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8820 const Stmt *PossibleBody) {
8821 assert(!CurrentInstantiationScope); // Ensured by caller
8822
8823 SourceLocation StmtLoc;
8824 const Stmt *Body;
8825 unsigned DiagID;
8826 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8827 StmtLoc = FS->getRParenLoc();
8828 Body = FS->getBody();
8829 DiagID = diag::warn_empty_for_body;
8830 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8831 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8832 Body = WS->getBody();
8833 DiagID = diag::warn_empty_while_body;
8834 } else
8835 return; // Neither `for' nor `while'.
8836
8837 // The body should be a null statement.
8838 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8839 if (!NBody)
8840 return;
8841
8842 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008843 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008844 return;
8845
8846 // Do the usual checks.
8847 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8848 return;
8849
8850 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8851 // noise level low, emit diagnostics only if for/while is followed by a
8852 // CompoundStmt, e.g.:
8853 // for (int i = 0; i < n; i++);
8854 // {
8855 // a(i);
8856 // }
8857 // or if for/while is followed by a statement with more indentation
8858 // than for/while itself:
8859 // for (int i = 0; i < n; i++);
8860 // a(i);
8861 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8862 if (!ProbableTypo) {
8863 bool BodyColInvalid;
8864 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8865 PossibleBody->getLocStart(),
8866 &BodyColInvalid);
8867 if (BodyColInvalid)
8868 return;
8869
8870 bool StmtColInvalid;
8871 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8872 S->getLocStart(),
8873 &StmtColInvalid);
8874 if (StmtColInvalid)
8875 return;
8876
8877 if (BodyCol > StmtCol)
8878 ProbableTypo = true;
8879 }
8880
8881 if (ProbableTypo) {
8882 Diag(NBody->getSemiLoc(), DiagID);
8883 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8884 }
8885}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008886
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008887//===--- CHECK: Warn on self move with std::move. -------------------------===//
8888
8889/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8890void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8891 SourceLocation OpLoc) {
8892
8893 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8894 return;
8895
8896 if (!ActiveTemplateInstantiations.empty())
8897 return;
8898
8899 // Strip parens and casts away.
8900 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8901 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8902
8903 // Check for a call expression
8904 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8905 if (!CE || CE->getNumArgs() != 1)
8906 return;
8907
8908 // Check for a call to std::move
8909 const FunctionDecl *FD = CE->getDirectCallee();
8910 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8911 !FD->getIdentifier()->isStr("move"))
8912 return;
8913
8914 // Get argument from std::move
8915 RHSExpr = CE->getArg(0);
8916
8917 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8918 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8919
8920 // Two DeclRefExpr's, check that the decls are the same.
8921 if (LHSDeclRef && RHSDeclRef) {
8922 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8923 return;
8924 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8925 RHSDeclRef->getDecl()->getCanonicalDecl())
8926 return;
8927
8928 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8929 << LHSExpr->getSourceRange()
8930 << RHSExpr->getSourceRange();
8931 return;
8932 }
8933
8934 // Member variables require a different approach to check for self moves.
8935 // MemberExpr's are the same if every nested MemberExpr refers to the same
8936 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8937 // the base Expr's are CXXThisExpr's.
8938 const Expr *LHSBase = LHSExpr;
8939 const Expr *RHSBase = RHSExpr;
8940 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8941 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8942 if (!LHSME || !RHSME)
8943 return;
8944
8945 while (LHSME && RHSME) {
8946 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8947 RHSME->getMemberDecl()->getCanonicalDecl())
8948 return;
8949
8950 LHSBase = LHSME->getBase();
8951 RHSBase = RHSME->getBase();
8952 LHSME = dyn_cast<MemberExpr>(LHSBase);
8953 RHSME = dyn_cast<MemberExpr>(RHSBase);
8954 }
8955
8956 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8957 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8958 if (LHSDeclRef && RHSDeclRef) {
8959 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8960 return;
8961 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8962 RHSDeclRef->getDecl()->getCanonicalDecl())
8963 return;
8964
8965 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8966 << LHSExpr->getSourceRange()
8967 << RHSExpr->getSourceRange();
8968 return;
8969 }
8970
8971 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8972 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8973 << LHSExpr->getSourceRange()
8974 << RHSExpr->getSourceRange();
8975}
8976
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008977//===--- Layout compatibility ----------------------------------------------//
8978
8979namespace {
8980
8981bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8982
8983/// \brief Check if two enumeration types are layout-compatible.
8984bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8985 // C++11 [dcl.enum] p8:
8986 // Two enumeration types are layout-compatible if they have the same
8987 // underlying type.
8988 return ED1->isComplete() && ED2->isComplete() &&
8989 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8990}
8991
8992/// \brief Check if two fields are layout-compatible.
8993bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8994 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8995 return false;
8996
8997 if (Field1->isBitField() != Field2->isBitField())
8998 return false;
8999
9000 if (Field1->isBitField()) {
9001 // Make sure that the bit-fields are the same length.
9002 unsigned Bits1 = Field1->getBitWidthValue(C);
9003 unsigned Bits2 = Field2->getBitWidthValue(C);
9004
9005 if (Bits1 != Bits2)
9006 return false;
9007 }
9008
9009 return true;
9010}
9011
9012/// \brief Check if two standard-layout structs are layout-compatible.
9013/// (C++11 [class.mem] p17)
9014bool isLayoutCompatibleStruct(ASTContext &C,
9015 RecordDecl *RD1,
9016 RecordDecl *RD2) {
9017 // If both records are C++ classes, check that base classes match.
9018 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9019 // If one of records is a CXXRecordDecl we are in C++ mode,
9020 // thus the other one is a CXXRecordDecl, too.
9021 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9022 // Check number of base classes.
9023 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9024 return false;
9025
9026 // Check the base classes.
9027 for (CXXRecordDecl::base_class_const_iterator
9028 Base1 = D1CXX->bases_begin(),
9029 BaseEnd1 = D1CXX->bases_end(),
9030 Base2 = D2CXX->bases_begin();
9031 Base1 != BaseEnd1;
9032 ++Base1, ++Base2) {
9033 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9034 return false;
9035 }
9036 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9037 // If only RD2 is a C++ class, it should have zero base classes.
9038 if (D2CXX->getNumBases() > 0)
9039 return false;
9040 }
9041
9042 // Check the fields.
9043 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9044 Field2End = RD2->field_end(),
9045 Field1 = RD1->field_begin(),
9046 Field1End = RD1->field_end();
9047 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9048 if (!isLayoutCompatible(C, *Field1, *Field2))
9049 return false;
9050 }
9051 if (Field1 != Field1End || Field2 != Field2End)
9052 return false;
9053
9054 return true;
9055}
9056
9057/// \brief Check if two standard-layout unions are layout-compatible.
9058/// (C++11 [class.mem] p18)
9059bool isLayoutCompatibleUnion(ASTContext &C,
9060 RecordDecl *RD1,
9061 RecordDecl *RD2) {
9062 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009063 for (auto *Field2 : RD2->fields())
9064 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009065
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009066 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009067 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9068 I = UnmatchedFields.begin(),
9069 E = UnmatchedFields.end();
9070
9071 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009072 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009073 bool Result = UnmatchedFields.erase(*I);
9074 (void) Result;
9075 assert(Result);
9076 break;
9077 }
9078 }
9079 if (I == E)
9080 return false;
9081 }
9082
9083 return UnmatchedFields.empty();
9084}
9085
9086bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9087 if (RD1->isUnion() != RD2->isUnion())
9088 return false;
9089
9090 if (RD1->isUnion())
9091 return isLayoutCompatibleUnion(C, RD1, RD2);
9092 else
9093 return isLayoutCompatibleStruct(C, RD1, RD2);
9094}
9095
9096/// \brief Check if two types are layout-compatible in C++11 sense.
9097bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9098 if (T1.isNull() || T2.isNull())
9099 return false;
9100
9101 // C++11 [basic.types] p11:
9102 // If two types T1 and T2 are the same type, then T1 and T2 are
9103 // layout-compatible types.
9104 if (C.hasSameType(T1, T2))
9105 return true;
9106
9107 T1 = T1.getCanonicalType().getUnqualifiedType();
9108 T2 = T2.getCanonicalType().getUnqualifiedType();
9109
9110 const Type::TypeClass TC1 = T1->getTypeClass();
9111 const Type::TypeClass TC2 = T2->getTypeClass();
9112
9113 if (TC1 != TC2)
9114 return false;
9115
9116 if (TC1 == Type::Enum) {
9117 return isLayoutCompatible(C,
9118 cast<EnumType>(T1)->getDecl(),
9119 cast<EnumType>(T2)->getDecl());
9120 } else if (TC1 == Type::Record) {
9121 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9122 return false;
9123
9124 return isLayoutCompatible(C,
9125 cast<RecordType>(T1)->getDecl(),
9126 cast<RecordType>(T2)->getDecl());
9127 }
9128
9129 return false;
9130}
9131}
9132
9133//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9134
9135namespace {
9136/// \brief Given a type tag expression find the type tag itself.
9137///
9138/// \param TypeExpr Type tag expression, as it appears in user's code.
9139///
9140/// \param VD Declaration of an identifier that appears in a type tag.
9141///
9142/// \param MagicValue Type tag magic value.
9143bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9144 const ValueDecl **VD, uint64_t *MagicValue) {
9145 while(true) {
9146 if (!TypeExpr)
9147 return false;
9148
9149 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9150
9151 switch (TypeExpr->getStmtClass()) {
9152 case Stmt::UnaryOperatorClass: {
9153 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9154 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9155 TypeExpr = UO->getSubExpr();
9156 continue;
9157 }
9158 return false;
9159 }
9160
9161 case Stmt::DeclRefExprClass: {
9162 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9163 *VD = DRE->getDecl();
9164 return true;
9165 }
9166
9167 case Stmt::IntegerLiteralClass: {
9168 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9169 llvm::APInt MagicValueAPInt = IL->getValue();
9170 if (MagicValueAPInt.getActiveBits() <= 64) {
9171 *MagicValue = MagicValueAPInt.getZExtValue();
9172 return true;
9173 } else
9174 return false;
9175 }
9176
9177 case Stmt::BinaryConditionalOperatorClass:
9178 case Stmt::ConditionalOperatorClass: {
9179 const AbstractConditionalOperator *ACO =
9180 cast<AbstractConditionalOperator>(TypeExpr);
9181 bool Result;
9182 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9183 if (Result)
9184 TypeExpr = ACO->getTrueExpr();
9185 else
9186 TypeExpr = ACO->getFalseExpr();
9187 continue;
9188 }
9189 return false;
9190 }
9191
9192 case Stmt::BinaryOperatorClass: {
9193 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9194 if (BO->getOpcode() == BO_Comma) {
9195 TypeExpr = BO->getRHS();
9196 continue;
9197 }
9198 return false;
9199 }
9200
9201 default:
9202 return false;
9203 }
9204 }
9205}
9206
9207/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9208///
9209/// \param TypeExpr Expression that specifies a type tag.
9210///
9211/// \param MagicValues Registered magic values.
9212///
9213/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9214/// kind.
9215///
9216/// \param TypeInfo Information about the corresponding C type.
9217///
9218/// \returns true if the corresponding C type was found.
9219bool GetMatchingCType(
9220 const IdentifierInfo *ArgumentKind,
9221 const Expr *TypeExpr, const ASTContext &Ctx,
9222 const llvm::DenseMap<Sema::TypeTagMagicValue,
9223 Sema::TypeTagData> *MagicValues,
9224 bool &FoundWrongKind,
9225 Sema::TypeTagData &TypeInfo) {
9226 FoundWrongKind = false;
9227
9228 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009229 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009230
9231 uint64_t MagicValue;
9232
9233 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9234 return false;
9235
9236 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009237 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009238 if (I->getArgumentKind() != ArgumentKind) {
9239 FoundWrongKind = true;
9240 return false;
9241 }
9242 TypeInfo.Type = I->getMatchingCType();
9243 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9244 TypeInfo.MustBeNull = I->getMustBeNull();
9245 return true;
9246 }
9247 return false;
9248 }
9249
9250 if (!MagicValues)
9251 return false;
9252
9253 llvm::DenseMap<Sema::TypeTagMagicValue,
9254 Sema::TypeTagData>::const_iterator I =
9255 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9256 if (I == MagicValues->end())
9257 return false;
9258
9259 TypeInfo = I->second;
9260 return true;
9261}
9262} // unnamed namespace
9263
9264void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9265 uint64_t MagicValue, QualType Type,
9266 bool LayoutCompatible,
9267 bool MustBeNull) {
9268 if (!TypeTagForDatatypeMagicValues)
9269 TypeTagForDatatypeMagicValues.reset(
9270 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9271
9272 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9273 (*TypeTagForDatatypeMagicValues)[Magic] =
9274 TypeTagData(Type, LayoutCompatible, MustBeNull);
9275}
9276
9277namespace {
9278bool IsSameCharType(QualType T1, QualType T2) {
9279 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9280 if (!BT1)
9281 return false;
9282
9283 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9284 if (!BT2)
9285 return false;
9286
9287 BuiltinType::Kind T1Kind = BT1->getKind();
9288 BuiltinType::Kind T2Kind = BT2->getKind();
9289
9290 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9291 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9292 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9293 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9294}
9295} // unnamed namespace
9296
9297void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9298 const Expr * const *ExprArgs) {
9299 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9300 bool IsPointerAttr = Attr->getIsPointer();
9301
9302 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9303 bool FoundWrongKind;
9304 TypeTagData TypeInfo;
9305 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9306 TypeTagForDatatypeMagicValues.get(),
9307 FoundWrongKind, TypeInfo)) {
9308 if (FoundWrongKind)
9309 Diag(TypeTagExpr->getExprLoc(),
9310 diag::warn_type_tag_for_datatype_wrong_kind)
9311 << TypeTagExpr->getSourceRange();
9312 return;
9313 }
9314
9315 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9316 if (IsPointerAttr) {
9317 // Skip implicit cast of pointer to `void *' (as a function argument).
9318 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009319 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009320 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009321 ArgumentExpr = ICE->getSubExpr();
9322 }
9323 QualType ArgumentType = ArgumentExpr->getType();
9324
9325 // Passing a `void*' pointer shouldn't trigger a warning.
9326 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9327 return;
9328
9329 if (TypeInfo.MustBeNull) {
9330 // Type tag with matching void type requires a null pointer.
9331 if (!ArgumentExpr->isNullPointerConstant(Context,
9332 Expr::NPC_ValueDependentIsNotNull)) {
9333 Diag(ArgumentExpr->getExprLoc(),
9334 diag::warn_type_safety_null_pointer_required)
9335 << ArgumentKind->getName()
9336 << ArgumentExpr->getSourceRange()
9337 << TypeTagExpr->getSourceRange();
9338 }
9339 return;
9340 }
9341
9342 QualType RequiredType = TypeInfo.Type;
9343 if (IsPointerAttr)
9344 RequiredType = Context.getPointerType(RequiredType);
9345
9346 bool mismatch = false;
9347 if (!TypeInfo.LayoutCompatible) {
9348 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9349
9350 // C++11 [basic.fundamental] p1:
9351 // Plain char, signed char, and unsigned char are three distinct types.
9352 //
9353 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9354 // char' depending on the current char signedness mode.
9355 if (mismatch)
9356 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9357 RequiredType->getPointeeType())) ||
9358 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9359 mismatch = false;
9360 } else
9361 if (IsPointerAttr)
9362 mismatch = !isLayoutCompatible(Context,
9363 ArgumentType->getPointeeType(),
9364 RequiredType->getPointeeType());
9365 else
9366 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9367
9368 if (mismatch)
9369 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009370 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009371 << TypeInfo.LayoutCompatible << RequiredType
9372 << ArgumentExpr->getSourceRange()
9373 << TypeTagExpr->getSourceRange();
9374}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009375