blob: 5eafa503486e39205c959df6f8498e0980a35e75 [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;
John McCallbebede42011-02-26 05:39:39 +0000326
327 case Builtin::BI__builtin_classify_type:
328 if (checkArgCount(*this, TheCall, 1)) return true;
329 TheCall->setType(Context.IntTy);
330 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000331 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000332 if (checkArgCount(*this, TheCall, 1)) return true;
333 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000334 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000335 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000336 case Builtin::BI__sync_fetch_and_add_1:
337 case Builtin::BI__sync_fetch_and_add_2:
338 case Builtin::BI__sync_fetch_and_add_4:
339 case Builtin::BI__sync_fetch_and_add_8:
340 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000341 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000342 case Builtin::BI__sync_fetch_and_sub_1:
343 case Builtin::BI__sync_fetch_and_sub_2:
344 case Builtin::BI__sync_fetch_and_sub_4:
345 case Builtin::BI__sync_fetch_and_sub_8:
346 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000347 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000348 case Builtin::BI__sync_fetch_and_or_1:
349 case Builtin::BI__sync_fetch_and_or_2:
350 case Builtin::BI__sync_fetch_and_or_4:
351 case Builtin::BI__sync_fetch_and_or_8:
352 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000353 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000354 case Builtin::BI__sync_fetch_and_and_1:
355 case Builtin::BI__sync_fetch_and_and_2:
356 case Builtin::BI__sync_fetch_and_and_4:
357 case Builtin::BI__sync_fetch_and_and_8:
358 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000359 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000360 case Builtin::BI__sync_fetch_and_xor_1:
361 case Builtin::BI__sync_fetch_and_xor_2:
362 case Builtin::BI__sync_fetch_and_xor_4:
363 case Builtin::BI__sync_fetch_and_xor_8:
364 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000365 case Builtin::BI__sync_fetch_and_nand:
366 case Builtin::BI__sync_fetch_and_nand_1:
367 case Builtin::BI__sync_fetch_and_nand_2:
368 case Builtin::BI__sync_fetch_and_nand_4:
369 case Builtin::BI__sync_fetch_and_nand_8:
370 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000371 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000372 case Builtin::BI__sync_add_and_fetch_1:
373 case Builtin::BI__sync_add_and_fetch_2:
374 case Builtin::BI__sync_add_and_fetch_4:
375 case Builtin::BI__sync_add_and_fetch_8:
376 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000377 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000378 case Builtin::BI__sync_sub_and_fetch_1:
379 case Builtin::BI__sync_sub_and_fetch_2:
380 case Builtin::BI__sync_sub_and_fetch_4:
381 case Builtin::BI__sync_sub_and_fetch_8:
382 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000383 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000384 case Builtin::BI__sync_and_and_fetch_1:
385 case Builtin::BI__sync_and_and_fetch_2:
386 case Builtin::BI__sync_and_and_fetch_4:
387 case Builtin::BI__sync_and_and_fetch_8:
388 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000389 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000390 case Builtin::BI__sync_or_and_fetch_1:
391 case Builtin::BI__sync_or_and_fetch_2:
392 case Builtin::BI__sync_or_and_fetch_4:
393 case Builtin::BI__sync_or_and_fetch_8:
394 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000395 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000396 case Builtin::BI__sync_xor_and_fetch_1:
397 case Builtin::BI__sync_xor_and_fetch_2:
398 case Builtin::BI__sync_xor_and_fetch_4:
399 case Builtin::BI__sync_xor_and_fetch_8:
400 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000401 case Builtin::BI__sync_nand_and_fetch:
402 case Builtin::BI__sync_nand_and_fetch_1:
403 case Builtin::BI__sync_nand_and_fetch_2:
404 case Builtin::BI__sync_nand_and_fetch_4:
405 case Builtin::BI__sync_nand_and_fetch_8:
406 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000407 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000408 case Builtin::BI__sync_val_compare_and_swap_1:
409 case Builtin::BI__sync_val_compare_and_swap_2:
410 case Builtin::BI__sync_val_compare_and_swap_4:
411 case Builtin::BI__sync_val_compare_and_swap_8:
412 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000413 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000414 case Builtin::BI__sync_bool_compare_and_swap_1:
415 case Builtin::BI__sync_bool_compare_and_swap_2:
416 case Builtin::BI__sync_bool_compare_and_swap_4:
417 case Builtin::BI__sync_bool_compare_and_swap_8:
418 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000419 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000420 case Builtin::BI__sync_lock_test_and_set_1:
421 case Builtin::BI__sync_lock_test_and_set_2:
422 case Builtin::BI__sync_lock_test_and_set_4:
423 case Builtin::BI__sync_lock_test_and_set_8:
424 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000425 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000426 case Builtin::BI__sync_lock_release_1:
427 case Builtin::BI__sync_lock_release_2:
428 case Builtin::BI__sync_lock_release_4:
429 case Builtin::BI__sync_lock_release_8:
430 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000431 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000432 case Builtin::BI__sync_swap_1:
433 case Builtin::BI__sync_swap_2:
434 case Builtin::BI__sync_swap_4:
435 case Builtin::BI__sync_swap_8:
436 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000437 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000438#define BUILTIN(ID, TYPE, ATTRS)
439#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
440 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000441 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000442#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000443 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000444 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000445 return ExprError();
446 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000447 case Builtin::BI__builtin_addressof:
448 if (SemaBuiltinAddressof(*this, TheCall))
449 return ExprError();
450 break;
Richard Smith760520b2014-06-03 23:27:44 +0000451 case Builtin::BI__builtin_operator_new:
452 case Builtin::BI__builtin_operator_delete:
453 if (!getLangOpts().CPlusPlus) {
454 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
455 << (BuiltinID == Builtin::BI__builtin_operator_new
456 ? "__builtin_operator_new"
457 : "__builtin_operator_delete")
458 << "C++";
459 return ExprError();
460 }
461 // CodeGen assumes it can find the global new and delete to call,
462 // so ensure that they are declared.
463 DeclareGlobalNewDelete();
464 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000465
466 // check secure string manipulation functions where overflows
467 // are detectable at compile time
468 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000469 case Builtin::BI__builtin___memmove_chk:
470 case Builtin::BI__builtin___memset_chk:
471 case Builtin::BI__builtin___strlcat_chk:
472 case Builtin::BI__builtin___strlcpy_chk:
473 case Builtin::BI__builtin___strncat_chk:
474 case Builtin::BI__builtin___strncpy_chk:
475 case Builtin::BI__builtin___stpncpy_chk:
476 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
477 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000478 case Builtin::BI__builtin___memccpy_chk:
479 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
480 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000481 case Builtin::BI__builtin___snprintf_chk:
482 case Builtin::BI__builtin___vsnprintf_chk:
483 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
484 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000485
486 case Builtin::BI__builtin_call_with_static_chain:
487 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
488 return ExprError();
489 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000490
491 case Builtin::BI__exception_code:
492 case Builtin::BI_exception_code: {
493 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
494 diag::err_seh___except_block))
495 return ExprError();
496 break;
497 }
498 case Builtin::BI__exception_info:
499 case Builtin::BI_exception_info: {
500 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
501 diag::err_seh___except_filter))
502 return ExprError();
503 break;
504 }
505
David Majnemerba3e5ec2015-03-13 18:26:17 +0000506 case Builtin::BI__GetExceptionInfo:
507 if (checkArgCount(*this, TheCall, 1))
508 return ExprError();
509
510 if (CheckCXXThrowOperand(
511 TheCall->getLocStart(),
512 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
513 TheCall))
514 return ExprError();
515
516 TheCall->setType(Context.VoidPtrTy);
517 break;
518
Nate Begeman4904e322010-06-08 02:47:44 +0000519 }
Richard Smith760520b2014-06-03 23:27:44 +0000520
Nate Begeman4904e322010-06-08 02:47:44 +0000521 // Since the target specific builtins for each arch overlap, only check those
522 // of the arch we are compiling for.
523 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000524 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000525 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000526 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000527 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000528 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000529 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
530 return ExprError();
531 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000532 case llvm::Triple::aarch64:
533 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000534 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000535 return ExprError();
536 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000537 case llvm::Triple::mips:
538 case llvm::Triple::mipsel:
539 case llvm::Triple::mips64:
540 case llvm::Triple::mips64el:
541 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
542 return ExprError();
543 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000544 case llvm::Triple::x86:
545 case llvm::Triple::x86_64:
546 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000549 default:
550 break;
551 }
552 }
553
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000554 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000555}
556
Nate Begeman91e1fea2010-06-14 05:21:25 +0000557// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000558static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000559 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000560 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000561 switch (Type.getEltType()) {
562 case NeonTypeFlags::Int8:
563 case NeonTypeFlags::Poly8:
564 return shift ? 7 : (8 << IsQuad) - 1;
565 case NeonTypeFlags::Int16:
566 case NeonTypeFlags::Poly16:
567 return shift ? 15 : (4 << IsQuad) - 1;
568 case NeonTypeFlags::Int32:
569 return shift ? 31 : (2 << IsQuad) - 1;
570 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000571 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000572 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000573 case NeonTypeFlags::Poly128:
574 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000575 case NeonTypeFlags::Float16:
576 assert(!shift && "cannot shift float types!");
577 return (4 << IsQuad) - 1;
578 case NeonTypeFlags::Float32:
579 assert(!shift && "cannot shift float types!");
580 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000581 case NeonTypeFlags::Float64:
582 assert(!shift && "cannot shift float types!");
583 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000584 }
David Blaikie8a40f702012-01-17 06:56:22 +0000585 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000586}
587
Bob Wilsone4d77232011-11-08 05:04:11 +0000588/// getNeonEltType - Return the QualType corresponding to the elements of
589/// the vector type specified by the NeonTypeFlags. This is used to check
590/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000591static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000592 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000593 switch (Flags.getEltType()) {
594 case NeonTypeFlags::Int8:
595 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
596 case NeonTypeFlags::Int16:
597 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
598 case NeonTypeFlags::Int32:
599 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
600 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000601 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000602 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
603 else
604 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
605 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000606 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000607 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000608 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000609 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000610 case NeonTypeFlags::Poly64:
Kevin Qinad64f6d2014-02-24 02:45:03 +0000611 return Context.UnsignedLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000612 case NeonTypeFlags::Poly128:
613 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000614 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000615 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000616 case NeonTypeFlags::Float32:
617 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000618 case NeonTypeFlags::Float64:
619 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000620 }
David Blaikie8a40f702012-01-17 06:56:22 +0000621 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000622}
623
Tim Northover12670412014-02-19 10:37:05 +0000624bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000625 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000626 uint64_t mask = 0;
627 unsigned TV = 0;
628 int PtrArgNum = -1;
629 bool HasConstPtr = false;
630 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000631#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000632#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000633#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000634 }
635
636 // For NEON intrinsics which are overloaded on vector element type, validate
637 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000638 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000639 if (mask) {
640 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
641 return true;
642
643 TV = Result.getLimitedValue(64);
644 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
645 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000646 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000647 }
648
649 if (PtrArgNum >= 0) {
650 // Check that pointer arguments have the specified type.
651 Expr *Arg = TheCall->getArg(PtrArgNum);
652 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
653 Arg = ICE->getSubExpr();
654 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
655 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000656
Tim Northovera2ee4332014-03-29 15:09:45 +0000657 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000658 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000659 bool IsInt64Long =
660 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
661 QualType EltTy =
662 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000663 if (HasConstPtr)
664 EltTy = EltTy.withConst();
665 QualType LHSTy = Context.getPointerType(EltTy);
666 AssignConvertType ConvTy;
667 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
668 if (RHS.isInvalid())
669 return true;
670 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
671 RHS.get(), AA_Assigning))
672 return true;
673 }
674
675 // For NEON intrinsics which take an immediate value as part of the
676 // instruction, range check them here.
677 unsigned i = 0, l = 0, u = 0;
678 switch (BuiltinID) {
679 default:
680 return false;
Tim Northover12670412014-02-19 10:37:05 +0000681#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000682#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000683#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000684 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000685
Richard Sandiford28940af2014-04-16 08:47:51 +0000686 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000687}
688
Tim Northovera2ee4332014-03-29 15:09:45 +0000689bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
690 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000691 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000692 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000693 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000694 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000695 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000696 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
697 BuiltinID == AArch64::BI__builtin_arm_strex ||
698 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000699 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000700 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000701 BuiltinID == ARM::BI__builtin_arm_ldaex ||
702 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
703 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000704
705 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
706
707 // Ensure that we have the proper number of arguments.
708 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
709 return true;
710
711 // Inspect the pointer argument of the atomic builtin. This should always be
712 // a pointer type, whose element is an integral scalar or pointer type.
713 // Because it is a pointer type, we don't have to worry about any implicit
714 // casts here.
715 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
716 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
717 if (PointerArgRes.isInvalid())
718 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000719 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000720
721 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
722 if (!pointerType) {
723 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
724 << PointerArg->getType() << PointerArg->getSourceRange();
725 return true;
726 }
727
728 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
729 // task is to insert the appropriate casts into the AST. First work out just
730 // what the appropriate type is.
731 QualType ValType = pointerType->getPointeeType();
732 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
733 if (IsLdrex)
734 AddrType.addConst();
735
736 // Issue a warning if the cast is dodgy.
737 CastKind CastNeeded = CK_NoOp;
738 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
739 CastNeeded = CK_BitCast;
740 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
741 << PointerArg->getType()
742 << Context.getPointerType(AddrType)
743 << AA_Passing << PointerArg->getSourceRange();
744 }
745
746 // Finally, do the cast and replace the argument with the corrected version.
747 AddrType = Context.getPointerType(AddrType);
748 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
749 if (PointerArgRes.isInvalid())
750 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000751 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000752
753 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
754
755 // In general, we allow ints, floats and pointers to be loaded and stored.
756 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
757 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
758 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
759 << PointerArg->getType() << PointerArg->getSourceRange();
760 return true;
761 }
762
763 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000764 if (Context.getTypeSize(ValType) > MaxWidth) {
765 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000766 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
767 << PointerArg->getType() << PointerArg->getSourceRange();
768 return true;
769 }
770
771 switch (ValType.getObjCLifetime()) {
772 case Qualifiers::OCL_None:
773 case Qualifiers::OCL_ExplicitNone:
774 // okay
775 break;
776
777 case Qualifiers::OCL_Weak:
778 case Qualifiers::OCL_Strong:
779 case Qualifiers::OCL_Autoreleasing:
780 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
781 << ValType << PointerArg->getSourceRange();
782 return true;
783 }
784
785
786 if (IsLdrex) {
787 TheCall->setType(ValType);
788 return false;
789 }
790
791 // Initialize the argument to be stored.
792 ExprResult ValArg = TheCall->getArg(0);
793 InitializedEntity Entity = InitializedEntity::InitializeParameter(
794 Context, ValType, /*consume*/ false);
795 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
796 if (ValArg.isInvalid())
797 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000798 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000799
800 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
801 // but the custom checker bypasses all default analysis.
802 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000803 return false;
804}
805
Nate Begeman4904e322010-06-08 02:47:44 +0000806bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000807 llvm::APSInt Result;
808
Tim Northover6aacd492013-07-16 09:47:53 +0000809 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000810 BuiltinID == ARM::BI__builtin_arm_ldaex ||
811 BuiltinID == ARM::BI__builtin_arm_strex ||
812 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000813 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000814 }
815
Yi Kong26d104a2014-08-13 19:18:14 +0000816 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
817 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
818 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
819 }
820
Tim Northover12670412014-02-19 10:37:05 +0000821 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
822 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000823
Yi Kong4efadfb2014-07-03 16:01:25 +0000824 // For intrinsics which take an immediate value as part of the instruction,
825 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000826 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000827 switch (BuiltinID) {
828 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000829 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
830 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000831 case ARM::BI__builtin_arm_vcvtr_f:
832 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000833 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000834 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000835 case ARM::BI__builtin_arm_isb:
836 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000837 }
Nate Begemand773fe62010-06-13 04:47:52 +0000838
Nate Begemanf568b072010-08-03 21:32:34 +0000839 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000840 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000841}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000842
Tim Northover573cbee2014-05-24 12:52:07 +0000843bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000844 CallExpr *TheCall) {
845 llvm::APSInt Result;
846
Tim Northover573cbee2014-05-24 12:52:07 +0000847 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000848 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
849 BuiltinID == AArch64::BI__builtin_arm_strex ||
850 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000851 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
852 }
853
Yi Konga5548432014-08-13 19:18:20 +0000854 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
855 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
856 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
857 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
858 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
859 }
860
Tim Northovera2ee4332014-03-29 15:09:45 +0000861 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
862 return true;
863
Yi Kong19a29ac2014-07-17 10:52:06 +0000864 // For intrinsics which take an immediate value as part of the instruction,
865 // range check them here.
866 unsigned i = 0, l = 0, u = 0;
867 switch (BuiltinID) {
868 default: return false;
869 case AArch64::BI__builtin_arm_dmb:
870 case AArch64::BI__builtin_arm_dsb:
871 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
872 }
873
Yi Kong19a29ac2014-07-17 10:52:06 +0000874 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000875}
876
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000877bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
878 unsigned i = 0, l = 0, u = 0;
879 switch (BuiltinID) {
880 default: return false;
881 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
882 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000883 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
884 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
885 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
886 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
887 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000888 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000889
Richard Sandiford28940af2014-04-16 08:47:51 +0000890 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000891}
892
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000893bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000894 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000895 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +0000896 default: return false;
897 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +0000898 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +0000899 case X86::BI__builtin_ia32_vpermil2pd:
900 case X86::BI__builtin_ia32_vpermil2pd256:
901 case X86::BI__builtin_ia32_vpermil2ps:
902 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +0000903 case X86::BI__builtin_ia32_cmpb128_mask:
904 case X86::BI__builtin_ia32_cmpw128_mask:
905 case X86::BI__builtin_ia32_cmpd128_mask:
906 case X86::BI__builtin_ia32_cmpq128_mask:
907 case X86::BI__builtin_ia32_cmpb256_mask:
908 case X86::BI__builtin_ia32_cmpw256_mask:
909 case X86::BI__builtin_ia32_cmpd256_mask:
910 case X86::BI__builtin_ia32_cmpq256_mask:
911 case X86::BI__builtin_ia32_cmpb512_mask:
912 case X86::BI__builtin_ia32_cmpw512_mask:
913 case X86::BI__builtin_ia32_cmpd512_mask:
914 case X86::BI__builtin_ia32_cmpq512_mask:
915 case X86::BI__builtin_ia32_ucmpb128_mask:
916 case X86::BI__builtin_ia32_ucmpw128_mask:
917 case X86::BI__builtin_ia32_ucmpd128_mask:
918 case X86::BI__builtin_ia32_ucmpq128_mask:
919 case X86::BI__builtin_ia32_ucmpb256_mask:
920 case X86::BI__builtin_ia32_ucmpw256_mask:
921 case X86::BI__builtin_ia32_ucmpd256_mask:
922 case X86::BI__builtin_ia32_ucmpq256_mask:
923 case X86::BI__builtin_ia32_ucmpb512_mask:
924 case X86::BI__builtin_ia32_ucmpw512_mask:
925 case X86::BI__builtin_ia32_ucmpd512_mask:
926 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +0000927 case X86::BI__builtin_ia32_roundps:
928 case X86::BI__builtin_ia32_roundpd:
929 case X86::BI__builtin_ia32_roundps256:
930 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
931 case X86::BI__builtin_ia32_roundss:
932 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
933 case X86::BI__builtin_ia32_cmpps:
934 case X86::BI__builtin_ia32_cmpss:
935 case X86::BI__builtin_ia32_cmppd:
936 case X86::BI__builtin_ia32_cmpsd:
937 case X86::BI__builtin_ia32_cmpps256:
938 case X86::BI__builtin_ia32_cmppd256:
939 case X86::BI__builtin_ia32_cmpps512_mask:
940 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +0000941 case X86::BI__builtin_ia32_vpcomub:
942 case X86::BI__builtin_ia32_vpcomuw:
943 case X86::BI__builtin_ia32_vpcomud:
944 case X86::BI__builtin_ia32_vpcomuq:
945 case X86::BI__builtin_ia32_vpcomb:
946 case X86::BI__builtin_ia32_vpcomw:
947 case X86::BI__builtin_ia32_vpcomd:
948 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000949 }
Craig Topperdd84ec52014-12-27 07:00:08 +0000950 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000951}
952
Richard Smith55ce3522012-06-25 20:30:08 +0000953/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
954/// parameter with the FormatAttr's correct format_idx and firstDataArg.
955/// Returns true when the format fits the function and the FormatStringInfo has
956/// been populated.
957bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
958 FormatStringInfo *FSI) {
959 FSI->HasVAListArg = Format->getFirstArg() == 0;
960 FSI->FormatIdx = Format->getFormatIdx() - 1;
961 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000962
Richard Smith55ce3522012-06-25 20:30:08 +0000963 // The way the format attribute works in GCC, the implicit this argument
964 // of member functions is counted. However, it doesn't appear in our own
965 // lists, so decrement format_idx in that case.
966 if (IsCXXMember) {
967 if(FSI->FormatIdx == 0)
968 return false;
969 --FSI->FormatIdx;
970 if (FSI->FirstDataArg != 0)
971 --FSI->FirstDataArg;
972 }
973 return true;
974}
Mike Stump11289f42009-09-09 15:08:12 +0000975
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000976/// Checks if a the given expression evaluates to null.
977///
978/// \brief Returns true if the value evaluates to null.
979static bool CheckNonNullExpr(Sema &S,
980 const Expr *Expr) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000981 // As a special case, transparent unions initialized with zero are
982 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000983 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +0000984 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
985 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000986 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +0000987 if (const InitListExpr *ILE =
988 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000989 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +0000990 }
991
992 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +0000993 return (!Expr->isValueDependent() &&
994 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
995 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +0000996}
997
998static void CheckNonNullArgument(Sema &S,
999 const Expr *ArgExpr,
1000 SourceLocation CallSiteLoc) {
1001 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001002 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1003}
1004
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001005bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1006 FormatStringInfo FSI;
1007 if ((GetFormatStringType(Format) == FST_NSString) &&
1008 getFormatStringInfo(Format, false, &FSI)) {
1009 Idx = FSI.FormatIdx;
1010 return true;
1011 }
1012 return false;
1013}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001014/// \brief Diagnose use of %s directive in an NSString which is being passed
1015/// as formatting string to formatting method.
1016static void
1017DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1018 const NamedDecl *FDecl,
1019 Expr **Args,
1020 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001021 unsigned Idx = 0;
1022 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001023 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1024 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001025 Idx = 2;
1026 Format = true;
1027 }
1028 else
1029 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1030 if (S.GetFormatNSStringIdx(I, Idx)) {
1031 Format = true;
1032 break;
1033 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001034 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001035 if (!Format || NumArgs <= Idx)
1036 return;
1037 const Expr *FormatExpr = Args[Idx];
1038 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1039 FormatExpr = CSCE->getSubExpr();
1040 const StringLiteral *FormatString;
1041 if (const ObjCStringLiteral *OSL =
1042 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1043 FormatString = OSL->getString();
1044 else
1045 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1046 if (!FormatString)
1047 return;
1048 if (S.FormatStringHasSArg(FormatString)) {
1049 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1050 << "%s" << 1 << 1;
1051 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1052 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001053 }
1054}
1055
Ted Kremenek2bc73332014-01-17 06:24:43 +00001056static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001057 const NamedDecl *FDecl,
Richard Smith588bd9b2014-08-27 04:59:42 +00001058 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001059 SourceLocation CallSiteLoc) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001060 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001061 llvm::SmallBitVector NonNullArgs;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001062 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001063 if (!NonNull->args_size()) {
1064 // Easy case: all pointer arguments are nonnull.
1065 for (const auto *Arg : Args)
Hal Finkelee90a222014-09-26 05:04:30 +00001066 if (S.isValidPointerAttrType(Arg->getType()))
Richard Smith588bd9b2014-08-27 04:59:42 +00001067 CheckNonNullArgument(S, Arg, CallSiteLoc);
1068 return;
1069 }
1070
1071 for (unsigned Val : NonNull->args()) {
1072 if (Val >= Args.size())
1073 continue;
1074 if (NonNullArgs.empty())
1075 NonNullArgs.resize(Args.size());
1076 NonNullArgs.set(Val);
1077 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001078 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001079
1080 // Check the attributes on the parameters.
1081 ArrayRef<ParmVarDecl*> parms;
1082 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1083 parms = FD->parameters();
1084 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1085 parms = MD->parameters();
1086
Richard Smith588bd9b2014-08-27 04:59:42 +00001087 unsigned ArgIndex = 0;
Ted Kremenek9aedc152014-01-17 06:24:56 +00001088 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
Richard Smith588bd9b2014-08-27 04:59:42 +00001089 I != E; ++I, ++ArgIndex) {
Ted Kremenek9aedc152014-01-17 06:24:56 +00001090 const ParmVarDecl *PVD = *I;
Richard Smith588bd9b2014-08-27 04:59:42 +00001091 if (PVD->hasAttr<NonNullAttr>() ||
1092 (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1093 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek9aedc152014-01-17 06:24:56 +00001094 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001095
1096 // In case this is a variadic call, check any remaining arguments.
1097 for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1098 if (NonNullArgs[ArgIndex])
1099 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Ted Kremenek2bc73332014-01-17 06:24:43 +00001100}
1101
Richard Smith55ce3522012-06-25 20:30:08 +00001102/// Handles the checks for format strings, non-POD arguments to vararg
1103/// functions, and NULL arguments passed to non-NULL parameters.
Alp Toker9cacbab2014-01-20 20:26:09 +00001104void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1105 unsigned NumParams, bool IsMemberFunction,
1106 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001107 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001108 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001109 if (CurContext->isDependentContext())
1110 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001111
Ted Kremenekb8176da2010-09-09 04:33:05 +00001112 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001113 llvm::SmallBitVector CheckedVarArgs;
1114 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001115 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001116 // Only create vector if there are format attributes.
1117 CheckedVarArgs.resize(Args.size());
1118
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001119 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001120 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001121 }
Richard Smithd7293d72013-08-05 18:49:43 +00001122 }
Richard Smith55ce3522012-06-25 20:30:08 +00001123
1124 // Refuse POD arguments that weren't caught by the format string
1125 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001126 if (CallType != VariadicDoesNotApply) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001127 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001128 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001129 if (const Expr *Arg = Args[ArgIdx]) {
1130 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1131 checkVariadicArgument(Arg, CallType);
1132 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001133 }
Richard Smithd7293d72013-08-05 18:49:43 +00001134 }
Mike Stump11289f42009-09-09 15:08:12 +00001135
Richard Trieu41bc0992013-06-22 00:20:41 +00001136 if (FDecl) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001137 CheckNonNullArguments(*this, FDecl, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001138
Richard Trieu41bc0992013-06-22 00:20:41 +00001139 // Type safety checking.
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001140 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1141 CheckArgumentWithTypeTag(I, Args.data());
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001142 }
Richard Smith55ce3522012-06-25 20:30:08 +00001143}
1144
1145/// CheckConstructorCall - Check a constructor call for correctness and safety
1146/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001147void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1148 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001149 const FunctionProtoType *Proto,
1150 SourceLocation Loc) {
1151 VariadicCallType CallType =
1152 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Alp Toker9cacbab2014-01-20 20:26:09 +00001153 checkCall(FDecl, Args, Proto->getNumParams(),
Richard Smith55ce3522012-06-25 20:30:08 +00001154 /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1155}
1156
1157/// CheckFunctionCall - Check a direct function call for various correctness
1158/// and safety properties not strictly enforced by the C type system.
1159bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1160 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001161 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1162 isa<CXXMethodDecl>(FDecl);
1163 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1164 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001165 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1166 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001167 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Eli Friedman726d11c2012-10-11 00:30:58 +00001168 Expr** Args = TheCall->getArgs();
1169 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001170 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001171 // If this is a call to a member operator, hide the first argument
1172 // from checkCall.
1173 // FIXME: Our choice of AST representation here is less than ideal.
1174 ++Args;
1175 --NumArgs;
1176 }
Craig Topper8c2a2a02014-08-30 16:55:39 +00001177 checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
Richard Smith55ce3522012-06-25 20:30:08 +00001178 IsMemberFunction, TheCall->getRParenLoc(),
1179 TheCall->getCallee()->getSourceRange(), CallType);
1180
1181 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1182 // None of the checks below are needed for functions that don't have
1183 // simple names (e.g., C++ conversion functions).
1184 if (!FnInfo)
1185 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001186
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001187 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001188 if (getLangOpts().ObjC1)
1189 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001190
Anna Zaks22122702012-01-17 00:37:07 +00001191 unsigned CMId = FDecl->getMemoryFunctionKind();
1192 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001193 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001194
Anna Zaks201d4892012-01-13 21:52:01 +00001195 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001196 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001197 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001198 else if (CMId == Builtin::BIstrncat)
1199 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001200 else
Anna Zaks22122702012-01-17 00:37:07 +00001201 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001202
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001203 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001204}
1205
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001206bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001207 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001208 VariadicCallType CallType =
1209 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001210
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001211 checkCall(Method, Args, Method->param_size(),
Richard Smith55ce3522012-06-25 20:30:08 +00001212 /*IsMemberFunction=*/false,
1213 lbrac, Method->getSourceRange(), CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001214
1215 return false;
1216}
1217
Richard Trieu664c4c62013-06-20 21:03:13 +00001218bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1219 const FunctionProtoType *Proto) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001220 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1221 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001222 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001223
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001224 QualType Ty = V->getType();
Richard Trieu664c4c62013-06-20 21:03:13 +00001225 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001226 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001227
Richard Trieu664c4c62013-06-20 21:03:13 +00001228 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001229 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001230 CallType = VariadicDoesNotApply;
1231 } else if (Ty->isBlockPointerType()) {
1232 CallType = VariadicBlock;
1233 } else { // Ty->isFunctionPointerType()
1234 CallType = VariadicFunction;
1235 }
Alp Toker9cacbab2014-01-20 20:26:09 +00001236 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001237
Craig Topper8c2a2a02014-08-30 16:55:39 +00001238 checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1239 TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001240 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001241 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001242
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001243 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001244}
1245
Richard Trieu41bc0992013-06-22 00:20:41 +00001246/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1247/// such as function pointers returned from functions.
1248bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001249 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001250 TheCall->getCallee());
Alp Toker9cacbab2014-01-20 20:26:09 +00001251 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
Richard Trieu41bc0992013-06-22 00:20:41 +00001252
Craig Topperc3ec1492014-05-26 06:22:03 +00001253 checkCall(/*FDecl=*/nullptr,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001254 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Alp Toker9cacbab2014-01-20 20:26:09 +00001255 NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001256 TheCall->getCallee()->getSourceRange(), CallType);
1257
1258 return false;
1259}
1260
Tim Northovere94a34c2014-03-11 10:49:14 +00001261static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1262 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1263 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1264 return false;
1265
1266 switch (Op) {
1267 case AtomicExpr::AO__c11_atomic_init:
1268 llvm_unreachable("There is no ordering argument for an init");
1269
1270 case AtomicExpr::AO__c11_atomic_load:
1271 case AtomicExpr::AO__atomic_load_n:
1272 case AtomicExpr::AO__atomic_load:
1273 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1274 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1275
1276 case AtomicExpr::AO__c11_atomic_store:
1277 case AtomicExpr::AO__atomic_store:
1278 case AtomicExpr::AO__atomic_store_n:
1279 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1280 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1281 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1282
1283 default:
1284 return true;
1285 }
1286}
1287
Richard Smithfeea8832012-04-12 05:08:17 +00001288ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1289 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001290 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1291 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001292
Richard Smithfeea8832012-04-12 05:08:17 +00001293 // All these operations take one of the following forms:
1294 enum {
1295 // C __c11_atomic_init(A *, C)
1296 Init,
1297 // C __c11_atomic_load(A *, int)
1298 Load,
1299 // void __atomic_load(A *, CP, int)
1300 Copy,
1301 // C __c11_atomic_add(A *, M, int)
1302 Arithmetic,
1303 // C __atomic_exchange_n(A *, CP, int)
1304 Xchg,
1305 // void __atomic_exchange(A *, C *, CP, int)
1306 GNUXchg,
1307 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1308 C11CmpXchg,
1309 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1310 GNUCmpXchg
1311 } Form = Init;
1312 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1313 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1314 // where:
1315 // C is an appropriate type,
1316 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1317 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1318 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1319 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001320
Richard Smithfeea8832012-04-12 05:08:17 +00001321 assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1322 AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1323 && "need to update code for modified C11 atomics");
1324 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1325 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1326 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1327 Op == AtomicExpr::AO__atomic_store_n ||
1328 Op == AtomicExpr::AO__atomic_exchange_n ||
1329 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1330 bool IsAddSub = false;
1331
1332 switch (Op) {
1333 case AtomicExpr::AO__c11_atomic_init:
1334 Form = Init;
1335 break;
1336
1337 case AtomicExpr::AO__c11_atomic_load:
1338 case AtomicExpr::AO__atomic_load_n:
1339 Form = Load;
1340 break;
1341
1342 case AtomicExpr::AO__c11_atomic_store:
1343 case AtomicExpr::AO__atomic_load:
1344 case AtomicExpr::AO__atomic_store:
1345 case AtomicExpr::AO__atomic_store_n:
1346 Form = Copy;
1347 break;
1348
1349 case AtomicExpr::AO__c11_atomic_fetch_add:
1350 case AtomicExpr::AO__c11_atomic_fetch_sub:
1351 case AtomicExpr::AO__atomic_fetch_add:
1352 case AtomicExpr::AO__atomic_fetch_sub:
1353 case AtomicExpr::AO__atomic_add_fetch:
1354 case AtomicExpr::AO__atomic_sub_fetch:
1355 IsAddSub = true;
1356 // Fall through.
1357 case AtomicExpr::AO__c11_atomic_fetch_and:
1358 case AtomicExpr::AO__c11_atomic_fetch_or:
1359 case AtomicExpr::AO__c11_atomic_fetch_xor:
1360 case AtomicExpr::AO__atomic_fetch_and:
1361 case AtomicExpr::AO__atomic_fetch_or:
1362 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001363 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001364 case AtomicExpr::AO__atomic_and_fetch:
1365 case AtomicExpr::AO__atomic_or_fetch:
1366 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001367 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001368 Form = Arithmetic;
1369 break;
1370
1371 case AtomicExpr::AO__c11_atomic_exchange:
1372 case AtomicExpr::AO__atomic_exchange_n:
1373 Form = Xchg;
1374 break;
1375
1376 case AtomicExpr::AO__atomic_exchange:
1377 Form = GNUXchg;
1378 break;
1379
1380 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1381 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1382 Form = C11CmpXchg;
1383 break;
1384
1385 case AtomicExpr::AO__atomic_compare_exchange:
1386 case AtomicExpr::AO__atomic_compare_exchange_n:
1387 Form = GNUCmpXchg;
1388 break;
1389 }
1390
1391 // Check we have the right number of arguments.
1392 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001393 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001394 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001395 << TheCall->getCallee()->getSourceRange();
1396 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001397 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1398 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001399 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001400 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001401 << TheCall->getCallee()->getSourceRange();
1402 return ExprError();
1403 }
1404
Richard Smithfeea8832012-04-12 05:08:17 +00001405 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001406 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001407 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1408 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1409 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001410 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001411 << Ptr->getType() << Ptr->getSourceRange();
1412 return ExprError();
1413 }
1414
Richard Smithfeea8832012-04-12 05:08:17 +00001415 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1416 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1417 QualType ValType = AtomTy; // 'C'
1418 if (IsC11) {
1419 if (!AtomTy->isAtomicType()) {
1420 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1421 << Ptr->getType() << Ptr->getSourceRange();
1422 return ExprError();
1423 }
Richard Smithe00921a2012-09-15 06:09:58 +00001424 if (AtomTy.isConstQualified()) {
1425 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1426 << Ptr->getType() << Ptr->getSourceRange();
1427 return ExprError();
1428 }
Richard Smithfeea8832012-04-12 05:08:17 +00001429 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001430 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001431
Richard Smithfeea8832012-04-12 05:08:17 +00001432 // For an arithmetic operation, the implied arithmetic must be well-formed.
1433 if (Form == Arithmetic) {
1434 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1435 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1436 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1437 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1438 return ExprError();
1439 }
1440 if (!IsAddSub && !ValType->isIntegerType()) {
1441 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1442 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1443 return ExprError();
1444 }
David Majnemere85cff82015-01-28 05:48:06 +00001445 if (IsC11 && ValType->isPointerType() &&
1446 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1447 diag::err_incomplete_type)) {
1448 return ExprError();
1449 }
Richard Smithfeea8832012-04-12 05:08:17 +00001450 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1451 // For __atomic_*_n operations, the value type must be a scalar integral or
1452 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001453 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001454 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1455 return ExprError();
1456 }
1457
Eli Friedmanaa769812013-09-11 03:49:34 +00001458 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1459 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001460 // For GNU atomics, require a trivially-copyable type. This is not part of
1461 // the GNU atomics specification, but we enforce it for sanity.
1462 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001463 << Ptr->getType() << Ptr->getSourceRange();
1464 return ExprError();
1465 }
1466
Richard Smithfeea8832012-04-12 05:08:17 +00001467 // FIXME: For any builtin other than a load, the ValType must not be
1468 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001469
1470 switch (ValType.getObjCLifetime()) {
1471 case Qualifiers::OCL_None:
1472 case Qualifiers::OCL_ExplicitNone:
1473 // okay
1474 break;
1475
1476 case Qualifiers::OCL_Weak:
1477 case Qualifiers::OCL_Strong:
1478 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001479 // FIXME: Can this happen? By this point, ValType should be known
1480 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001481 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1482 << ValType << Ptr->getSourceRange();
1483 return ExprError();
1484 }
1485
1486 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001487 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001488 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001489 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001490 ResultType = Context.BoolTy;
1491
Richard Smithfeea8832012-04-12 05:08:17 +00001492 // The type of a parameter passed 'by value'. In the GNU atomics, such
1493 // arguments are actually passed as pointers.
1494 QualType ByValType = ValType; // 'CP'
1495 if (!IsC11 && !IsN)
1496 ByValType = Ptr->getType();
1497
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001498 // The first argument --- the pointer --- has a fixed type; we
1499 // deduce the types of the rest of the arguments accordingly. Walk
1500 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001501 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001502 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001503 if (i < NumVals[Form] + 1) {
1504 switch (i) {
1505 case 1:
1506 // The second argument is the non-atomic operand. For arithmetic, this
1507 // is always passed by value, and for a compare_exchange it is always
1508 // passed by address. For the rest, GNU uses by-address and C11 uses
1509 // by-value.
1510 assert(Form != Load);
1511 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1512 Ty = ValType;
1513 else if (Form == Copy || Form == Xchg)
1514 Ty = ByValType;
1515 else if (Form == Arithmetic)
1516 Ty = Context.getPointerDiffType();
1517 else
1518 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1519 break;
1520 case 2:
1521 // The third argument to compare_exchange / GNU exchange is a
1522 // (pointer to a) desired value.
1523 Ty = ByValType;
1524 break;
1525 case 3:
1526 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1527 Ty = Context.BoolTy;
1528 break;
1529 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001530 } else {
1531 // The order(s) are always converted to int.
1532 Ty = Context.IntTy;
1533 }
Richard Smithfeea8832012-04-12 05:08:17 +00001534
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001535 InitializedEntity Entity =
1536 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001537 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001538 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1539 if (Arg.isInvalid())
1540 return true;
1541 TheCall->setArg(i, Arg.get());
1542 }
1543
Richard Smithfeea8832012-04-12 05:08:17 +00001544 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001545 SmallVector<Expr*, 5> SubExprs;
1546 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001547 switch (Form) {
1548 case Init:
1549 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001550 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001551 break;
1552 case Load:
1553 SubExprs.push_back(TheCall->getArg(1)); // Order
1554 break;
1555 case Copy:
1556 case Arithmetic:
1557 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001558 SubExprs.push_back(TheCall->getArg(2)); // Order
1559 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001560 break;
1561 case GNUXchg:
1562 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1563 SubExprs.push_back(TheCall->getArg(3)); // Order
1564 SubExprs.push_back(TheCall->getArg(1)); // Val1
1565 SubExprs.push_back(TheCall->getArg(2)); // Val2
1566 break;
1567 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001568 SubExprs.push_back(TheCall->getArg(3)); // Order
1569 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001570 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001571 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001572 break;
1573 case GNUCmpXchg:
1574 SubExprs.push_back(TheCall->getArg(4)); // Order
1575 SubExprs.push_back(TheCall->getArg(1)); // Val1
1576 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1577 SubExprs.push_back(TheCall->getArg(2)); // Val2
1578 SubExprs.push_back(TheCall->getArg(3)); // Weak
1579 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001580 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001581
1582 if (SubExprs.size() >= 2 && Form != Init) {
1583 llvm::APSInt Result(32);
1584 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1585 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001586 Diag(SubExprs[1]->getLocStart(),
1587 diag::warn_atomic_op_has_invalid_memory_order)
1588 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001589 }
1590
Fariborz Jahanian615de762013-05-28 17:37:39 +00001591 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1592 SubExprs, ResultType, Op,
1593 TheCall->getRParenLoc());
1594
1595 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1596 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1597 Context.AtomicUsesUnsupportedLibcall(AE))
1598 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1599 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001600
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001601 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001602}
1603
1604
John McCall29ad95b2011-08-27 01:09:30 +00001605/// checkBuiltinArgument - Given a call to a builtin function, perform
1606/// normal type-checking on the given argument, updating the call in
1607/// place. This is useful when a builtin function requires custom
1608/// type-checking for some of its arguments but not necessarily all of
1609/// them.
1610///
1611/// Returns true on error.
1612static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1613 FunctionDecl *Fn = E->getDirectCallee();
1614 assert(Fn && "builtin call without direct callee!");
1615
1616 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1617 InitializedEntity Entity =
1618 InitializedEntity::InitializeParameter(S.Context, Param);
1619
1620 ExprResult Arg = E->getArg(0);
1621 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1622 if (Arg.isInvalid())
1623 return true;
1624
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001625 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001626 return false;
1627}
1628
Chris Lattnerdc046542009-05-08 06:58:22 +00001629/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1630/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1631/// type of its first argument. The main ActOnCallExpr routines have already
1632/// promoted the types of arguments because all of these calls are prototyped as
1633/// void(...).
1634///
1635/// This function goes through and does final semantic checking for these
1636/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001637ExprResult
1638Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001639 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001640 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1641 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1642
1643 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001644 if (TheCall->getNumArgs() < 1) {
1645 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1646 << 0 << 1 << TheCall->getNumArgs()
1647 << TheCall->getCallee()->getSourceRange();
1648 return ExprError();
1649 }
Mike Stump11289f42009-09-09 15:08:12 +00001650
Chris Lattnerdc046542009-05-08 06:58:22 +00001651 // Inspect the first argument of the atomic builtin. This should always be
1652 // a pointer type, whose element is an integral scalar or pointer type.
1653 // Because it is a pointer type, we don't have to worry about any implicit
1654 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001655 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001656 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001657 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1658 if (FirstArgResult.isInvalid())
1659 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001660 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001661 TheCall->setArg(0, FirstArg);
1662
John McCall31168b02011-06-15 23:02:42 +00001663 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1664 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001665 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1666 << FirstArg->getType() << FirstArg->getSourceRange();
1667 return ExprError();
1668 }
Mike Stump11289f42009-09-09 15:08:12 +00001669
John McCall31168b02011-06-15 23:02:42 +00001670 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001671 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001672 !ValType->isBlockPointerType()) {
1673 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1674 << FirstArg->getType() << FirstArg->getSourceRange();
1675 return ExprError();
1676 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001677
John McCall31168b02011-06-15 23:02:42 +00001678 switch (ValType.getObjCLifetime()) {
1679 case Qualifiers::OCL_None:
1680 case Qualifiers::OCL_ExplicitNone:
1681 // okay
1682 break;
1683
1684 case Qualifiers::OCL_Weak:
1685 case Qualifiers::OCL_Strong:
1686 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001687 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001688 << ValType << FirstArg->getSourceRange();
1689 return ExprError();
1690 }
1691
John McCallb50451a2011-10-05 07:41:44 +00001692 // Strip any qualifiers off ValType.
1693 ValType = ValType.getUnqualifiedType();
1694
Chandler Carruth3973af72010-07-18 20:54:12 +00001695 // The majority of builtins return a value, but a few have special return
1696 // types, so allow them to override appropriately below.
1697 QualType ResultType = ValType;
1698
Chris Lattnerdc046542009-05-08 06:58:22 +00001699 // We need to figure out which concrete builtin this maps onto. For example,
1700 // __sync_fetch_and_add with a 2 byte object turns into
1701 // __sync_fetch_and_add_2.
1702#define BUILTIN_ROW(x) \
1703 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1704 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001705
Chris Lattnerdc046542009-05-08 06:58:22 +00001706 static const unsigned BuiltinIndices[][5] = {
1707 BUILTIN_ROW(__sync_fetch_and_add),
1708 BUILTIN_ROW(__sync_fetch_and_sub),
1709 BUILTIN_ROW(__sync_fetch_and_or),
1710 BUILTIN_ROW(__sync_fetch_and_and),
1711 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001712 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001713
Chris Lattnerdc046542009-05-08 06:58:22 +00001714 BUILTIN_ROW(__sync_add_and_fetch),
1715 BUILTIN_ROW(__sync_sub_and_fetch),
1716 BUILTIN_ROW(__sync_and_and_fetch),
1717 BUILTIN_ROW(__sync_or_and_fetch),
1718 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001719 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001720
Chris Lattnerdc046542009-05-08 06:58:22 +00001721 BUILTIN_ROW(__sync_val_compare_and_swap),
1722 BUILTIN_ROW(__sync_bool_compare_and_swap),
1723 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001724 BUILTIN_ROW(__sync_lock_release),
1725 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001726 };
Mike Stump11289f42009-09-09 15:08:12 +00001727#undef BUILTIN_ROW
1728
Chris Lattnerdc046542009-05-08 06:58:22 +00001729 // Determine the index of the size.
1730 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001731 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001732 case 1: SizeIndex = 0; break;
1733 case 2: SizeIndex = 1; break;
1734 case 4: SizeIndex = 2; break;
1735 case 8: SizeIndex = 3; break;
1736 case 16: SizeIndex = 4; break;
1737 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001738 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1739 << FirstArg->getType() << FirstArg->getSourceRange();
1740 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Chris Lattnerdc046542009-05-08 06:58:22 +00001743 // Each of these builtins has one pointer argument, followed by some number of
1744 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1745 // that we ignore. Find out which row of BuiltinIndices to read from as well
1746 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001747 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001748 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001749 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001750 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001751 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001752 case Builtin::BI__sync_fetch_and_add:
1753 case Builtin::BI__sync_fetch_and_add_1:
1754 case Builtin::BI__sync_fetch_and_add_2:
1755 case Builtin::BI__sync_fetch_and_add_4:
1756 case Builtin::BI__sync_fetch_and_add_8:
1757 case Builtin::BI__sync_fetch_and_add_16:
1758 BuiltinIndex = 0;
1759 break;
1760
1761 case Builtin::BI__sync_fetch_and_sub:
1762 case Builtin::BI__sync_fetch_and_sub_1:
1763 case Builtin::BI__sync_fetch_and_sub_2:
1764 case Builtin::BI__sync_fetch_and_sub_4:
1765 case Builtin::BI__sync_fetch_and_sub_8:
1766 case Builtin::BI__sync_fetch_and_sub_16:
1767 BuiltinIndex = 1;
1768 break;
1769
1770 case Builtin::BI__sync_fetch_and_or:
1771 case Builtin::BI__sync_fetch_and_or_1:
1772 case Builtin::BI__sync_fetch_and_or_2:
1773 case Builtin::BI__sync_fetch_and_or_4:
1774 case Builtin::BI__sync_fetch_and_or_8:
1775 case Builtin::BI__sync_fetch_and_or_16:
1776 BuiltinIndex = 2;
1777 break;
1778
1779 case Builtin::BI__sync_fetch_and_and:
1780 case Builtin::BI__sync_fetch_and_and_1:
1781 case Builtin::BI__sync_fetch_and_and_2:
1782 case Builtin::BI__sync_fetch_and_and_4:
1783 case Builtin::BI__sync_fetch_and_and_8:
1784 case Builtin::BI__sync_fetch_and_and_16:
1785 BuiltinIndex = 3;
1786 break;
Mike Stump11289f42009-09-09 15:08:12 +00001787
Douglas Gregor73722482011-11-28 16:30:08 +00001788 case Builtin::BI__sync_fetch_and_xor:
1789 case Builtin::BI__sync_fetch_and_xor_1:
1790 case Builtin::BI__sync_fetch_and_xor_2:
1791 case Builtin::BI__sync_fetch_and_xor_4:
1792 case Builtin::BI__sync_fetch_and_xor_8:
1793 case Builtin::BI__sync_fetch_and_xor_16:
1794 BuiltinIndex = 4;
1795 break;
1796
Hal Finkeld2208b52014-10-02 20:53:50 +00001797 case Builtin::BI__sync_fetch_and_nand:
1798 case Builtin::BI__sync_fetch_and_nand_1:
1799 case Builtin::BI__sync_fetch_and_nand_2:
1800 case Builtin::BI__sync_fetch_and_nand_4:
1801 case Builtin::BI__sync_fetch_and_nand_8:
1802 case Builtin::BI__sync_fetch_and_nand_16:
1803 BuiltinIndex = 5;
1804 WarnAboutSemanticsChange = true;
1805 break;
1806
Douglas Gregor73722482011-11-28 16:30:08 +00001807 case Builtin::BI__sync_add_and_fetch:
1808 case Builtin::BI__sync_add_and_fetch_1:
1809 case Builtin::BI__sync_add_and_fetch_2:
1810 case Builtin::BI__sync_add_and_fetch_4:
1811 case Builtin::BI__sync_add_and_fetch_8:
1812 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001813 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00001814 break;
1815
1816 case Builtin::BI__sync_sub_and_fetch:
1817 case Builtin::BI__sync_sub_and_fetch_1:
1818 case Builtin::BI__sync_sub_and_fetch_2:
1819 case Builtin::BI__sync_sub_and_fetch_4:
1820 case Builtin::BI__sync_sub_and_fetch_8:
1821 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001822 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00001823 break;
1824
1825 case Builtin::BI__sync_and_and_fetch:
1826 case Builtin::BI__sync_and_and_fetch_1:
1827 case Builtin::BI__sync_and_and_fetch_2:
1828 case Builtin::BI__sync_and_and_fetch_4:
1829 case Builtin::BI__sync_and_and_fetch_8:
1830 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001831 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00001832 break;
1833
1834 case Builtin::BI__sync_or_and_fetch:
1835 case Builtin::BI__sync_or_and_fetch_1:
1836 case Builtin::BI__sync_or_and_fetch_2:
1837 case Builtin::BI__sync_or_and_fetch_4:
1838 case Builtin::BI__sync_or_and_fetch_8:
1839 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001840 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00001841 break;
1842
1843 case Builtin::BI__sync_xor_and_fetch:
1844 case Builtin::BI__sync_xor_and_fetch_1:
1845 case Builtin::BI__sync_xor_and_fetch_2:
1846 case Builtin::BI__sync_xor_and_fetch_4:
1847 case Builtin::BI__sync_xor_and_fetch_8:
1848 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001849 BuiltinIndex = 10;
1850 break;
1851
1852 case Builtin::BI__sync_nand_and_fetch:
1853 case Builtin::BI__sync_nand_and_fetch_1:
1854 case Builtin::BI__sync_nand_and_fetch_2:
1855 case Builtin::BI__sync_nand_and_fetch_4:
1856 case Builtin::BI__sync_nand_and_fetch_8:
1857 case Builtin::BI__sync_nand_and_fetch_16:
1858 BuiltinIndex = 11;
1859 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00001860 break;
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattnerdc046542009-05-08 06:58:22 +00001862 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001863 case Builtin::BI__sync_val_compare_and_swap_1:
1864 case Builtin::BI__sync_val_compare_and_swap_2:
1865 case Builtin::BI__sync_val_compare_and_swap_4:
1866 case Builtin::BI__sync_val_compare_and_swap_8:
1867 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001868 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00001869 NumFixed = 2;
1870 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001871
Chris Lattnerdc046542009-05-08 06:58:22 +00001872 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00001873 case Builtin::BI__sync_bool_compare_and_swap_1:
1874 case Builtin::BI__sync_bool_compare_and_swap_2:
1875 case Builtin::BI__sync_bool_compare_and_swap_4:
1876 case Builtin::BI__sync_bool_compare_and_swap_8:
1877 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001878 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00001879 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00001880 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001881 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001882
1883 case Builtin::BI__sync_lock_test_and_set:
1884 case Builtin::BI__sync_lock_test_and_set_1:
1885 case Builtin::BI__sync_lock_test_and_set_2:
1886 case Builtin::BI__sync_lock_test_and_set_4:
1887 case Builtin::BI__sync_lock_test_and_set_8:
1888 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001889 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00001890 break;
1891
Chris Lattnerdc046542009-05-08 06:58:22 +00001892 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00001893 case Builtin::BI__sync_lock_release_1:
1894 case Builtin::BI__sync_lock_release_2:
1895 case Builtin::BI__sync_lock_release_4:
1896 case Builtin::BI__sync_lock_release_8:
1897 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001898 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00001899 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00001900 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00001901 break;
Douglas Gregor73722482011-11-28 16:30:08 +00001902
1903 case Builtin::BI__sync_swap:
1904 case Builtin::BI__sync_swap_1:
1905 case Builtin::BI__sync_swap_2:
1906 case Builtin::BI__sync_swap_4:
1907 case Builtin::BI__sync_swap_8:
1908 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00001909 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00001910 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00001911 }
Mike Stump11289f42009-09-09 15:08:12 +00001912
Chris Lattnerdc046542009-05-08 06:58:22 +00001913 // Now that we know how many fixed arguments we expect, first check that we
1914 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001915 if (TheCall->getNumArgs() < 1+NumFixed) {
1916 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1917 << 0 << 1+NumFixed << TheCall->getNumArgs()
1918 << TheCall->getCallee()->getSourceRange();
1919 return ExprError();
1920 }
Mike Stump11289f42009-09-09 15:08:12 +00001921
Hal Finkeld2208b52014-10-02 20:53:50 +00001922 if (WarnAboutSemanticsChange) {
1923 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1924 << TheCall->getCallee()->getSourceRange();
1925 }
1926
Chris Lattner5b9241b2009-05-08 15:36:58 +00001927 // Get the decl for the concrete builtin from this, we can tell what the
1928 // concrete integer type we should convert to is.
1929 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1930 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001931 FunctionDecl *NewBuiltinDecl;
1932 if (NewBuiltinID == BuiltinID)
1933 NewBuiltinDecl = FDecl;
1934 else {
1935 // Perform builtin lookup to avoid redeclaring it.
1936 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1937 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1938 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1939 assert(Res.getFoundDecl());
1940 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00001941 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00001942 return ExprError();
1943 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001944
John McCallcf142162010-08-07 06:22:56 +00001945 // The first argument --- the pointer --- has a fixed type; we
1946 // deduce the types of the rest of the arguments accordingly. Walk
1947 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00001948 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00001949 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattnerdc046542009-05-08 06:58:22 +00001951 // GCC does an implicit conversion to the pointer or integer ValType. This
1952 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00001953 // Initialize the argument.
1954 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1955 ValType, /*consume*/ false);
1956 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00001957 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001958 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001959
Chris Lattnerdc046542009-05-08 06:58:22 +00001960 // Okay, we have something that *can* be converted to the right type. Check
1961 // to see if there is a potentially weird extension going on here. This can
1962 // happen when you do an atomic operation on something like an char* and
1963 // pass in 42. The 42 gets converted to char. This is even more strange
1964 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00001965 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001966 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00001967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001969 ASTContext& Context = this->getASTContext();
1970
1971 // Create a new DeclRefExpr to refer to the new decl.
1972 DeclRefExpr* NewDRE = DeclRefExpr::Create(
1973 Context,
1974 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001975 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001976 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00001977 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001978 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00001979 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00001980 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattnerdc046542009-05-08 06:58:22 +00001982 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00001983 // FIXME: This loses syntactic information.
1984 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1985 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1986 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001987 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00001988
Chandler Carruthbc8cab12010-07-18 07:23:17 +00001989 // Change the result type of the call to match the original value type. This
1990 // is arbitrary, but the codegen for these builtins ins design to handle it
1991 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00001992 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001993
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001994 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00001995}
1996
Chris Lattner6436fb62009-02-18 06:01:06 +00001997/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00001998/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00001999/// Note: It might also make sense to do the UTF-16 conversion here (would
2000/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002001bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002002 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002003 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2004
Douglas Gregorfb65e592011-07-27 05:40:30 +00002005 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002006 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2007 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002008 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002011 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002012 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002013 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002014 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002015 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002016 UTF16 *ToPtr = &ToBuf[0];
2017
2018 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2019 &ToPtr, ToPtr + NumBytes,
2020 strictConversion);
2021 // Check for conversion failure.
2022 if (Result != conversionOK)
2023 Diag(Arg->getLocStart(),
2024 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2025 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002026 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002027}
2028
Chris Lattnere202e6a2007-12-20 00:05:45 +00002029/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2030/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002031bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2032 Expr *Fn = TheCall->getCallee();
2033 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002034 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002035 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002036 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2037 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002038 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002039 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002040 return true;
2041 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002042
2043 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002044 return Diag(TheCall->getLocEnd(),
2045 diag::err_typecheck_call_too_few_args_at_least)
2046 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002047 }
2048
John McCall29ad95b2011-08-27 01:09:30 +00002049 // Type-check the first argument normally.
2050 if (checkBuiltinArgument(*this, TheCall, 0))
2051 return true;
2052
Chris Lattnere202e6a2007-12-20 00:05:45 +00002053 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002054 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002055 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002056 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002057 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002058 else if (FunctionDecl *FD = getCurFunctionDecl())
2059 isVariadic = FD->isVariadic();
2060 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002061 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002062
Chris Lattnere202e6a2007-12-20 00:05:45 +00002063 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002064 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2065 return true;
2066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Chris Lattner43be2e62007-12-19 23:59:04 +00002068 // Verify that the second argument to the builtin is the last argument of the
2069 // current function or method.
2070 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002071 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002072
Nico Weber9eea7642013-05-24 23:31:57 +00002073 // These are valid if SecondArgIsLastNamedArgument is false after the next
2074 // block.
2075 QualType Type;
2076 SourceLocation ParamLoc;
2077
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002078 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2079 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002080 // FIXME: This isn't correct for methods (results in bogus warning).
2081 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002082 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002083 if (CurBlock)
2084 LastArg = *(CurBlock->TheDecl->param_end()-1);
2085 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002086 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002087 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002088 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002089 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002090
2091 Type = PV->getType();
2092 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002093 }
2094 }
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattner43be2e62007-12-19 23:59:04 +00002096 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002097 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002098 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002099 else if (Type->isReferenceType()) {
2100 Diag(Arg->getLocStart(),
2101 diag::warn_va_start_of_reference_type_is_undefined);
2102 Diag(ParamLoc, diag::note_parameter_type) << Type;
2103 }
2104
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002105 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002106 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002107}
Chris Lattner43be2e62007-12-19 23:59:04 +00002108
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002109bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2110 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2111 // const char *named_addr);
2112
2113 Expr *Func = Call->getCallee();
2114
2115 if (Call->getNumArgs() < 3)
2116 return Diag(Call->getLocEnd(),
2117 diag::err_typecheck_call_too_few_args_at_least)
2118 << 0 /*function call*/ << 3 << Call->getNumArgs();
2119
2120 // Determine whether the current function is variadic or not.
2121 bool IsVariadic;
2122 if (BlockScopeInfo *CurBlock = getCurBlock())
2123 IsVariadic = CurBlock->TheDecl->isVariadic();
2124 else if (FunctionDecl *FD = getCurFunctionDecl())
2125 IsVariadic = FD->isVariadic();
2126 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2127 IsVariadic = MD->isVariadic();
2128 else
2129 llvm_unreachable("unexpected statement type");
2130
2131 if (!IsVariadic) {
2132 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2133 return true;
2134 }
2135
2136 // Type-check the first argument normally.
2137 if (checkBuiltinArgument(*this, Call, 0))
2138 return true;
2139
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002140 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002141 unsigned ArgNo;
2142 QualType Type;
2143 } ArgumentTypes[] = {
2144 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2145 { 2, Context.getSizeType() },
2146 };
2147
2148 for (const auto &AT : ArgumentTypes) {
2149 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2150 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2151 continue;
2152 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2153 << Arg->getType() << AT.Type << 1 /* different class */
2154 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2155 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2156 }
2157
2158 return false;
2159}
2160
Chris Lattner2da14fb2007-12-20 00:26:33 +00002161/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2162/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002163bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2164 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002165 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002166 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002167 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002168 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002169 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002170 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002171 << SourceRange(TheCall->getArg(2)->getLocStart(),
2172 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002173
John Wiegley01296292011-04-08 18:41:53 +00002174 ExprResult OrigArg0 = TheCall->getArg(0);
2175 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002176
Chris Lattner2da14fb2007-12-20 00:26:33 +00002177 // Do standard promotions between the two arguments, returning their common
2178 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002179 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002180 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2181 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002182
2183 // Make sure any conversions are pushed back into the call; this is
2184 // type safe since unordered compare builtins are declared as "_Bool
2185 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002186 TheCall->setArg(0, OrigArg0.get());
2187 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002188
John Wiegley01296292011-04-08 18:41:53 +00002189 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002190 return false;
2191
Chris Lattner2da14fb2007-12-20 00:26:33 +00002192 // If the common type isn't a real floating type, then the arguments were
2193 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002194 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002195 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002196 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002197 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2198 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002199
Chris Lattner2da14fb2007-12-20 00:26:33 +00002200 return false;
2201}
2202
Benjamin Kramer634fc102010-02-15 22:42:31 +00002203/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2204/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002205/// to check everything. We expect the last argument to be a floating point
2206/// value.
2207bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2208 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002209 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002210 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002211 if (TheCall->getNumArgs() > NumArgs)
2212 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002213 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002214 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002215 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002216 (*(TheCall->arg_end()-1))->getLocEnd());
2217
Benjamin Kramer64aae502010-02-16 10:07:31 +00002218 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002219
Eli Friedman7e4faac2009-08-31 20:06:00 +00002220 if (OrigArg->isTypeDependent())
2221 return false;
2222
Chris Lattner68784ef2010-05-06 05:50:07 +00002223 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002224 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002225 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002226 diag::err_typecheck_call_invalid_unary_fp)
2227 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002228
Chris Lattner68784ef2010-05-06 05:50:07 +00002229 // If this is an implicit conversion from float -> double, remove it.
2230 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2231 Expr *CastArg = Cast->getSubExpr();
2232 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2233 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2234 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002235 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002236 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002237 }
2238 }
2239
Eli Friedman7e4faac2009-08-31 20:06:00 +00002240 return false;
2241}
2242
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002243/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2244// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002245ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002246 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002247 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002248 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002249 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2250 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002251
Nate Begemana0110022010-06-08 00:16:34 +00002252 // Determine which of the following types of shufflevector we're checking:
2253 // 1) unary, vector mask: (lhs, mask)
2254 // 2) binary, vector mask: (lhs, rhs, mask)
2255 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2256 QualType resType = TheCall->getArg(0)->getType();
2257 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002258
Douglas Gregorc25f7662009-05-19 22:10:17 +00002259 if (!TheCall->getArg(0)->isTypeDependent() &&
2260 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002261 QualType LHSType = TheCall->getArg(0)->getType();
2262 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002263
Craig Topperbaca3892013-07-29 06:47:04 +00002264 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2265 return ExprError(Diag(TheCall->getLocStart(),
2266 diag::err_shufflevector_non_vector)
2267 << SourceRange(TheCall->getArg(0)->getLocStart(),
2268 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002269
Nate Begemana0110022010-06-08 00:16:34 +00002270 numElements = LHSType->getAs<VectorType>()->getNumElements();
2271 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002272
Nate Begemana0110022010-06-08 00:16:34 +00002273 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2274 // with mask. If so, verify that RHS is an integer vector type with the
2275 // same number of elts as lhs.
2276 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002277 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002278 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002279 return ExprError(Diag(TheCall->getLocStart(),
2280 diag::err_shufflevector_incompatible_vector)
2281 << SourceRange(TheCall->getArg(1)->getLocStart(),
2282 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002283 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002284 return ExprError(Diag(TheCall->getLocStart(),
2285 diag::err_shufflevector_incompatible_vector)
2286 << SourceRange(TheCall->getArg(0)->getLocStart(),
2287 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002288 } else if (numElements != numResElements) {
2289 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002290 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002291 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002292 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002293 }
2294
2295 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002296 if (TheCall->getArg(i)->isTypeDependent() ||
2297 TheCall->getArg(i)->isValueDependent())
2298 continue;
2299
Nate Begemana0110022010-06-08 00:16:34 +00002300 llvm::APSInt Result(32);
2301 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2302 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002303 diag::err_shufflevector_nonconstant_argument)
2304 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002305
Craig Topper50ad5b72013-08-03 17:40:38 +00002306 // Allow -1 which will be translated to undef in the IR.
2307 if (Result.isSigned() && Result.isAllOnesValue())
2308 continue;
2309
Chris Lattner7ab824e2008-08-10 02:05:13 +00002310 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002311 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002312 diag::err_shufflevector_argument_too_large)
2313 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002314 }
2315
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002316 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002317
Chris Lattner7ab824e2008-08-10 02:05:13 +00002318 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002319 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002320 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002321 }
2322
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002323 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2324 TheCall->getCallee()->getLocStart(),
2325 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002326}
Chris Lattner43be2e62007-12-19 23:59:04 +00002327
Hal Finkelc4d7c822013-09-18 03:29:45 +00002328/// SemaConvertVectorExpr - Handle __builtin_convertvector
2329ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2330 SourceLocation BuiltinLoc,
2331 SourceLocation RParenLoc) {
2332 ExprValueKind VK = VK_RValue;
2333 ExprObjectKind OK = OK_Ordinary;
2334 QualType DstTy = TInfo->getType();
2335 QualType SrcTy = E->getType();
2336
2337 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2338 return ExprError(Diag(BuiltinLoc,
2339 diag::err_convertvector_non_vector)
2340 << E->getSourceRange());
2341 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2342 return ExprError(Diag(BuiltinLoc,
2343 diag::err_convertvector_non_vector_type));
2344
2345 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2346 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2347 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2348 if (SrcElts != DstElts)
2349 return ExprError(Diag(BuiltinLoc,
2350 diag::err_convertvector_incompatible_vector)
2351 << E->getSourceRange());
2352 }
2353
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002354 return new (Context)
2355 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002356}
2357
Daniel Dunbarb7257262008-07-21 22:59:13 +00002358/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2359// This is declared to take (const void*, ...) and can take two
2360// optional constant int args.
2361bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002362 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002363
Chris Lattner3b054132008-11-19 05:08:23 +00002364 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002365 return Diag(TheCall->getLocEnd(),
2366 diag::err_typecheck_call_too_many_args_at_most)
2367 << 0 /*function call*/ << 3 << NumArgs
2368 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002369
2370 // Argument 0 is checked for us and the remaining arguments must be
2371 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002372 for (unsigned i = 1; i != NumArgs; ++i)
2373 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002374 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002375
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002376 return false;
2377}
2378
Hal Finkelf0417332014-07-17 14:25:55 +00002379/// SemaBuiltinAssume - Handle __assume (MS Extension).
2380// __assume does not evaluate its arguments, and should warn if its argument
2381// has side effects.
2382bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2383 Expr *Arg = TheCall->getArg(0);
2384 if (Arg->isInstantiationDependent()) return false;
2385
2386 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002387 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002388 << Arg->getSourceRange()
2389 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2390
2391 return false;
2392}
2393
2394/// Handle __builtin_assume_aligned. This is declared
2395/// as (const void*, size_t, ...) and can take one optional constant int arg.
2396bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2397 unsigned NumArgs = TheCall->getNumArgs();
2398
2399 if (NumArgs > 3)
2400 return Diag(TheCall->getLocEnd(),
2401 diag::err_typecheck_call_too_many_args_at_most)
2402 << 0 /*function call*/ << 3 << NumArgs
2403 << TheCall->getSourceRange();
2404
2405 // The alignment must be a constant integer.
2406 Expr *Arg = TheCall->getArg(1);
2407
2408 // We can't check the value of a dependent argument.
2409 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2410 llvm::APSInt Result;
2411 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2412 return true;
2413
2414 if (!Result.isPowerOf2())
2415 return Diag(TheCall->getLocStart(),
2416 diag::err_alignment_not_power_of_two)
2417 << Arg->getSourceRange();
2418 }
2419
2420 if (NumArgs > 2) {
2421 ExprResult Arg(TheCall->getArg(2));
2422 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2423 Context.getSizeType(), false);
2424 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2425 if (Arg.isInvalid()) return true;
2426 TheCall->setArg(2, Arg.get());
2427 }
Hal Finkelf0417332014-07-17 14:25:55 +00002428
2429 return false;
2430}
2431
Eric Christopher8d0c6212010-04-17 02:26:23 +00002432/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2433/// TheCall is a constant expression.
2434bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2435 llvm::APSInt &Result) {
2436 Expr *Arg = TheCall->getArg(ArgNum);
2437 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2438 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2439
2440 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2441
2442 if (!Arg->isIntegerConstantExpr(Result, Context))
2443 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002444 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002445
Chris Lattnerd545ad12009-09-23 06:06:36 +00002446 return false;
2447}
2448
Richard Sandiford28940af2014-04-16 08:47:51 +00002449/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2450/// TheCall is a constant expression in the range [Low, High].
2451bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2452 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002453 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002454
2455 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002456 Expr *Arg = TheCall->getArg(ArgNum);
2457 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002458 return false;
2459
Eric Christopher8d0c6212010-04-17 02:26:23 +00002460 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002461 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002462 return true;
2463
Richard Sandiford28940af2014-04-16 08:47:51 +00002464 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002465 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002466 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002467
2468 return false;
2469}
2470
Eli Friedmanc97d0142009-05-03 06:04:26 +00002471/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002472/// This checks that the target supports __builtin_longjmp and
2473/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002474bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002475 if (!Context.getTargetInfo().hasSjLjLowering())
2476 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2477 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2478
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002479 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002480 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002481
Eric Christopher8d0c6212010-04-17 02:26:23 +00002482 // TODO: This is less than ideal. Overload this to take a value.
2483 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2484 return true;
2485
2486 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002487 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2488 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2489
2490 return false;
2491}
2492
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002493
2494/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2495/// This checks that the target supports __builtin_setjmp.
2496bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2497 if (!Context.getTargetInfo().hasSjLjLowering())
2498 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2499 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2500 return false;
2501}
2502
Richard Smithd7293d72013-08-05 18:49:43 +00002503namespace {
2504enum StringLiteralCheckType {
2505 SLCT_NotALiteral,
2506 SLCT_UncheckedLiteral,
2507 SLCT_CheckedLiteral
2508};
2509}
2510
Richard Smith55ce3522012-06-25 20:30:08 +00002511// Determine if an expression is a string literal or constant string.
2512// If this function returns false on the arguments to a function expecting a
2513// format string, we will usually need to emit a warning.
2514// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002515static StringLiteralCheckType
2516checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2517 bool HasVAListArg, unsigned format_idx,
2518 unsigned firstDataArg, Sema::FormatStringType Type,
2519 Sema::VariadicCallType CallType, bool InFunctionCall,
2520 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002521 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002522 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002523 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002524
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002525 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002526
Richard Smithd7293d72013-08-05 18:49:43 +00002527 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002528 // Technically -Wformat-nonliteral does not warn about this case.
2529 // The behavior of printf and friends in this case is implementation
2530 // dependent. Ideally if the format string cannot be null then
2531 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002532 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002533
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002534 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002535 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002536 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002537 // The expression is a literal if both sub-expressions were, and it was
2538 // completely checked only if both sub-expressions were checked.
2539 const AbstractConditionalOperator *C =
2540 cast<AbstractConditionalOperator>(E);
2541 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002542 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002543 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002544 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002545 if (Left == SLCT_NotALiteral)
2546 return SLCT_NotALiteral;
2547 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002548 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002549 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002550 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002551 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002552 }
2553
2554 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002555 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2556 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002557 }
2558
John McCallc07a0c72011-02-17 10:25:35 +00002559 case Stmt::OpaqueValueExprClass:
2560 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2561 E = src;
2562 goto tryAgain;
2563 }
Richard Smith55ce3522012-06-25 20:30:08 +00002564 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002565
Ted Kremeneka8890832011-02-24 23:03:04 +00002566 case Stmt::PredefinedExprClass:
2567 // While __func__, etc., are technically not string literals, they
2568 // cannot contain format specifiers and thus are not a security
2569 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002570 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002571
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002572 case Stmt::DeclRefExprClass: {
2573 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002574
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002575 // As an exception, do not flag errors for variables binding to
2576 // const string literals.
2577 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2578 bool isConstant = false;
2579 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002580
Richard Smithd7293d72013-08-05 18:49:43 +00002581 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2582 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002583 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002584 isConstant = T.isConstant(S.Context) &&
2585 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002586 } else if (T->isObjCObjectPointerType()) {
2587 // In ObjC, there is usually no "const ObjectPointer" type,
2588 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002589 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002590 }
Mike Stump11289f42009-09-09 15:08:12 +00002591
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002592 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002593 if (const Expr *Init = VD->getAnyInitializer()) {
2594 // Look through initializers like const char c[] = { "foo" }
2595 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2596 if (InitList->isStringLiteralInit())
2597 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2598 }
Richard Smithd7293d72013-08-05 18:49:43 +00002599 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002600 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002601 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002602 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002603 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002604 }
Mike Stump11289f42009-09-09 15:08:12 +00002605
Anders Carlssonb012ca92009-06-28 19:55:58 +00002606 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2607 // special check to see if the format string is a function parameter
2608 // of the function calling the printf function. If the function
2609 // has an attribute indicating it is a printf-like function, then we
2610 // should suppress warnings concerning non-literals being used in a call
2611 // to a vprintf function. For example:
2612 //
2613 // void
2614 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2615 // va_list ap;
2616 // va_start(ap, fmt);
2617 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2618 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002619 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002620 if (HasVAListArg) {
2621 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2622 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2623 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002624 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002625 // adjust for implicit parameter
2626 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2627 if (MD->isInstance())
2628 ++PVIndex;
2629 // We also check if the formats are compatible.
2630 // We can't pass a 'scanf' string to a 'printf' function.
2631 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002632 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002633 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002634 }
2635 }
2636 }
2637 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002638 }
Mike Stump11289f42009-09-09 15:08:12 +00002639
Richard Smith55ce3522012-06-25 20:30:08 +00002640 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002641 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002642
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002643 case Stmt::CallExprClass:
2644 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002645 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002646 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2647 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2648 unsigned ArgIndex = FA->getFormatIdx();
2649 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2650 if (MD->isInstance())
2651 --ArgIndex;
2652 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002653
Richard Smithd7293d72013-08-05 18:49:43 +00002654 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002655 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002656 Type, CallType, InFunctionCall,
2657 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002658 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2659 unsigned BuiltinID = FD->getBuiltinID();
2660 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2661 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2662 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002663 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002664 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002665 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002666 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002667 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002668 }
2669 }
Mike Stump11289f42009-09-09 15:08:12 +00002670
Richard Smith55ce3522012-06-25 20:30:08 +00002671 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002672 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002673 case Stmt::ObjCStringLiteralClass:
2674 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002675 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002676
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002677 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002678 StrE = ObjCFExpr->getString();
2679 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002680 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002681
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002682 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002683 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2684 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002685 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002686 }
Mike Stump11289f42009-09-09 15:08:12 +00002687
Richard Smith55ce3522012-06-25 20:30:08 +00002688 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002689 }
Mike Stump11289f42009-09-09 15:08:12 +00002690
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002691 default:
Richard Smith55ce3522012-06-25 20:30:08 +00002692 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002693 }
2694}
2695
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002696Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00002697 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002698 .Case("scanf", FST_Scanf)
2699 .Cases("printf", "printf0", FST_Printf)
2700 .Cases("NSString", "CFString", FST_NSString)
2701 .Case("strftime", FST_Strftime)
2702 .Case("strfmon", FST_Strfmon)
2703 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00002704 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00002705 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002706 .Default(FST_Unknown);
2707}
2708
Jordan Rose3e0ec582012-07-19 18:10:23 +00002709/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00002710/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002711/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002712bool Sema::CheckFormatArguments(const FormatAttr *Format,
2713 ArrayRef<const Expr *> Args,
2714 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002715 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002716 SourceLocation Loc, SourceRange Range,
2717 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00002718 FormatStringInfo FSI;
2719 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002720 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00002721 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00002722 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002723 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002724}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00002725
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002726bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002727 bool HasVAListArg, unsigned format_idx,
2728 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002729 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002730 SourceLocation Loc, SourceRange Range,
2731 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00002732 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002733 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002734 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00002735 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002736 }
Mike Stump11289f42009-09-09 15:08:12 +00002737
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002738 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002739
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002740 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00002741 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002742 // Dynamically generated format strings are difficult to
2743 // automatically vet at compile time. Requiring that format strings
2744 // are string literals: (1) permits the checking of format strings by
2745 // the compiler and thereby (2) can practically remove the source of
2746 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00002747
Mike Stump11289f42009-09-09 15:08:12 +00002748 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00002749 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00002750 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00002751 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00002752 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00002753 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2754 format_idx, firstDataArg, Type, CallType,
2755 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002756 if (CT != SLCT_NotALiteral)
2757 // Literal format string found, check done!
2758 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00002759
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002760 // Strftime is particular as it always uses a single 'time' argument,
2761 // so it is safe to pass a non-literal string.
2762 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00002763 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00002764
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002765 // Do not emit diag when the string param is a macro expansion and the
2766 // format is either NSString or CFString. This is a hack to prevent
2767 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2768 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00002769 if (Type == FST_NSString &&
2770 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00002771 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00002772
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002773 // If there are no arguments specified, warn with -Wformat-security, otherwise
2774 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00002775 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002776 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002777 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002778 << OrigFormatExpr->getSourceRange();
2779 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00002780 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002781 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00002782 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00002783 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002784}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00002785
Ted Kremenekab278de2010-01-28 23:39:18 +00002786namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00002787class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2788protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00002789 Sema &S;
2790 const StringLiteral *FExpr;
2791 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002792 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00002793 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00002794 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00002795 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002796 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00002797 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00002798 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00002799 bool usesPositionalArgs;
2800 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00002801 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00002802 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00002803 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002804public:
Ted Kremenek02087932010-07-16 02:11:22 +00002805 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00002806 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002807 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002808 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002809 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00002810 Sema::VariadicCallType callType,
2811 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00002812 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002813 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2814 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00002815 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002816 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00002817 inFunctionCall(inFunctionCall), CallType(callType),
2818 CheckedVarArgs(CheckedVarArgs) {
2819 CoveredArgs.resize(numDataArgs);
2820 CoveredArgs.reset();
2821 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002822
Ted Kremenek019d2242010-01-29 01:50:07 +00002823 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002824
Ted Kremenek02087932010-07-16 02:11:22 +00002825 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00002826 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002827
Jordan Rose92303592012-09-08 04:00:03 +00002828 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002829 const analyze_format_string::FormatSpecifier &FS,
2830 const analyze_format_string::ConversionSpecifier &CS,
2831 const char *startSpecifier, unsigned specifierLen,
2832 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00002833
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002834 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002835 const analyze_format_string::FormatSpecifier &FS,
2836 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002837
2838 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00002839 const analyze_format_string::ConversionSpecifier &CS,
2840 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002841
Craig Toppere14c0f82014-03-12 04:55:44 +00002842 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00002843
Craig Toppere14c0f82014-03-12 04:55:44 +00002844 void HandleInvalidPosition(const char *startSpecifier,
2845 unsigned specifierLen,
2846 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002847
Craig Toppere14c0f82014-03-12 04:55:44 +00002848 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00002849
Craig Toppere14c0f82014-03-12 04:55:44 +00002850 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002851
Richard Trieu03cf7b72011-10-28 00:41:25 +00002852 template <typename Range>
2853 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2854 const Expr *ArgumentExpr,
2855 PartialDiagnostic PDiag,
2856 SourceLocation StringLoc,
2857 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002858 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002859
Ted Kremenek02087932010-07-16 02:11:22 +00002860protected:
Ted Kremenekce815422010-07-19 21:25:57 +00002861 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2862 const char *startSpec,
2863 unsigned specifierLen,
2864 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002865
2866 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2867 const char *startSpec,
2868 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002869
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002870 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00002871 CharSourceRange getSpecifierRange(const char *startSpecifier,
2872 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00002873 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002874
Ted Kremenek5739de72010-01-29 01:06:55 +00002875 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002876
2877 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2878 const analyze_format_string::ConversionSpecifier &CS,
2879 const char *startSpecifier, unsigned specifierLen,
2880 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00002881
2882 template <typename Range>
2883 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2884 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00002885 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00002886};
2887}
2888
Ted Kremenek02087932010-07-16 02:11:22 +00002889SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00002890 return OrigFormatExpr->getSourceRange();
2891}
2892
Ted Kremenek02087932010-07-16 02:11:22 +00002893CharSourceRange CheckFormatHandler::
2894getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00002895 SourceLocation Start = getLocationOfByte(startSpecifier);
2896 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
2897
2898 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00002899 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00002900
2901 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00002902}
2903
Ted Kremenek02087932010-07-16 02:11:22 +00002904SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002905 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00002906}
2907
Ted Kremenek02087932010-07-16 02:11:22 +00002908void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2909 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00002910 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2911 getLocationOfByte(startSpecifier),
2912 /*IsStringLocation*/true,
2913 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00002914}
2915
Jordan Rose92303592012-09-08 04:00:03 +00002916void CheckFormatHandler::HandleInvalidLengthModifier(
2917 const analyze_format_string::FormatSpecifier &FS,
2918 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00002919 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00002920 using namespace analyze_format_string;
2921
2922 const LengthModifier &LM = FS.getLengthModifier();
2923 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2924
2925 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002926 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00002927 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002928 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002929 getLocationOfByte(LM.getStart()),
2930 /*IsStringLocation*/true,
2931 getSpecifierRange(startSpecifier, specifierLen));
2932
2933 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2934 << FixedLM->toString()
2935 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2936
2937 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002938 FixItHint Hint;
2939 if (DiagID == diag::warn_format_nonsensical_length)
2940 Hint = FixItHint::CreateRemoval(LMRange);
2941
2942 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00002943 getLocationOfByte(LM.getStart()),
2944 /*IsStringLocation*/true,
2945 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00002946 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00002947 }
2948}
2949
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002950void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00002951 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002952 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00002953 using namespace analyze_format_string;
2954
2955 const LengthModifier &LM = FS.getLengthModifier();
2956 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2957
2958 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00002959 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00002960 if (FixedLM) {
2961 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2962 << LM.toString() << 0,
2963 getLocationOfByte(LM.getStart()),
2964 /*IsStringLocation*/true,
2965 getSpecifierRange(startSpecifier, specifierLen));
2966
2967 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2968 << FixedLM->toString()
2969 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2970
2971 } else {
2972 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2973 << LM.toString() << 0,
2974 getLocationOfByte(LM.getStart()),
2975 /*IsStringLocation*/true,
2976 getSpecifierRange(startSpecifier, specifierLen));
2977 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00002978}
2979
2980void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2981 const analyze_format_string::ConversionSpecifier &CS,
2982 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00002983 using namespace analyze_format_string;
2984
2985 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00002986 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00002987 if (FixedCS) {
2988 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2989 << CS.toString() << /*conversion specifier*/1,
2990 getLocationOfByte(CS.getStart()),
2991 /*IsStringLocation*/true,
2992 getSpecifierRange(startSpecifier, specifierLen));
2993
2994 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2995 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2996 << FixedCS->toString()
2997 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2998 } else {
2999 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3000 << CS.toString() << /*conversion specifier*/1,
3001 getLocationOfByte(CS.getStart()),
3002 /*IsStringLocation*/true,
3003 getSpecifierRange(startSpecifier, specifierLen));
3004 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003005}
3006
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003007void CheckFormatHandler::HandlePosition(const char *startPos,
3008 unsigned posLen) {
3009 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3010 getLocationOfByte(startPos),
3011 /*IsStringLocation*/true,
3012 getSpecifierRange(startPos, posLen));
3013}
3014
Ted Kremenekd1668192010-02-27 01:41:03 +00003015void
Ted Kremenek02087932010-07-16 02:11:22 +00003016CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3017 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003018 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3019 << (unsigned) p,
3020 getLocationOfByte(startPos), /*IsStringLocation*/true,
3021 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003022}
3023
Ted Kremenek02087932010-07-16 02:11:22 +00003024void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003025 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003026 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3027 getLocationOfByte(startPos),
3028 /*IsStringLocation*/true,
3029 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003030}
3031
Ted Kremenek02087932010-07-16 02:11:22 +00003032void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003033 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003034 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003035 EmitFormatDiagnostic(
3036 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3037 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3038 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003039 }
Ted Kremenek02087932010-07-16 02:11:22 +00003040}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003041
Jordan Rose58bbe422012-07-19 18:10:08 +00003042// Note that this may return NULL if there was an error parsing or building
3043// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003044const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003045 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003046}
3047
3048void CheckFormatHandler::DoneProcessing() {
3049 // Does the number of data arguments exceed the number of
3050 // format conversions in the format string?
3051 if (!HasVAListArg) {
3052 // Find any arguments that weren't covered.
3053 CoveredArgs.flip();
3054 signed notCoveredArg = CoveredArgs.find_first();
3055 if (notCoveredArg >= 0) {
3056 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003057 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3058 SourceLocation Loc = E->getLocStart();
3059 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3060 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3061 Loc, /*IsStringLocation*/false,
3062 getFormatStringRange());
3063 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003064 }
Ted Kremenek02087932010-07-16 02:11:22 +00003065 }
3066 }
3067}
3068
Ted Kremenekce815422010-07-19 21:25:57 +00003069bool
3070CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3071 SourceLocation Loc,
3072 const char *startSpec,
3073 unsigned specifierLen,
3074 const char *csStart,
3075 unsigned csLen) {
3076
3077 bool keepGoing = true;
3078 if (argIndex < NumDataArgs) {
3079 // Consider the argument coverered, even though the specifier doesn't
3080 // make sense.
3081 CoveredArgs.set(argIndex);
3082 }
3083 else {
3084 // If argIndex exceeds the number of data arguments we
3085 // don't issue a warning because that is just a cascade of warnings (and
3086 // they may have intended '%%' anyway). We don't want to continue processing
3087 // the format string after this point, however, as we will like just get
3088 // gibberish when trying to match arguments.
3089 keepGoing = false;
3090 }
3091
Richard Trieu03cf7b72011-10-28 00:41:25 +00003092 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3093 << StringRef(csStart, csLen),
3094 Loc, /*IsStringLocation*/true,
3095 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003096
3097 return keepGoing;
3098}
3099
Richard Trieu03cf7b72011-10-28 00:41:25 +00003100void
3101CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3102 const char *startSpec,
3103 unsigned specifierLen) {
3104 EmitFormatDiagnostic(
3105 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3106 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3107}
3108
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003109bool
3110CheckFormatHandler::CheckNumArgs(
3111 const analyze_format_string::FormatSpecifier &FS,
3112 const analyze_format_string::ConversionSpecifier &CS,
3113 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3114
3115 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003116 PartialDiagnostic PDiag = FS.usesPositionalArg()
3117 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3118 << (argIndex+1) << NumDataArgs)
3119 : S.PDiag(diag::warn_printf_insufficient_data_args);
3120 EmitFormatDiagnostic(
3121 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3122 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003123 return false;
3124 }
3125 return true;
3126}
3127
Richard Trieu03cf7b72011-10-28 00:41:25 +00003128template<typename Range>
3129void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3130 SourceLocation Loc,
3131 bool IsStringLocation,
3132 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003133 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003134 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003135 Loc, IsStringLocation, StringRange, FixIt);
3136}
3137
3138/// \brief If the format string is not within the funcion call, emit a note
3139/// so that the function call and string are in diagnostic messages.
3140///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003141/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003142/// call and only one diagnostic message will be produced. Otherwise, an
3143/// extra note will be emitted pointing to location of the format string.
3144///
3145/// \param ArgumentExpr the expression that is passed as the format string
3146/// argument in the function call. Used for getting locations when two
3147/// diagnostics are emitted.
3148///
3149/// \param PDiag the callee should already have provided any strings for the
3150/// diagnostic message. This function only adds locations and fixits
3151/// to diagnostics.
3152///
3153/// \param Loc primary location for diagnostic. If two diagnostics are
3154/// required, one will be at Loc and a new SourceLocation will be created for
3155/// the other one.
3156///
3157/// \param IsStringLocation if true, Loc points to the format string should be
3158/// used for the note. Otherwise, Loc points to the argument list and will
3159/// be used with PDiag.
3160///
3161/// \param StringRange some or all of the string to highlight. This is
3162/// templated so it can accept either a CharSourceRange or a SourceRange.
3163///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003164/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003165template<typename Range>
3166void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3167 const Expr *ArgumentExpr,
3168 PartialDiagnostic PDiag,
3169 SourceLocation Loc,
3170 bool IsStringLocation,
3171 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003172 ArrayRef<FixItHint> FixIt) {
3173 if (InFunctionCall) {
3174 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3175 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003176 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003177 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003178 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3179 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003180
3181 const Sema::SemaDiagnosticBuilder &Note =
3182 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3183 diag::note_format_string_defined);
3184
3185 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003186 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003187 }
3188}
3189
Ted Kremenek02087932010-07-16 02:11:22 +00003190//===--- CHECK: Printf format string checking ------------------------------===//
3191
3192namespace {
3193class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003194 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003195public:
3196 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3197 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003198 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003199 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003200 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003201 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003202 Sema::VariadicCallType CallType,
3203 llvm::SmallBitVector &CheckedVarArgs)
3204 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3205 numDataArgs, beg, hasVAListArg, Args,
3206 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3207 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003208 {}
3209
Craig Toppere14c0f82014-03-12 04:55:44 +00003210
Ted Kremenek02087932010-07-16 02:11:22 +00003211 bool HandleInvalidPrintfConversionSpecifier(
3212 const analyze_printf::PrintfSpecifier &FS,
3213 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003214 unsigned specifierLen) override;
3215
Ted Kremenek02087932010-07-16 02:11:22 +00003216 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3217 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003218 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003219 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3220 const char *StartSpecifier,
3221 unsigned SpecifierLen,
3222 const Expr *E);
3223
Ted Kremenek02087932010-07-16 02:11:22 +00003224 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3225 const char *startSpecifier, unsigned specifierLen);
3226 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3227 const analyze_printf::OptionalAmount &Amt,
3228 unsigned type,
3229 const char *startSpecifier, unsigned specifierLen);
3230 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3231 const analyze_printf::OptionalFlag &flag,
3232 const char *startSpecifier, unsigned specifierLen);
3233 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3234 const analyze_printf::OptionalFlag &ignoredFlag,
3235 const analyze_printf::OptionalFlag &flag,
3236 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003237 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003238 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003239
Ted Kremenek02087932010-07-16 02:11:22 +00003240};
3241}
3242
3243bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3244 const analyze_printf::PrintfSpecifier &FS,
3245 const char *startSpecifier,
3246 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003247 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003248 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003249
Ted Kremenekce815422010-07-19 21:25:57 +00003250 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3251 getLocationOfByte(CS.getStart()),
3252 startSpecifier, specifierLen,
3253 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003254}
3255
Ted Kremenek02087932010-07-16 02:11:22 +00003256bool CheckPrintfHandler::HandleAmount(
3257 const analyze_format_string::OptionalAmount &Amt,
3258 unsigned k, const char *startSpecifier,
3259 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003260
3261 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003262 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003263 unsigned argIndex = Amt.getArgIndex();
3264 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003265 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3266 << k,
3267 getLocationOfByte(Amt.getStart()),
3268 /*IsStringLocation*/true,
3269 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003270 // Don't do any more checking. We will just emit
3271 // spurious errors.
3272 return false;
3273 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003274
Ted Kremenek5739de72010-01-29 01:06:55 +00003275 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003276 // Although not in conformance with C99, we also allow the argument to be
3277 // an 'unsigned int' as that is a reasonably safe case. GCC also
3278 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003279 CoveredArgs.set(argIndex);
3280 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003281 if (!Arg)
3282 return false;
3283
Ted Kremenek5739de72010-01-29 01:06:55 +00003284 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003285
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003286 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3287 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003288
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003289 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003290 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003291 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003292 << T << Arg->getSourceRange(),
3293 getLocationOfByte(Amt.getStart()),
3294 /*IsStringLocation*/true,
3295 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003296 // Don't do any more checking. We will just emit
3297 // spurious errors.
3298 return false;
3299 }
3300 }
3301 }
3302 return true;
3303}
Ted Kremenek5739de72010-01-29 01:06:55 +00003304
Tom Careb49ec692010-06-17 19:00:27 +00003305void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003306 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003307 const analyze_printf::OptionalAmount &Amt,
3308 unsigned type,
3309 const char *startSpecifier,
3310 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003311 const analyze_printf::PrintfConversionSpecifier &CS =
3312 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003313
Richard Trieu03cf7b72011-10-28 00:41:25 +00003314 FixItHint fixit =
3315 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3316 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3317 Amt.getConstantLength()))
3318 : FixItHint();
3319
3320 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3321 << type << CS.toString(),
3322 getLocationOfByte(Amt.getStart()),
3323 /*IsStringLocation*/true,
3324 getSpecifierRange(startSpecifier, specifierLen),
3325 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003326}
3327
Ted Kremenek02087932010-07-16 02:11:22 +00003328void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003329 const analyze_printf::OptionalFlag &flag,
3330 const char *startSpecifier,
3331 unsigned specifierLen) {
3332 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003333 const analyze_printf::PrintfConversionSpecifier &CS =
3334 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003335 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3336 << flag.toString() << CS.toString(),
3337 getLocationOfByte(flag.getPosition()),
3338 /*IsStringLocation*/true,
3339 getSpecifierRange(startSpecifier, specifierLen),
3340 FixItHint::CreateRemoval(
3341 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003342}
3343
3344void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003345 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003346 const analyze_printf::OptionalFlag &ignoredFlag,
3347 const analyze_printf::OptionalFlag &flag,
3348 const char *startSpecifier,
3349 unsigned specifierLen) {
3350 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003351 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3352 << ignoredFlag.toString() << flag.toString(),
3353 getLocationOfByte(ignoredFlag.getPosition()),
3354 /*IsStringLocation*/true,
3355 getSpecifierRange(startSpecifier, specifierLen),
3356 FixItHint::CreateRemoval(
3357 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003358}
3359
Richard Smith55ce3522012-06-25 20:30:08 +00003360// Determines if the specified is a C++ class or struct containing
3361// a member with the specified name and kind (e.g. a CXXMethodDecl named
3362// "c_str()").
3363template<typename MemberKind>
3364static llvm::SmallPtrSet<MemberKind*, 1>
3365CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3366 const RecordType *RT = Ty->getAs<RecordType>();
3367 llvm::SmallPtrSet<MemberKind*, 1> Results;
3368
3369 if (!RT)
3370 return Results;
3371 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003372 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003373 return Results;
3374
Alp Tokerb6cc5922014-05-03 03:45:55 +00003375 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003376 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003377 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003378
3379 // We just need to include all members of the right kind turned up by the
3380 // filter, at this point.
3381 if (S.LookupQualifiedName(R, RT->getDecl()))
3382 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3383 NamedDecl *decl = (*I)->getUnderlyingDecl();
3384 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3385 Results.insert(FK);
3386 }
3387 return Results;
3388}
3389
Richard Smith2868a732014-02-28 01:36:39 +00003390/// Check if we could call '.c_str()' on an object.
3391///
3392/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3393/// allow the call, or if it would be ambiguous).
3394bool Sema::hasCStrMethod(const Expr *E) {
3395 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3396 MethodSet Results =
3397 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3398 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3399 MI != ME; ++MI)
3400 if ((*MI)->getMinRequiredArguments() == 0)
3401 return true;
3402 return false;
3403}
3404
Richard Smith55ce3522012-06-25 20:30:08 +00003405// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003406// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003407// Returns true when a c_str() conversion method is found.
3408bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003409 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003410 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3411
3412 MethodSet Results =
3413 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3414
3415 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3416 MI != ME; ++MI) {
3417 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003418 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003419 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003420 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003421 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003422 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3423 << "c_str()"
3424 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3425 return true;
3426 }
3427 }
3428
3429 return false;
3430}
3431
Ted Kremenekab278de2010-01-28 23:39:18 +00003432bool
Ted Kremenek02087932010-07-16 02:11:22 +00003433CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003434 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003435 const char *startSpecifier,
3436 unsigned specifierLen) {
3437
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003438 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003439 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003440 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003441
Ted Kremenek6cd69422010-07-19 22:01:06 +00003442 if (FS.consumesDataArgument()) {
3443 if (atFirstArg) {
3444 atFirstArg = false;
3445 usesPositionalArgs = FS.usesPositionalArg();
3446 }
3447 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003448 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3449 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003450 return false;
3451 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003452 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003453
Ted Kremenekd1668192010-02-27 01:41:03 +00003454 // First check if the field width, precision, and conversion specifier
3455 // have matching data arguments.
3456 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3457 startSpecifier, specifierLen)) {
3458 return false;
3459 }
3460
3461 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3462 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003463 return false;
3464 }
3465
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003466 if (!CS.consumesDataArgument()) {
3467 // FIXME: Technically specifying a precision or field width here
3468 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003469 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003470 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003471
Ted Kremenek4a49d982010-02-26 19:18:41 +00003472 // Consume the argument.
3473 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003474 if (argIndex < NumDataArgs) {
3475 // The check to see if the argIndex is valid will come later.
3476 // We set the bit here because we may exit early from this
3477 // function if we encounter some other error.
3478 CoveredArgs.set(argIndex);
3479 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003480
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003481 // FreeBSD kernel extensions.
3482 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3483 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3484 // We need at least two arguments.
3485 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3486 return false;
3487
3488 // Claim the second argument.
3489 CoveredArgs.set(argIndex + 1);
3490
3491 // Type check the first argument (int for %b, pointer for %D)
3492 const Expr *Ex = getDataArg(argIndex);
3493 const analyze_printf::ArgType &AT =
3494 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3495 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3496 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3497 EmitFormatDiagnostic(
3498 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3499 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3500 << false << Ex->getSourceRange(),
3501 Ex->getLocStart(), /*IsStringLocation*/false,
3502 getSpecifierRange(startSpecifier, specifierLen));
3503
3504 // Type check the second argument (char * for both %b and %D)
3505 Ex = getDataArg(argIndex + 1);
3506 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3507 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3508 EmitFormatDiagnostic(
3509 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3510 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3511 << false << Ex->getSourceRange(),
3512 Ex->getLocStart(), /*IsStringLocation*/false,
3513 getSpecifierRange(startSpecifier, specifierLen));
3514
3515 return true;
3516 }
3517
Ted Kremenek4a49d982010-02-26 19:18:41 +00003518 // Check for using an Objective-C specific conversion specifier
3519 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003520 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003521 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3522 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003523 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003524
Tom Careb49ec692010-06-17 19:00:27 +00003525 // Check for invalid use of field width
3526 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003527 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003528 startSpecifier, specifierLen);
3529 }
3530
3531 // Check for invalid use of precision
3532 if (!FS.hasValidPrecision()) {
3533 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3534 startSpecifier, specifierLen);
3535 }
3536
3537 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003538 if (!FS.hasValidThousandsGroupingPrefix())
3539 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003540 if (!FS.hasValidLeadingZeros())
3541 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3542 if (!FS.hasValidPlusPrefix())
3543 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003544 if (!FS.hasValidSpacePrefix())
3545 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003546 if (!FS.hasValidAlternativeForm())
3547 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3548 if (!FS.hasValidLeftJustified())
3549 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3550
3551 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003552 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3553 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3554 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003555 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3556 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3557 startSpecifier, specifierLen);
3558
3559 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003560 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003561 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3562 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003563 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003564 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003565 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003566 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3567 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003568
Jordan Rose92303592012-09-08 04:00:03 +00003569 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3570 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3571
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003572 // The remaining checks depend on the data arguments.
3573 if (HasVAListArg)
3574 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003575
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003576 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003577 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003578
Jordan Rose58bbe422012-07-19 18:10:08 +00003579 const Expr *Arg = getDataArg(argIndex);
3580 if (!Arg)
3581 return true;
3582
3583 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003584}
3585
Jordan Roseaee34382012-09-05 22:56:26 +00003586static bool requiresParensToAddCast(const Expr *E) {
3587 // FIXME: We should have a general way to reason about operator
3588 // precedence and whether parens are actually needed here.
3589 // Take care of a few common cases where they aren't.
3590 const Expr *Inside = E->IgnoreImpCasts();
3591 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3592 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3593
3594 switch (Inside->getStmtClass()) {
3595 case Stmt::ArraySubscriptExprClass:
3596 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003597 case Stmt::CharacterLiteralClass:
3598 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003599 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003600 case Stmt::FloatingLiteralClass:
3601 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003602 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003603 case Stmt::ObjCArrayLiteralClass:
3604 case Stmt::ObjCBoolLiteralExprClass:
3605 case Stmt::ObjCBoxedExprClass:
3606 case Stmt::ObjCDictionaryLiteralClass:
3607 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003608 case Stmt::ObjCIvarRefExprClass:
3609 case Stmt::ObjCMessageExprClass:
3610 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003611 case Stmt::ObjCStringLiteralClass:
3612 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003613 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003614 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003615 case Stmt::UnaryOperatorClass:
3616 return false;
3617 default:
3618 return true;
3619 }
3620}
3621
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003622static std::pair<QualType, StringRef>
3623shouldNotPrintDirectly(const ASTContext &Context,
3624 QualType IntendedTy,
3625 const Expr *E) {
3626 // Use a 'while' to peel off layers of typedefs.
3627 QualType TyTy = IntendedTy;
3628 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3629 StringRef Name = UserTy->getDecl()->getName();
3630 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3631 .Case("NSInteger", Context.LongTy)
3632 .Case("NSUInteger", Context.UnsignedLongTy)
3633 .Case("SInt32", Context.IntTy)
3634 .Case("UInt32", Context.UnsignedIntTy)
3635 .Default(QualType());
3636
3637 if (!CastTy.isNull())
3638 return std::make_pair(CastTy, Name);
3639
3640 TyTy = UserTy->desugar();
3641 }
3642
3643 // Strip parens if necessary.
3644 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3645 return shouldNotPrintDirectly(Context,
3646 PE->getSubExpr()->getType(),
3647 PE->getSubExpr());
3648
3649 // If this is a conditional expression, then its result type is constructed
3650 // via usual arithmetic conversions and thus there might be no necessary
3651 // typedef sugar there. Recurse to operands to check for NSInteger &
3652 // Co. usage condition.
3653 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3654 QualType TrueTy, FalseTy;
3655 StringRef TrueName, FalseName;
3656
3657 std::tie(TrueTy, TrueName) =
3658 shouldNotPrintDirectly(Context,
3659 CO->getTrueExpr()->getType(),
3660 CO->getTrueExpr());
3661 std::tie(FalseTy, FalseName) =
3662 shouldNotPrintDirectly(Context,
3663 CO->getFalseExpr()->getType(),
3664 CO->getFalseExpr());
3665
3666 if (TrueTy == FalseTy)
3667 return std::make_pair(TrueTy, TrueName);
3668 else if (TrueTy.isNull())
3669 return std::make_pair(FalseTy, FalseName);
3670 else if (FalseTy.isNull())
3671 return std::make_pair(TrueTy, TrueName);
3672 }
3673
3674 return std::make_pair(QualType(), StringRef());
3675}
3676
Richard Smith55ce3522012-06-25 20:30:08 +00003677bool
3678CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3679 const char *StartSpecifier,
3680 unsigned SpecifierLen,
3681 const Expr *E) {
3682 using namespace analyze_format_string;
3683 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003684 // Now type check the data expression that matches the
3685 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003686 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3687 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00003688 if (!AT.isValid())
3689 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00003690
Jordan Rose598ec092012-12-05 18:44:40 +00003691 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00003692 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3693 ExprTy = TET->getUnderlyingExpr()->getType();
3694 }
3695
Seth Cantrellb4802962015-03-04 03:12:10 +00003696 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
3697
3698 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00003699 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00003700 }
Jordan Rose98709982012-06-04 22:48:57 +00003701
Jordan Rose22b74712012-09-05 22:56:19 +00003702 // Look through argument promotions for our error message's reported type.
3703 // This includes the integral and floating promotions, but excludes array
3704 // and function pointer decay; seeing that an argument intended to be a
3705 // string has type 'char [6]' is probably more confusing than 'char *'.
3706 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3707 if (ICE->getCastKind() == CK_IntegralCast ||
3708 ICE->getCastKind() == CK_FloatingCast) {
3709 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00003710 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00003711
3712 // Check if we didn't match because of an implicit cast from a 'char'
3713 // or 'short' to an 'int'. This is done because printf is a varargs
3714 // function.
3715 if (ICE->getType() == S.Context.IntTy ||
3716 ICE->getType() == S.Context.UnsignedIntTy) {
3717 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00003718 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00003719 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00003720 }
Jordan Rose98709982012-06-04 22:48:57 +00003721 }
Jordan Rose598ec092012-12-05 18:44:40 +00003722 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3723 // Special case for 'a', which has type 'int' in C.
3724 // Note, however, that we do /not/ want to treat multibyte constants like
3725 // 'MooV' as characters! This form is deprecated but still exists.
3726 if (ExprTy == S.Context.IntTy)
3727 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3728 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00003729 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003730
Jordan Rosebc53ed12014-05-31 04:12:14 +00003731 // Look through enums to their underlying type.
3732 bool IsEnum = false;
3733 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3734 ExprTy = EnumTy->getDecl()->getIntegerType();
3735 IsEnum = true;
3736 }
3737
Jordan Rose0e5badd2012-12-05 18:44:49 +00003738 // %C in an Objective-C context prints a unichar, not a wchar_t.
3739 // If the argument is an integer of some kind, believe the %C and suggest
3740 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00003741 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003742 if (ObjCContext &&
3743 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3744 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3745 !ExprTy->isCharType()) {
3746 // 'unichar' is defined as a typedef of unsigned short, but we should
3747 // prefer using the typedef if it is visible.
3748 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00003749
3750 // While we are here, check if the value is an IntegerLiteral that happens
3751 // to be within the valid range.
3752 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3753 const llvm::APInt &V = IL->getValue();
3754 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3755 return true;
3756 }
3757
Jordan Rose0e5badd2012-12-05 18:44:49 +00003758 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3759 Sema::LookupOrdinaryName);
3760 if (S.LookupName(Result, S.getCurScope())) {
3761 NamedDecl *ND = Result.getFoundDecl();
3762 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3763 if (TD->getUnderlyingType() == IntendedTy)
3764 IntendedTy = S.Context.getTypedefType(TD);
3765 }
3766 }
3767 }
3768
3769 // Special-case some of Darwin's platform-independence types by suggesting
3770 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003771 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00003772 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003773 QualType CastTy;
3774 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3775 if (!CastTy.isNull()) {
3776 IntendedTy = CastTy;
3777 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00003778 }
3779 }
3780
Jordan Rose22b74712012-09-05 22:56:19 +00003781 // We may be able to offer a FixItHint if it is a supported type.
3782 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00003783 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00003784 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003785
Jordan Rose22b74712012-09-05 22:56:19 +00003786 if (success) {
3787 // Get the fix string from the fixed format specifier
3788 SmallString<16> buf;
3789 llvm::raw_svector_ostream os(buf);
3790 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003791
Jordan Roseaee34382012-09-05 22:56:26 +00003792 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3793
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003794 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00003795 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3796 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
3797 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3798 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00003799 // In this case, the specifier is wrong and should be changed to match
3800 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00003801 EmitFormatDiagnostic(S.PDiag(diag)
3802 << AT.getRepresentativeTypeName(S.Context)
3803 << IntendedTy << IsEnum << E->getSourceRange(),
3804 E->getLocStart(),
3805 /*IsStringLocation*/ false, SpecRange,
3806 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00003807
3808 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00003809 // The canonical type for formatting this value is different from the
3810 // actual type of the expression. (This occurs, for example, with Darwin's
3811 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3812 // should be printed as 'long' for 64-bit compatibility.)
3813 // Rather than emitting a normal format/argument mismatch, we want to
3814 // add a cast to the recommended type (and correct the format string
3815 // if necessary).
3816 SmallString<16> CastBuf;
3817 llvm::raw_svector_ostream CastFix(CastBuf);
3818 CastFix << "(";
3819 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3820 CastFix << ")";
3821
3822 SmallVector<FixItHint,4> Hints;
3823 if (!AT.matchesType(S.Context, IntendedTy))
3824 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3825
3826 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3827 // If there's already a cast present, just replace it.
3828 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3829 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3830
3831 } else if (!requiresParensToAddCast(E)) {
3832 // If the expression has high enough precedence,
3833 // just write the C-style cast.
3834 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3835 CastFix.str()));
3836 } else {
3837 // Otherwise, add parens around the expression as well as the cast.
3838 CastFix << "(";
3839 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3840 CastFix.str()));
3841
Alp Tokerb6cc5922014-05-03 03:45:55 +00003842 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00003843 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3844 }
3845
Jordan Rose0e5badd2012-12-05 18:44:49 +00003846 if (ShouldNotPrintDirectly) {
3847 // The expression has a type that should not be printed directly.
3848 // We extract the name from the typedef because we don't want to show
3849 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003850 StringRef Name;
3851 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3852 Name = TypedefTy->getDecl()->getName();
3853 else
3854 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00003855 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00003856 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003857 << E->getSourceRange(),
3858 E->getLocStart(), /*IsStringLocation=*/false,
3859 SpecRange, Hints);
3860 } else {
3861 // In this case, the expression could be printed using a different
3862 // specifier, but we've decided that the specifier is probably correct
3863 // and we should cast instead. Just use the normal warning message.
3864 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00003865 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3866 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00003867 << E->getSourceRange(),
3868 E->getLocStart(), /*IsStringLocation*/false,
3869 SpecRange, Hints);
3870 }
Jordan Roseaee34382012-09-05 22:56:26 +00003871 }
Jordan Rose22b74712012-09-05 22:56:19 +00003872 } else {
3873 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3874 SpecifierLen);
3875 // Since the warning for passing non-POD types to variadic functions
3876 // was deferred until now, we emit a warning for non-POD
3877 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00003878 switch (S.isValidVarArgType(ExprTy)) {
3879 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00003880 case Sema::VAK_ValidInCXX11: {
3881 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
3882 if (match == analyze_printf::ArgType::NoMatchPedantic) {
3883 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
3884 }
Richard Smithd7293d72013-08-05 18:49:43 +00003885
Seth Cantrellb4802962015-03-04 03:12:10 +00003886 EmitFormatDiagnostic(
3887 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
3888 << IsEnum << CSR << E->getSourceRange(),
3889 E->getLocStart(), /*IsStringLocation*/ false, CSR);
3890 break;
3891 }
Richard Smithd7293d72013-08-05 18:49:43 +00003892 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00003893 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00003894 EmitFormatDiagnostic(
3895 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003896 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00003897 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00003898 << CallType
3899 << AT.getRepresentativeTypeName(S.Context)
3900 << CSR
3901 << E->getSourceRange(),
3902 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00003903 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00003904 break;
3905
3906 case Sema::VAK_Invalid:
3907 if (ExprTy->isObjCObjectType())
3908 EmitFormatDiagnostic(
3909 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3910 << S.getLangOpts().CPlusPlus11
3911 << ExprTy
3912 << CallType
3913 << AT.getRepresentativeTypeName(S.Context)
3914 << CSR
3915 << E->getSourceRange(),
3916 E->getLocStart(), /*IsStringLocation*/false, CSR);
3917 else
3918 // FIXME: If this is an initializer list, suggest removing the braces
3919 // or inserting a cast to the target type.
3920 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3921 << isa<InitListExpr>(E) << ExprTy << CallType
3922 << AT.getRepresentativeTypeName(S.Context)
3923 << E->getSourceRange();
3924 break;
3925 }
3926
3927 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3928 "format string specifier index out of range");
3929 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003930 }
3931
Ted Kremenekab278de2010-01-28 23:39:18 +00003932 return true;
3933}
3934
Ted Kremenek02087932010-07-16 02:11:22 +00003935//===--- CHECK: Scanf format string checking ------------------------------===//
3936
3937namespace {
3938class CheckScanfHandler : public CheckFormatHandler {
3939public:
3940 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3941 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003942 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003943 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003944 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003945 Sema::VariadicCallType CallType,
3946 llvm::SmallBitVector &CheckedVarArgs)
3947 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3948 numDataArgs, beg, hasVAListArg,
3949 Args, formatIdx, inFunctionCall, CallType,
3950 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003951 {}
Ted Kremenek02087932010-07-16 02:11:22 +00003952
3953 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3954 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003955 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00003956
3957 bool HandleInvalidScanfConversionSpecifier(
3958 const analyze_scanf::ScanfSpecifier &FS,
3959 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003960 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003961
Craig Toppere14c0f82014-03-12 04:55:44 +00003962 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00003963};
Ted Kremenek019d2242010-01-29 01:50:07 +00003964}
Ted Kremenekab278de2010-01-28 23:39:18 +00003965
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003966void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3967 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003968 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3969 getLocationOfByte(end), /*IsStringLocation*/true,
3970 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00003971}
3972
Ted Kremenekce815422010-07-19 21:25:57 +00003973bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3974 const analyze_scanf::ScanfSpecifier &FS,
3975 const char *startSpecifier,
3976 unsigned specifierLen) {
3977
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003978 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003979 FS.getConversionSpecifier();
3980
3981 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3982 getLocationOfByte(CS.getStart()),
3983 startSpecifier, specifierLen,
3984 CS.getStart(), CS.getLength());
3985}
3986
Ted Kremenek02087932010-07-16 02:11:22 +00003987bool CheckScanfHandler::HandleScanfSpecifier(
3988 const analyze_scanf::ScanfSpecifier &FS,
3989 const char *startSpecifier,
3990 unsigned specifierLen) {
3991
3992 using namespace analyze_scanf;
3993 using namespace analyze_format_string;
3994
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003995 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003996
Ted Kremenek6cd69422010-07-19 22:01:06 +00003997 // Handle case where '%' and '*' don't consume an argument. These shouldn't
3998 // be used to decide if we are using positional arguments consistently.
3999 if (FS.consumesDataArgument()) {
4000 if (atFirstArg) {
4001 atFirstArg = false;
4002 usesPositionalArgs = FS.usesPositionalArg();
4003 }
4004 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4006 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004007 return false;
4008 }
Ted Kremenek02087932010-07-16 02:11:22 +00004009 }
4010
4011 // Check if the field with is non-zero.
4012 const OptionalAmount &Amt = FS.getFieldWidth();
4013 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4014 if (Amt.getConstantAmount() == 0) {
4015 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4016 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004017 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4018 getLocationOfByte(Amt.getStart()),
4019 /*IsStringLocation*/true, R,
4020 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004021 }
4022 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004023
Ted Kremenek02087932010-07-16 02:11:22 +00004024 if (!FS.consumesDataArgument()) {
4025 // FIXME: Technically specifying a precision or field width here
4026 // makes no sense. Worth issuing a warning at some point.
4027 return true;
4028 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004029
Ted Kremenek02087932010-07-16 02:11:22 +00004030 // Consume the argument.
4031 unsigned argIndex = FS.getArgIndex();
4032 if (argIndex < NumDataArgs) {
4033 // The check to see if the argIndex is valid will come later.
4034 // We set the bit here because we may exit early from this
4035 // function if we encounter some other error.
4036 CoveredArgs.set(argIndex);
4037 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004038
Ted Kremenek4407ea42010-07-20 20:04:47 +00004039 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004040 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004041 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4042 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004043 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004044 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004045 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004046 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4047 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004048
Jordan Rose92303592012-09-08 04:00:03 +00004049 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4050 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4051
Ted Kremenek02087932010-07-16 02:11:22 +00004052 // The remaining checks depend on the data arguments.
4053 if (HasVAListArg)
4054 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004055
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004056 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004057 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004058
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004059 // Check that the argument type matches the format specifier.
4060 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004061 if (!Ex)
4062 return true;
4063
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004064 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004065
4066 if (!AT.isValid()) {
4067 return true;
4068 }
4069
Seth Cantrellb4802962015-03-04 03:12:10 +00004070 analyze_format_string::ArgType::MatchKind match =
4071 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004072 if (match == analyze_format_string::ArgType::Match) {
4073 return true;
4074 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004075
Seth Cantrell79340072015-03-04 05:58:08 +00004076 ScanfSpecifier fixedFS = FS;
4077 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4078 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004079
Seth Cantrell79340072015-03-04 05:58:08 +00004080 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4081 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4082 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4083 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004084
Seth Cantrell79340072015-03-04 05:58:08 +00004085 if (success) {
4086 // Get the fix string from the fixed format specifier.
4087 SmallString<128> buf;
4088 llvm::raw_svector_ostream os(buf);
4089 fixedFS.toString(os);
4090
4091 EmitFormatDiagnostic(
4092 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4093 << Ex->getType() << false << Ex->getSourceRange(),
4094 Ex->getLocStart(),
4095 /*IsStringLocation*/ false,
4096 getSpecifierRange(startSpecifier, specifierLen),
4097 FixItHint::CreateReplacement(
4098 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4099 } else {
4100 EmitFormatDiagnostic(S.PDiag(diag)
4101 << AT.getRepresentativeTypeName(S.Context)
4102 << Ex->getType() << false << Ex->getSourceRange(),
4103 Ex->getLocStart(),
4104 /*IsStringLocation*/ false,
4105 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004106 }
4107
Ted Kremenek02087932010-07-16 02:11:22 +00004108 return true;
4109}
4110
4111void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004112 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004113 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004114 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004115 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004116 bool inFunctionCall, VariadicCallType CallType,
4117 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004118
Ted Kremenekab278de2010-01-28 23:39:18 +00004119 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004120 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004121 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004122 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004123 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4124 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004125 return;
4126 }
Ted Kremenek02087932010-07-16 02:11:22 +00004127
Ted Kremenekab278de2010-01-28 23:39:18 +00004128 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004129 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004130 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004131 // Account for cases where the string literal is truncated in a declaration.
4132 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4133 assert(T && "String literal not of constant array type!");
4134 size_t TypeSize = T->getSize().getZExtValue();
4135 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004136 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004137
4138 // Emit a warning if the string literal is truncated and does not contain an
4139 // embedded null character.
4140 if (TypeSize <= StrRef.size() &&
4141 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4142 CheckFormatHandler::EmitFormatDiagnostic(
4143 *this, inFunctionCall, Args[format_idx],
4144 PDiag(diag::warn_printf_format_string_not_null_terminated),
4145 FExpr->getLocStart(),
4146 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4147 return;
4148 }
4149
Ted Kremenekab278de2010-01-28 23:39:18 +00004150 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004151 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004152 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004153 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004154 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4155 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004156 return;
4157 }
Ted Kremenek02087932010-07-16 02:11:22 +00004158
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004159 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004160 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004161 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004162 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004163 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004164 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004165
Hans Wennborg23926bd2011-12-15 10:25:47 +00004166 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004167 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004168 Context.getTargetInfo(),
4169 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004170 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004171 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004172 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004173 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004174 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004175
Hans Wennborg23926bd2011-12-15 10:25:47 +00004176 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004177 getLangOpts(),
4178 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004179 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004180 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004181}
4182
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004183bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4184 // Str - The format string. NOTE: this is NOT null-terminated!
4185 StringRef StrRef = FExpr->getString();
4186 const char *Str = StrRef.data();
4187 // Account for cases where the string literal is truncated in a declaration.
4188 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4189 assert(T && "String literal not of constant array type!");
4190 size_t TypeSize = T->getSize().getZExtValue();
4191 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4192 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4193 getLangOpts(),
4194 Context.getTargetInfo());
4195}
4196
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004197//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4198
4199// Returns the related absolute value function that is larger, of 0 if one
4200// does not exist.
4201static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4202 switch (AbsFunction) {
4203 default:
4204 return 0;
4205
4206 case Builtin::BI__builtin_abs:
4207 return Builtin::BI__builtin_labs;
4208 case Builtin::BI__builtin_labs:
4209 return Builtin::BI__builtin_llabs;
4210 case Builtin::BI__builtin_llabs:
4211 return 0;
4212
4213 case Builtin::BI__builtin_fabsf:
4214 return Builtin::BI__builtin_fabs;
4215 case Builtin::BI__builtin_fabs:
4216 return Builtin::BI__builtin_fabsl;
4217 case Builtin::BI__builtin_fabsl:
4218 return 0;
4219
4220 case Builtin::BI__builtin_cabsf:
4221 return Builtin::BI__builtin_cabs;
4222 case Builtin::BI__builtin_cabs:
4223 return Builtin::BI__builtin_cabsl;
4224 case Builtin::BI__builtin_cabsl:
4225 return 0;
4226
4227 case Builtin::BIabs:
4228 return Builtin::BIlabs;
4229 case Builtin::BIlabs:
4230 return Builtin::BIllabs;
4231 case Builtin::BIllabs:
4232 return 0;
4233
4234 case Builtin::BIfabsf:
4235 return Builtin::BIfabs;
4236 case Builtin::BIfabs:
4237 return Builtin::BIfabsl;
4238 case Builtin::BIfabsl:
4239 return 0;
4240
4241 case Builtin::BIcabsf:
4242 return Builtin::BIcabs;
4243 case Builtin::BIcabs:
4244 return Builtin::BIcabsl;
4245 case Builtin::BIcabsl:
4246 return 0;
4247 }
4248}
4249
4250// Returns the argument type of the absolute value function.
4251static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4252 unsigned AbsType) {
4253 if (AbsType == 0)
4254 return QualType();
4255
4256 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4257 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4258 if (Error != ASTContext::GE_None)
4259 return QualType();
4260
4261 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4262 if (!FT)
4263 return QualType();
4264
4265 if (FT->getNumParams() != 1)
4266 return QualType();
4267
4268 return FT->getParamType(0);
4269}
4270
4271// Returns the best absolute value function, or zero, based on type and
4272// current absolute value function.
4273static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4274 unsigned AbsFunctionKind) {
4275 unsigned BestKind = 0;
4276 uint64_t ArgSize = Context.getTypeSize(ArgType);
4277 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4278 Kind = getLargerAbsoluteValueFunction(Kind)) {
4279 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4280 if (Context.getTypeSize(ParamType) >= ArgSize) {
4281 if (BestKind == 0)
4282 BestKind = Kind;
4283 else if (Context.hasSameType(ParamType, ArgType)) {
4284 BestKind = Kind;
4285 break;
4286 }
4287 }
4288 }
4289 return BestKind;
4290}
4291
4292enum AbsoluteValueKind {
4293 AVK_Integer,
4294 AVK_Floating,
4295 AVK_Complex
4296};
4297
4298static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4299 if (T->isIntegralOrEnumerationType())
4300 return AVK_Integer;
4301 if (T->isRealFloatingType())
4302 return AVK_Floating;
4303 if (T->isAnyComplexType())
4304 return AVK_Complex;
4305
4306 llvm_unreachable("Type not integer, floating, or complex");
4307}
4308
4309// Changes the absolute value function to a different type. Preserves whether
4310// the function is a builtin.
4311static unsigned changeAbsFunction(unsigned AbsKind,
4312 AbsoluteValueKind ValueKind) {
4313 switch (ValueKind) {
4314 case AVK_Integer:
4315 switch (AbsKind) {
4316 default:
4317 return 0;
4318 case Builtin::BI__builtin_fabsf:
4319 case Builtin::BI__builtin_fabs:
4320 case Builtin::BI__builtin_fabsl:
4321 case Builtin::BI__builtin_cabsf:
4322 case Builtin::BI__builtin_cabs:
4323 case Builtin::BI__builtin_cabsl:
4324 return Builtin::BI__builtin_abs;
4325 case Builtin::BIfabsf:
4326 case Builtin::BIfabs:
4327 case Builtin::BIfabsl:
4328 case Builtin::BIcabsf:
4329 case Builtin::BIcabs:
4330 case Builtin::BIcabsl:
4331 return Builtin::BIabs;
4332 }
4333 case AVK_Floating:
4334 switch (AbsKind) {
4335 default:
4336 return 0;
4337 case Builtin::BI__builtin_abs:
4338 case Builtin::BI__builtin_labs:
4339 case Builtin::BI__builtin_llabs:
4340 case Builtin::BI__builtin_cabsf:
4341 case Builtin::BI__builtin_cabs:
4342 case Builtin::BI__builtin_cabsl:
4343 return Builtin::BI__builtin_fabsf;
4344 case Builtin::BIabs:
4345 case Builtin::BIlabs:
4346 case Builtin::BIllabs:
4347 case Builtin::BIcabsf:
4348 case Builtin::BIcabs:
4349 case Builtin::BIcabsl:
4350 return Builtin::BIfabsf;
4351 }
4352 case AVK_Complex:
4353 switch (AbsKind) {
4354 default:
4355 return 0;
4356 case Builtin::BI__builtin_abs:
4357 case Builtin::BI__builtin_labs:
4358 case Builtin::BI__builtin_llabs:
4359 case Builtin::BI__builtin_fabsf:
4360 case Builtin::BI__builtin_fabs:
4361 case Builtin::BI__builtin_fabsl:
4362 return Builtin::BI__builtin_cabsf;
4363 case Builtin::BIabs:
4364 case Builtin::BIlabs:
4365 case Builtin::BIllabs:
4366 case Builtin::BIfabsf:
4367 case Builtin::BIfabs:
4368 case Builtin::BIfabsl:
4369 return Builtin::BIcabsf;
4370 }
4371 }
4372 llvm_unreachable("Unable to convert function");
4373}
4374
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004375static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004376 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4377 if (!FnInfo)
4378 return 0;
4379
4380 switch (FDecl->getBuiltinID()) {
4381 default:
4382 return 0;
4383 case Builtin::BI__builtin_abs:
4384 case Builtin::BI__builtin_fabs:
4385 case Builtin::BI__builtin_fabsf:
4386 case Builtin::BI__builtin_fabsl:
4387 case Builtin::BI__builtin_labs:
4388 case Builtin::BI__builtin_llabs:
4389 case Builtin::BI__builtin_cabs:
4390 case Builtin::BI__builtin_cabsf:
4391 case Builtin::BI__builtin_cabsl:
4392 case Builtin::BIabs:
4393 case Builtin::BIlabs:
4394 case Builtin::BIllabs:
4395 case Builtin::BIfabs:
4396 case Builtin::BIfabsf:
4397 case Builtin::BIfabsl:
4398 case Builtin::BIcabs:
4399 case Builtin::BIcabsf:
4400 case Builtin::BIcabsl:
4401 return FDecl->getBuiltinID();
4402 }
4403 llvm_unreachable("Unknown Builtin type");
4404}
4405
4406// If the replacement is valid, emit a note with replacement function.
4407// Additionally, suggest including the proper header if not already included.
4408static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004409 unsigned AbsKind, QualType ArgType) {
4410 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004411 const char *HeaderName = nullptr;
4412 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004413 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4414 FunctionName = "std::abs";
4415 if (ArgType->isIntegralOrEnumerationType()) {
4416 HeaderName = "cstdlib";
4417 } else if (ArgType->isRealFloatingType()) {
4418 HeaderName = "cmath";
4419 } else {
4420 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004421 }
Richard Trieubeffb832014-04-15 23:47:53 +00004422
4423 // Lookup all std::abs
4424 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004425 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004426 R.suppressDiagnostics();
4427 S.LookupQualifiedName(R, Std);
4428
4429 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004430 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004431 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4432 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4433 } else {
4434 FDecl = dyn_cast<FunctionDecl>(I);
4435 }
4436 if (!FDecl)
4437 continue;
4438
4439 // Found std::abs(), check that they are the right ones.
4440 if (FDecl->getNumParams() != 1)
4441 continue;
4442
4443 // Check that the parameter type can handle the argument.
4444 QualType ParamType = FDecl->getParamDecl(0)->getType();
4445 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4446 S.Context.getTypeSize(ArgType) <=
4447 S.Context.getTypeSize(ParamType)) {
4448 // Found a function, don't need the header hint.
4449 EmitHeaderHint = false;
4450 break;
4451 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004452 }
Richard Trieubeffb832014-04-15 23:47:53 +00004453 }
4454 } else {
4455 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4456 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4457
4458 if (HeaderName) {
4459 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4460 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4461 R.suppressDiagnostics();
4462 S.LookupName(R, S.getCurScope());
4463
4464 if (R.isSingleResult()) {
4465 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4466 if (FD && FD->getBuiltinID() == AbsKind) {
4467 EmitHeaderHint = false;
4468 } else {
4469 return;
4470 }
4471 } else if (!R.empty()) {
4472 return;
4473 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004474 }
4475 }
4476
4477 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004478 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004479
Richard Trieubeffb832014-04-15 23:47:53 +00004480 if (!HeaderName)
4481 return;
4482
4483 if (!EmitHeaderHint)
4484 return;
4485
Alp Toker5d96e0a2014-07-11 20:53:51 +00004486 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4487 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004488}
4489
4490static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4491 if (!FDecl)
4492 return false;
4493
4494 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4495 return false;
4496
4497 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4498
4499 while (ND && ND->isInlineNamespace()) {
4500 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004501 }
Richard Trieubeffb832014-04-15 23:47:53 +00004502
4503 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4504 return false;
4505
4506 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4507 return false;
4508
4509 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004510}
4511
4512// Warn when using the wrong abs() function.
4513void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4514 const FunctionDecl *FDecl,
4515 IdentifierInfo *FnInfo) {
4516 if (Call->getNumArgs() != 1)
4517 return;
4518
4519 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004520 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4521 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004522 return;
4523
4524 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4525 QualType ParamType = Call->getArg(0)->getType();
4526
Alp Toker5d96e0a2014-07-11 20:53:51 +00004527 // Unsigned types cannot be negative. Suggest removing the absolute value
4528 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004529 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004530 const char *FunctionName =
4531 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004532 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4533 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004534 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004535 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4536 return;
4537 }
4538
Richard Trieubeffb832014-04-15 23:47:53 +00004539 // std::abs has overloads which prevent most of the absolute value problems
4540 // from occurring.
4541 if (IsStdAbs)
4542 return;
4543
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004544 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4545 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4546
4547 // The argument and parameter are the same kind. Check if they are the right
4548 // size.
4549 if (ArgValueKind == ParamValueKind) {
4550 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4551 return;
4552
4553 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4554 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4555 << FDecl << ArgType << ParamType;
4556
4557 if (NewAbsKind == 0)
4558 return;
4559
4560 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004561 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004562 return;
4563 }
4564
4565 // ArgValueKind != ParamValueKind
4566 // The wrong type of absolute value function was used. Attempt to find the
4567 // proper one.
4568 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4569 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4570 if (NewAbsKind == 0)
4571 return;
4572
4573 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4574 << FDecl << ParamValueKind << ArgValueKind;
4575
4576 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004577 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004578 return;
4579}
4580
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004581//===--- CHECK: Standard memory functions ---------------------------------===//
4582
Nico Weber0e6daef2013-12-26 23:38:39 +00004583/// \brief Takes the expression passed to the size_t parameter of functions
4584/// such as memcmp, strncat, etc and warns if it's a comparison.
4585///
4586/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4587static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4588 IdentifierInfo *FnName,
4589 SourceLocation FnLoc,
4590 SourceLocation RParenLoc) {
4591 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4592 if (!Size)
4593 return false;
4594
4595 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4596 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4597 return false;
4598
Nico Weber0e6daef2013-12-26 23:38:39 +00004599 SourceRange SizeRange = Size->getSourceRange();
4600 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4601 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004602 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004603 << FnName << FixItHint::CreateInsertion(
4604 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004605 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004606 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004607 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004608 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4609 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004610
4611 return true;
4612}
4613
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004614/// \brief Determine whether the given type is or contains a dynamic class type
4615/// (e.g., whether it has a vtable).
4616static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4617 bool &IsContained) {
4618 // Look through array types while ignoring qualifiers.
4619 const Type *Ty = T->getBaseElementTypeUnsafe();
4620 IsContained = false;
4621
4622 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4623 RD = RD ? RD->getDefinition() : nullptr;
4624 if (!RD)
4625 return nullptr;
4626
4627 if (RD->isDynamicClass())
4628 return RD;
4629
4630 // Check all the fields. If any bases were dynamic, the class is dynamic.
4631 // It's impossible for a class to transitively contain itself by value, so
4632 // infinite recursion is impossible.
4633 for (auto *FD : RD->fields()) {
4634 bool SubContained;
4635 if (const CXXRecordDecl *ContainedRD =
4636 getContainedDynamicClass(FD->getType(), SubContained)) {
4637 IsContained = true;
4638 return ContainedRD;
4639 }
4640 }
4641
4642 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004643}
4644
Chandler Carruth889ed862011-06-21 23:04:20 +00004645/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004646/// otherwise returns NULL.
4647static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004648 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004649 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4650 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4651 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004652
Craig Topperc3ec1492014-05-26 06:22:03 +00004653 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004654}
4655
Chandler Carruth889ed862011-06-21 23:04:20 +00004656/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004657static QualType getSizeOfArgType(const Expr* E) {
4658 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4659 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4660 if (SizeOf->getKind() == clang::UETT_SizeOf)
4661 return SizeOf->getTypeOfArgument();
4662
4663 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004664}
4665
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004666/// \brief Check for dangerous or invalid arguments to memset().
4667///
Chandler Carruthac687262011-06-03 06:23:57 +00004668/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004669/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4670/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004671///
4672/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004673void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004674 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004675 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004676 assert(BId != 0);
4677
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004678 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004679 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004680 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004681 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004682 return;
4683
Anna Zaks22122702012-01-17 00:37:07 +00004684 unsigned LastArg = (BId == Builtin::BImemset ||
4685 BId == Builtin::BIstrndup ? 1 : 2);
4686 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00004687 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004688
Nico Weber0e6daef2013-12-26 23:38:39 +00004689 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4690 Call->getLocStart(), Call->getRParenLoc()))
4691 return;
4692
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004693 // We have special checking when the length is a sizeof expression.
4694 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4695 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4696 llvm::FoldingSetNodeID SizeOfArgID;
4697
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004698 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4699 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004700 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004701
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004702 QualType DestTy = Dest->getType();
4703 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4704 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00004705
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004706 // Never warn about void type pointers. This can be used to suppress
4707 // false positives.
4708 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004709 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004710
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004711 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4712 // actually comparing the expressions for equality. Because computing the
4713 // expression IDs can be expensive, we only do this if the diagnostic is
4714 // enabled.
4715 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004716 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4717 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004718 // We only compute IDs for expressions if the warning is enabled, and
4719 // cache the sizeof arg's ID.
4720 if (SizeOfArgID == llvm::FoldingSetNodeID())
4721 SizeOfArg->Profile(SizeOfArgID, Context, true);
4722 llvm::FoldingSetNodeID DestID;
4723 Dest->Profile(DestID, Context, true);
4724 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00004725 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4726 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004727 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00004728 StringRef ReadableName = FnName->getName();
4729
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004730 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00004731 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004732 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00004733 if (!PointeeTy->isIncompleteType() &&
4734 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004735 ActionIdx = 2; // If the pointee's size is sizeof(char),
4736 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00004737
4738 // If the function is defined as a builtin macro, do not show macro
4739 // expansion.
4740 SourceLocation SL = SizeOfArg->getExprLoc();
4741 SourceRange DSR = Dest->getSourceRange();
4742 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004743 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00004744
4745 if (SM.isMacroArgExpansion(SL)) {
4746 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4747 SL = SM.getSpellingLoc(SL);
4748 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4749 SM.getSpellingLoc(DSR.getEnd()));
4750 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4751 SM.getSpellingLoc(SSR.getEnd()));
4752 }
4753
Anna Zaksd08d9152012-05-30 23:14:52 +00004754 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004755 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00004756 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00004757 << PointeeTy
4758 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00004759 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00004760 << SSR);
4761 DiagRuntimeBehavior(SL, SizeOfArg,
4762 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4763 << ActionIdx
4764 << SSR);
4765
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004766 break;
4767 }
4768 }
4769
4770 // Also check for cases where the sizeof argument is the exact same
4771 // type as the memory argument, and where it points to a user-defined
4772 // record type.
4773 if (SizeOfArgTy != QualType()) {
4774 if (PointeeTy->isRecordType() &&
4775 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4776 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4777 PDiag(diag::warn_sizeof_pointer_type_memaccess)
4778 << FnName << SizeOfArgTy << ArgIdx
4779 << PointeeTy << Dest->getSourceRange()
4780 << LenExpr->getSourceRange());
4781 break;
4782 }
Nico Weberc5e73862011-06-14 16:14:58 +00004783 }
4784
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004785 // Always complain about dynamic classes.
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004786 bool IsContained;
4787 if (const CXXRecordDecl *ContainedRD =
4788 getContainedDynamicClass(PointeeTy, IsContained)) {
Anna Zaks22122702012-01-17 00:37:07 +00004789
4790 unsigned OperationType = 0;
4791 // "overwritten" if we're warning about the destination for any call
4792 // but memcmp; otherwise a verb appropriate to the call.
4793 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4794 if (BId == Builtin::BImemcpy)
4795 OperationType = 1;
4796 else if(BId == Builtin::BImemmove)
4797 OperationType = 2;
4798 else if (BId == Builtin::BImemcmp)
4799 OperationType = 3;
4800 }
4801
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004802 DiagRuntimeBehavior(
4803 Dest->getExprLoc(), Dest,
4804 PDiag(diag::warn_dyn_class_memaccess)
Anna Zaks22122702012-01-17 00:37:07 +00004805 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004806 << FnName << IsContained << ContainedRD << OperationType
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004807 << Call->getCallee()->getSourceRange());
Anna Zaks22122702012-01-17 00:37:07 +00004808 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4809 BId != Builtin::BImemset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00004810 DiagRuntimeBehavior(
4811 Dest->getExprLoc(), Dest,
4812 PDiag(diag::warn_arc_object_memaccess)
4813 << ArgIdx << FnName << PointeeTy
4814 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00004815 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004816 continue;
John McCall31168b02011-06-15 23:02:42 +00004817
4818 DiagRuntimeBehavior(
4819 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00004820 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00004821 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4822 break;
4823 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004824 }
4825}
4826
Ted Kremenek6865f772011-08-18 20:55:45 +00004827// A little helper routine: ignore addition and subtraction of integer literals.
4828// This intentionally does not ignore all integer constant expressions because
4829// we don't want to remove sizeof().
4830static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4831 Ex = Ex->IgnoreParenCasts();
4832
4833 for (;;) {
4834 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4835 if (!BO || !BO->isAdditiveOp())
4836 break;
4837
4838 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4839 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4840
4841 if (isa<IntegerLiteral>(RHS))
4842 Ex = LHS;
4843 else if (isa<IntegerLiteral>(LHS))
4844 Ex = RHS;
4845 else
4846 break;
4847 }
4848
4849 return Ex;
4850}
4851
Anna Zaks13b08572012-08-08 21:42:23 +00004852static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4853 ASTContext &Context) {
4854 // Only handle constant-sized or VLAs, but not flexible members.
4855 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4856 // Only issue the FIXIT for arrays of size > 1.
4857 if (CAT->getSize().getSExtValue() <= 1)
4858 return false;
4859 } else if (!Ty->isVariableArrayType()) {
4860 return false;
4861 }
4862 return true;
4863}
4864
Ted Kremenek6865f772011-08-18 20:55:45 +00004865// Warn if the user has made the 'size' argument to strlcpy or strlcat
4866// be the size of the source, instead of the destination.
4867void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4868 IdentifierInfo *FnName) {
4869
4870 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00004871 unsigned NumArgs = Call->getNumArgs();
4872 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00004873 return;
4874
4875 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4876 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004877 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00004878
4879 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4880 Call->getLocStart(), Call->getRParenLoc()))
4881 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00004882
4883 // Look for 'strlcpy(dst, x, sizeof(x))'
4884 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4885 CompareWithSrc = Ex;
4886 else {
4887 // Look for 'strlcpy(dst, x, strlen(x))'
4888 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00004889 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4890 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00004891 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4892 }
4893 }
4894
4895 if (!CompareWithSrc)
4896 return;
4897
4898 // Determine if the argument to sizeof/strlen is equal to the source
4899 // argument. In principle there's all kinds of things you could do
4900 // here, for instance creating an == expression and evaluating it with
4901 // EvaluateAsBooleanCondition, but this uses a more direct technique:
4902 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4903 if (!SrcArgDRE)
4904 return;
4905
4906 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4907 if (!CompareWithSrcDRE ||
4908 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4909 return;
4910
4911 const Expr *OriginalSizeArg = Call->getArg(2);
4912 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4913 << OriginalSizeArg->getSourceRange() << FnName;
4914
4915 // Output a FIXIT hint if the destination is an array (rather than a
4916 // pointer to an array). This could be enhanced to handle some
4917 // pointers if we know the actual size, like if DstArg is 'array+2'
4918 // we could say 'sizeof(array)-2'.
4919 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00004920 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00004921 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004922
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00004923 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00004924 llvm::raw_svector_ostream OS(sizeString);
4925 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00004926 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00004927 OS << ")";
4928
4929 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4930 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4931 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00004932}
4933
Anna Zaks314cd092012-02-01 19:08:57 +00004934/// Check if two expressions refer to the same declaration.
4935static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4936 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4937 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4938 return D1->getDecl() == D2->getDecl();
4939 return false;
4940}
4941
4942static const Expr *getStrlenExprArg(const Expr *E) {
4943 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4944 const FunctionDecl *FD = CE->getDirectCallee();
4945 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00004946 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004947 return CE->getArg(0)->IgnoreParenCasts();
4948 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004949 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00004950}
4951
4952// Warn on anti-patterns as the 'size' argument to strncat.
4953// The correct size argument should look like following:
4954// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4955void Sema::CheckStrncatArguments(const CallExpr *CE,
4956 IdentifierInfo *FnName) {
4957 // Don't crash if the user has the wrong number of arguments.
4958 if (CE->getNumArgs() < 3)
4959 return;
4960 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4961 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4962 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4963
Nico Weber0e6daef2013-12-26 23:38:39 +00004964 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4965 CE->getRParenLoc()))
4966 return;
4967
Anna Zaks314cd092012-02-01 19:08:57 +00004968 // Identify common expressions, which are wrongly used as the size argument
4969 // to strncat and may lead to buffer overflows.
4970 unsigned PatternType = 0;
4971 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4972 // - sizeof(dst)
4973 if (referToTheSameDecl(SizeOfArg, DstArg))
4974 PatternType = 1;
4975 // - sizeof(src)
4976 else if (referToTheSameDecl(SizeOfArg, SrcArg))
4977 PatternType = 2;
4978 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4979 if (BE->getOpcode() == BO_Sub) {
4980 const Expr *L = BE->getLHS()->IgnoreParenCasts();
4981 const Expr *R = BE->getRHS()->IgnoreParenCasts();
4982 // - sizeof(dst) - strlen(dst)
4983 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4984 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4985 PatternType = 1;
4986 // - sizeof(src) - (anything)
4987 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4988 PatternType = 2;
4989 }
4990 }
4991
4992 if (PatternType == 0)
4993 return;
4994
Anna Zaks5069aa32012-02-03 01:27:37 +00004995 // Generate the diagnostic.
4996 SourceLocation SL = LenArg->getLocStart();
4997 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00004998 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00004999
5000 // If the function is defined as a builtin macro, do not show macro expansion.
5001 if (SM.isMacroArgExpansion(SL)) {
5002 SL = SM.getSpellingLoc(SL);
5003 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5004 SM.getSpellingLoc(SR.getEnd()));
5005 }
5006
Anna Zaks13b08572012-08-08 21:42:23 +00005007 // Check if the destination is an array (rather than a pointer to an array).
5008 QualType DstTy = DstArg->getType();
5009 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5010 Context);
5011 if (!isKnownSizeArray) {
5012 if (PatternType == 1)
5013 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5014 else
5015 Diag(SL, diag::warn_strncat_src_size) << SR;
5016 return;
5017 }
5018
Anna Zaks314cd092012-02-01 19:08:57 +00005019 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005020 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005021 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005022 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005023
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005024 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005025 llvm::raw_svector_ostream OS(sizeString);
5026 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005027 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005028 OS << ") - ";
5029 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005030 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005031 OS << ") - 1";
5032
Anna Zaks5069aa32012-02-03 01:27:37 +00005033 Diag(SL, diag::note_strncat_wrong_size)
5034 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005035}
5036
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005037//===--- CHECK: Return Address of Stack Variable --------------------------===//
5038
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005039static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5040 Decl *ParentDecl);
5041static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5042 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005043
5044/// CheckReturnStackAddr - Check if a return statement returns the address
5045/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005046static void
5047CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5048 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005049
Craig Topperc3ec1492014-05-26 06:22:03 +00005050 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005051 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005052
5053 // Perform checking for returned stack addresses, local blocks,
5054 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005055 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005056 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005057 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005058 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005059 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005060 }
5061
Craig Topperc3ec1492014-05-26 06:22:03 +00005062 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005063 return; // Nothing suspicious was found.
5064
5065 SourceLocation diagLoc;
5066 SourceRange diagRange;
5067 if (refVars.empty()) {
5068 diagLoc = stackE->getLocStart();
5069 diagRange = stackE->getSourceRange();
5070 } else {
5071 // We followed through a reference variable. 'stackE' contains the
5072 // problematic expression but we will warn at the return statement pointing
5073 // at the reference variable. We will later display the "trail" of
5074 // reference variables using notes.
5075 diagLoc = refVars[0]->getLocStart();
5076 diagRange = refVars[0]->getSourceRange();
5077 }
5078
5079 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005080 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005081 : diag::warn_ret_stack_addr)
5082 << DR->getDecl()->getDeclName() << diagRange;
5083 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005084 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005085 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005086 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005087 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005088 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5089 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005090 << diagRange;
5091 }
5092
5093 // Display the "trail" of reference variables that we followed until we
5094 // found the problematic expression using notes.
5095 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5096 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5097 // If this var binds to another reference var, show the range of the next
5098 // var, otherwise the var binds to the problematic expression, in which case
5099 // show the range of the expression.
5100 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5101 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005102 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5103 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005104 }
5105}
5106
5107/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5108/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005109/// to a location on the stack, a local block, an address of a label, or a
5110/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005111/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005112/// encounter a subexpression that (1) clearly does not lead to one of the
5113/// above problematic expressions (2) is something we cannot determine leads to
5114/// a problematic expression based on such local checking.
5115///
5116/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5117/// the expression that they point to. Such variables are added to the
5118/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005119///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005120/// EvalAddr processes expressions that are pointers that are used as
5121/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005122/// At the base case of the recursion is a check for the above problematic
5123/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005124///
5125/// This implementation handles:
5126///
5127/// * pointer-to-pointer casts
5128/// * implicit conversions from array references to pointers
5129/// * taking the address of fields
5130/// * arbitrary interplay between "&" and "*" operators
5131/// * pointer arithmetic from an address of a stack variable
5132/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005133static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5134 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005135 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005136 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005137
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005138 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005139 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005140 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005141 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005142 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005143
Peter Collingbourne91147592011-04-15 00:35:48 +00005144 E = E->IgnoreParens();
5145
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005146 // Our "symbolic interpreter" is just a dispatch off the currently
5147 // viewed AST node. We then recursively traverse the AST by calling
5148 // EvalAddr and EvalVal appropriately.
5149 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005150 case Stmt::DeclRefExprClass: {
5151 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5152
Richard Smith40f08eb2014-01-30 22:05:38 +00005153 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005154 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005155 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005156
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005157 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5158 // If this is a reference variable, follow through to the expression that
5159 // it points to.
5160 if (V->hasLocalStorage() &&
5161 V->getType()->isReferenceType() && V->hasInit()) {
5162 // Add the reference variable to the "trail".
5163 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005164 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005165 }
5166
Craig Topperc3ec1492014-05-26 06:22:03 +00005167 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005168 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005169
Chris Lattner934edb22007-12-28 05:31:15 +00005170 case Stmt::UnaryOperatorClass: {
5171 // The only unary operator that make sense to handle here
5172 // is AddrOf. All others don't make sense as pointers.
5173 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005174
John McCalle3027922010-08-25 11:45:40 +00005175 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005176 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005177 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005178 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005179 }
Mike Stump11289f42009-09-09 15:08:12 +00005180
Chris Lattner934edb22007-12-28 05:31:15 +00005181 case Stmt::BinaryOperatorClass: {
5182 // Handle pointer arithmetic. All other binary operators are not valid
5183 // in this context.
5184 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005185 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005186
John McCalle3027922010-08-25 11:45:40 +00005187 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005188 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005189
Chris Lattner934edb22007-12-28 05:31:15 +00005190 Expr *Base = B->getLHS();
5191
5192 // Determine which argument is the real pointer base. It could be
5193 // the RHS argument instead of the LHS.
5194 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005195
Chris Lattner934edb22007-12-28 05:31:15 +00005196 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005197 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005198 }
Steve Naroff2752a172008-09-10 19:17:48 +00005199
Chris Lattner934edb22007-12-28 05:31:15 +00005200 // For conditional operators we need to see if either the LHS or RHS are
5201 // valid DeclRefExpr*s. If one of them is valid, we return it.
5202 case Stmt::ConditionalOperatorClass: {
5203 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005204
Chris Lattner934edb22007-12-28 05:31:15 +00005205 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005206 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5207 if (Expr *LHSExpr = C->getLHS()) {
5208 // In C++, we can have a throw-expression, which has 'void' type.
5209 if (!LHSExpr->getType()->isVoidType())
5210 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005211 return LHS;
5212 }
Chris Lattner934edb22007-12-28 05:31:15 +00005213
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005214 // In C++, we can have a throw-expression, which has 'void' type.
5215 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005216 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005217
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005218 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005219 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005220
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005221 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005222 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005223 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005224 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005225
5226 case Stmt::AddrLabelExprClass:
5227 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005228
John McCall28fc7092011-11-10 05:35:25 +00005229 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005230 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5231 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005232
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005233 // For casts, we need to handle conversions from arrays to
5234 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005235 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005236 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005237 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005238 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005239 case Stmt::CXXStaticCastExprClass:
5240 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005241 case Stmt::CXXConstCastExprClass:
5242 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005243 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5244 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005245 case CK_LValueToRValue:
5246 case CK_NoOp:
5247 case CK_BaseToDerived:
5248 case CK_DerivedToBase:
5249 case CK_UncheckedDerivedToBase:
5250 case CK_Dynamic:
5251 case CK_CPointerToObjCPointerCast:
5252 case CK_BlockPointerToObjCPointerCast:
5253 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005254 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005255
5256 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005257 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005258
Richard Trieudadefde2014-07-02 04:39:38 +00005259 case CK_BitCast:
5260 if (SubExpr->getType()->isAnyPointerType() ||
5261 SubExpr->getType()->isBlockPointerType() ||
5262 SubExpr->getType()->isObjCQualifiedIdType())
5263 return EvalAddr(SubExpr, refVars, ParentDecl);
5264 else
5265 return nullptr;
5266
Eli Friedman8195ad72012-02-23 23:04:32 +00005267 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005268 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005269 }
Chris Lattner934edb22007-12-28 05:31:15 +00005270 }
Mike Stump11289f42009-09-09 15:08:12 +00005271
Douglas Gregorfe314812011-06-21 17:03:29 +00005272 case Stmt::MaterializeTemporaryExprClass:
5273 if (Expr *Result = EvalAddr(
5274 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005275 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005276 return Result;
5277
5278 return E;
5279
Chris Lattner934edb22007-12-28 05:31:15 +00005280 // Everything else: we simply don't reason about them.
5281 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005282 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005283 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005284}
Mike Stump11289f42009-09-09 15:08:12 +00005285
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005286
5287/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5288/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005289static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5290 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005291do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005292 // We should only be called for evaluating non-pointer expressions, or
5293 // expressions with a pointer type that are not used as references but instead
5294 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005295
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005296 // Our "symbolic interpreter" is just a dispatch off the currently
5297 // viewed AST node. We then recursively traverse the AST by calling
5298 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005299
5300 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005301 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005302 case Stmt::ImplicitCastExprClass: {
5303 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005304 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005305 E = IE->getSubExpr();
5306 continue;
5307 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005308 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005309 }
5310
John McCall28fc7092011-11-10 05:35:25 +00005311 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005312 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005313
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005314 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005315 // When we hit a DeclRefExpr we are looking at code that refers to a
5316 // variable's name. If it's not a reference variable we check if it has
5317 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005318 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005319
Richard Smith40f08eb2014-01-30 22:05:38 +00005320 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005321 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005322 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005323
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005324 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5325 // Check if it refers to itself, e.g. "int& i = i;".
5326 if (V == ParentDecl)
5327 return DR;
5328
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005329 if (V->hasLocalStorage()) {
5330 if (!V->getType()->isReferenceType())
5331 return DR;
5332
5333 // Reference variable, follow through to the expression that
5334 // it points to.
5335 if (V->hasInit()) {
5336 // Add the reference variable to the "trail".
5337 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005338 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005339 }
5340 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005341 }
Mike Stump11289f42009-09-09 15:08:12 +00005342
Craig Topperc3ec1492014-05-26 06:22:03 +00005343 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005344 }
Mike Stump11289f42009-09-09 15:08:12 +00005345
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005346 case Stmt::UnaryOperatorClass: {
5347 // The only unary operator that make sense to handle here
5348 // is Deref. All others don't resolve to a "name." This includes
5349 // handling all sorts of rvalues passed to a unary operator.
5350 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005351
John McCalle3027922010-08-25 11:45:40 +00005352 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005353 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005354
Craig Topperc3ec1492014-05-26 06:22:03 +00005355 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005356 }
Mike Stump11289f42009-09-09 15:08:12 +00005357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005358 case Stmt::ArraySubscriptExprClass: {
5359 // Array subscripts are potential references to data on the stack. We
5360 // retrieve the DeclRefExpr* for the array variable if it indeed
5361 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005362 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005363 }
Mike Stump11289f42009-09-09 15:08:12 +00005364
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005365 case Stmt::ConditionalOperatorClass: {
5366 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005367 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005368 ConditionalOperator *C = cast<ConditionalOperator>(E);
5369
Anders Carlsson801c5c72007-11-30 19:04:31 +00005370 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005371 if (Expr *LHSExpr = C->getLHS()) {
5372 // In C++, we can have a throw-expression, which has 'void' type.
5373 if (!LHSExpr->getType()->isVoidType())
5374 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5375 return LHS;
5376 }
5377
5378 // In C++, we can have a throw-expression, which has 'void' type.
5379 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005380 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005381
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005382 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005383 }
Mike Stump11289f42009-09-09 15:08:12 +00005384
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005385 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005386 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005387 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005388
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005389 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005390 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005391 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005392
5393 // Check whether the member type is itself a reference, in which case
5394 // we're not going to refer to the member, but to what the member refers to.
5395 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005396 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005397
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005398 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005399 }
Mike Stump11289f42009-09-09 15:08:12 +00005400
Douglas Gregorfe314812011-06-21 17:03:29 +00005401 case Stmt::MaterializeTemporaryExprClass:
5402 if (Expr *Result = EvalVal(
5403 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005404 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005405 return Result;
5406
5407 return E;
5408
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005409 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005410 // Check that we don't return or take the address of a reference to a
5411 // temporary. This is only useful in C++.
5412 if (!E->isTypeDependent() && E->isRValue())
5413 return E;
5414
5415 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005416 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005417 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005418} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005419}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005420
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005421void
5422Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5423 SourceLocation ReturnLoc,
5424 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005425 const AttrVec *Attrs,
5426 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005427 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5428
5429 // Check if the return value is null but should not be.
Benjamin Kramerae852a62014-02-23 14:34:50 +00005430 if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5431 CheckNonNullExpr(*this, RetValExp))
5432 Diag(ReturnLoc, diag::warn_null_ret)
5433 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005434
5435 // C++11 [basic.stc.dynamic.allocation]p4:
5436 // If an allocation function declared with a non-throwing
5437 // exception-specification fails to allocate storage, it shall return
5438 // a null pointer. Any other allocation function that fails to allocate
5439 // storage shall indicate failure only by throwing an exception [...]
5440 if (FD) {
5441 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5442 if (Op == OO_New || Op == OO_Array_New) {
5443 const FunctionProtoType *Proto
5444 = FD->getType()->castAs<FunctionProtoType>();
5445 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5446 CheckNonNullExpr(*this, RetValExp))
5447 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5448 << FD << getLangOpts().CPlusPlus11;
5449 }
5450 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005451}
5452
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005453//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5454
5455/// Check for comparisons of floating point operands using != and ==.
5456/// Issue a warning if these are no self-comparisons, as they are not likely
5457/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005458void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005459 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5460 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005461
5462 // Special case: check for x == x (which is OK).
5463 // Do not emit warnings for such cases.
5464 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5465 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5466 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005467 return;
Mike Stump11289f42009-09-09 15:08:12 +00005468
5469
Ted Kremenekeda40e22007-11-29 00:59:04 +00005470 // Special case: check for comparisons against literals that can be exactly
5471 // represented by APFloat. In such cases, do not emit a warning. This
5472 // is a heuristic: often comparison against such literals are used to
5473 // detect if a value in a variable has not changed. This clearly can
5474 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005475 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5476 if (FLL->isExact())
5477 return;
5478 } else
5479 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5480 if (FLR->isExact())
5481 return;
Mike Stump11289f42009-09-09 15:08:12 +00005482
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005483 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005484 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005485 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005486 return;
Mike Stump11289f42009-09-09 15:08:12 +00005487
David Blaikie1f4ff152012-07-16 20:47:22 +00005488 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005489 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005490 return;
Mike Stump11289f42009-09-09 15:08:12 +00005491
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005492 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005493 Diag(Loc, diag::warn_floatingpoint_eq)
5494 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005495}
John McCallca01b222010-01-04 23:21:16 +00005496
John McCall70aa5392010-01-06 05:24:50 +00005497//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5498//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005499
John McCall70aa5392010-01-06 05:24:50 +00005500namespace {
John McCallca01b222010-01-04 23:21:16 +00005501
John McCall70aa5392010-01-06 05:24:50 +00005502/// Structure recording the 'active' range of an integer-valued
5503/// expression.
5504struct IntRange {
5505 /// The number of bits active in the int.
5506 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005507
John McCall70aa5392010-01-06 05:24:50 +00005508 /// True if the int is known not to have negative values.
5509 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005510
John McCall70aa5392010-01-06 05:24:50 +00005511 IntRange(unsigned Width, bool NonNegative)
5512 : Width(Width), NonNegative(NonNegative)
5513 {}
John McCallca01b222010-01-04 23:21:16 +00005514
John McCall817d4af2010-11-10 23:38:19 +00005515 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005516 static IntRange forBoolType() {
5517 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005518 }
5519
John McCall817d4af2010-11-10 23:38:19 +00005520 /// Returns the range of an opaque value of the given integral type.
5521 static IntRange forValueOfType(ASTContext &C, QualType T) {
5522 return forValueOfCanonicalType(C,
5523 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005524 }
5525
John McCall817d4af2010-11-10 23:38:19 +00005526 /// Returns the range of an opaque value of a canonical integral type.
5527 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005528 assert(T->isCanonicalUnqualified());
5529
5530 if (const VectorType *VT = dyn_cast<VectorType>(T))
5531 T = VT->getElementType().getTypePtr();
5532 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5533 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005534 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5535 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005536
David Majnemer6a426652013-06-07 22:07:20 +00005537 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005538 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005539 EnumDecl *Enum = ET->getDecl();
5540 if (!Enum->isCompleteDefinition())
5541 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005542
David Majnemer6a426652013-06-07 22:07:20 +00005543 unsigned NumPositive = Enum->getNumPositiveBits();
5544 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005545
David Majnemer6a426652013-06-07 22:07:20 +00005546 if (NumNegative == 0)
5547 return IntRange(NumPositive, true/*NonNegative*/);
5548 else
5549 return IntRange(std::max(NumPositive + 1, NumNegative),
5550 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005551 }
John McCall70aa5392010-01-06 05:24:50 +00005552
5553 const BuiltinType *BT = cast<BuiltinType>(T);
5554 assert(BT->isInteger());
5555
5556 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5557 }
5558
John McCall817d4af2010-11-10 23:38:19 +00005559 /// Returns the "target" range of a canonical integral type, i.e.
5560 /// the range of values expressible in the type.
5561 ///
5562 /// This matches forValueOfCanonicalType except that enums have the
5563 /// full range of their type, not the range of their enumerators.
5564 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5565 assert(T->isCanonicalUnqualified());
5566
5567 if (const VectorType *VT = dyn_cast<VectorType>(T))
5568 T = VT->getElementType().getTypePtr();
5569 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5570 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005571 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5572 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005573 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005574 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005575
5576 const BuiltinType *BT = cast<BuiltinType>(T);
5577 assert(BT->isInteger());
5578
5579 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5580 }
5581
5582 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005583 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005584 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005585 L.NonNegative && R.NonNegative);
5586 }
5587
John McCall817d4af2010-11-10 23:38:19 +00005588 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005589 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005590 return IntRange(std::min(L.Width, R.Width),
5591 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005592 }
5593};
5594
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005595static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5596 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005597 if (value.isSigned() && value.isNegative())
5598 return IntRange(value.getMinSignedBits(), false);
5599
5600 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005601 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005602
5603 // isNonNegative() just checks the sign bit without considering
5604 // signedness.
5605 return IntRange(value.getActiveBits(), true);
5606}
5607
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005608static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5609 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005610 if (result.isInt())
5611 return GetValueRange(C, result.getInt(), MaxWidth);
5612
5613 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005614 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5615 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5616 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5617 R = IntRange::join(R, El);
5618 }
John McCall70aa5392010-01-06 05:24:50 +00005619 return R;
5620 }
5621
5622 if (result.isComplexInt()) {
5623 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5624 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5625 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005626 }
5627
5628 // This can happen with lossless casts to intptr_t of "based" lvalues.
5629 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005630 // FIXME: The only reason we need to pass the type in here is to get
5631 // the sign right on this one case. It would be nice if APValue
5632 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005633 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005634 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005635}
John McCall70aa5392010-01-06 05:24:50 +00005636
Eli Friedmane6d33952013-07-08 20:20:06 +00005637static QualType GetExprType(Expr *E) {
5638 QualType Ty = E->getType();
5639 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5640 Ty = AtomicRHS->getValueType();
5641 return Ty;
5642}
5643
John McCall70aa5392010-01-06 05:24:50 +00005644/// Pseudo-evaluate the given integer expression, estimating the
5645/// range of values it might take.
5646///
5647/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005648static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005649 E = E->IgnoreParens();
5650
5651 // Try a full evaluation first.
5652 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005653 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005654 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005655
5656 // I think we only want to look through implicit casts here; if the
5657 // user has an explicit widening cast, we should treat the value as
5658 // being of the new, wider type.
5659 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005660 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005661 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5662
Eli Friedmane6d33952013-07-08 20:20:06 +00005663 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005664
John McCalle3027922010-08-25 11:45:40 +00005665 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005666
John McCall70aa5392010-01-06 05:24:50 +00005667 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005668 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005669 return OutputTypeRange;
5670
5671 IntRange SubRange
5672 = GetExprRange(C, CE->getSubExpr(),
5673 std::min(MaxWidth, OutputTypeRange.Width));
5674
5675 // Bail out if the subexpr's range is as wide as the cast type.
5676 if (SubRange.Width >= OutputTypeRange.Width)
5677 return OutputTypeRange;
5678
5679 // Otherwise, we take the smaller width, and we're non-negative if
5680 // either the output type or the subexpr is.
5681 return IntRange(SubRange.Width,
5682 SubRange.NonNegative || OutputTypeRange.NonNegative);
5683 }
5684
5685 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5686 // If we can fold the condition, just take that operand.
5687 bool CondResult;
5688 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5689 return GetExprRange(C, CondResult ? CO->getTrueExpr()
5690 : CO->getFalseExpr(),
5691 MaxWidth);
5692
5693 // Otherwise, conservatively merge.
5694 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5695 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5696 return IntRange::join(L, R);
5697 }
5698
5699 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5700 switch (BO->getOpcode()) {
5701
5702 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00005703 case BO_LAnd:
5704 case BO_LOr:
5705 case BO_LT:
5706 case BO_GT:
5707 case BO_LE:
5708 case BO_GE:
5709 case BO_EQ:
5710 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00005711 return IntRange::forBoolType();
5712
John McCallc3688382011-07-13 06:35:24 +00005713 // The type of the assignments is the type of the LHS, so the RHS
5714 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00005715 case BO_MulAssign:
5716 case BO_DivAssign:
5717 case BO_RemAssign:
5718 case BO_AddAssign:
5719 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00005720 case BO_XorAssign:
5721 case BO_OrAssign:
5722 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00005723 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00005724
John McCallc3688382011-07-13 06:35:24 +00005725 // Simple assignments just pass through the RHS, which will have
5726 // been coerced to the LHS type.
5727 case BO_Assign:
5728 // TODO: bitfields?
5729 return GetExprRange(C, BO->getRHS(), MaxWidth);
5730
John McCall70aa5392010-01-06 05:24:50 +00005731 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005732 case BO_PtrMemD:
5733 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00005734 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005735
John McCall2ce81ad2010-01-06 22:07:33 +00005736 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00005737 case BO_And:
5738 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00005739 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5740 GetExprRange(C, BO->getRHS(), MaxWidth));
5741
John McCall70aa5392010-01-06 05:24:50 +00005742 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00005743 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00005744 // ...except that we want to treat '1 << (blah)' as logically
5745 // positive. It's an important idiom.
5746 if (IntegerLiteral *I
5747 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5748 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005749 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00005750 return IntRange(R.Width, /*NonNegative*/ true);
5751 }
5752 }
5753 // fallthrough
5754
John McCalle3027922010-08-25 11:45:40 +00005755 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00005756 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005757
John McCall2ce81ad2010-01-06 22:07:33 +00005758 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00005759 case BO_Shr:
5760 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00005761 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5762
5763 // If the shift amount is a positive constant, drop the width by
5764 // that much.
5765 llvm::APSInt shift;
5766 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5767 shift.isNonNegative()) {
5768 unsigned zext = shift.getZExtValue();
5769 if (zext >= L.Width)
5770 L.Width = (L.NonNegative ? 0 : 1);
5771 else
5772 L.Width -= zext;
5773 }
5774
5775 return L;
5776 }
5777
5778 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00005779 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00005780 return GetExprRange(C, BO->getRHS(), MaxWidth);
5781
John McCall2ce81ad2010-01-06 22:07:33 +00005782 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00005783 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00005784 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00005785 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005786 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00005787
John McCall51431812011-07-14 22:39:48 +00005788 // The width of a division result is mostly determined by the size
5789 // of the LHS.
5790 case BO_Div: {
5791 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005792 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005793 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5794
5795 // If the divisor is constant, use that.
5796 llvm::APSInt divisor;
5797 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5798 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5799 if (log2 >= L.Width)
5800 L.Width = (L.NonNegative ? 0 : 1);
5801 else
5802 L.Width = std::min(L.Width - log2, MaxWidth);
5803 return L;
5804 }
5805
5806 // Otherwise, just use the LHS's width.
5807 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5808 return IntRange(L.Width, L.NonNegative && R.NonNegative);
5809 }
5810
5811 // The result of a remainder can't be larger than the result of
5812 // either side.
5813 case BO_Rem: {
5814 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00005815 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00005816 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5817 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5818
5819 IntRange meet = IntRange::meet(L, R);
5820 meet.Width = std::min(meet.Width, MaxWidth);
5821 return meet;
5822 }
5823
5824 // The default behavior is okay for these.
5825 case BO_Mul:
5826 case BO_Add:
5827 case BO_Xor:
5828 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00005829 break;
5830 }
5831
John McCall51431812011-07-14 22:39:48 +00005832 // The default case is to treat the operation as if it were closed
5833 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00005834 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5835 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5836 return IntRange::join(L, R);
5837 }
5838
5839 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5840 switch (UO->getOpcode()) {
5841 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00005842 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00005843 return IntRange::forBoolType();
5844
5845 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00005846 case UO_Deref:
5847 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00005848 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005849
5850 default:
5851 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5852 }
5853 }
5854
Ted Kremeneka553fbf2013-10-14 18:55:27 +00005855 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5856 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5857
John McCalld25db7e2013-05-06 21:39:12 +00005858 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00005859 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00005860 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00005861
Eli Friedmane6d33952013-07-08 20:20:06 +00005862 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00005863}
John McCall263a48b2010-01-04 23:31:57 +00005864
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005865static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00005866 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00005867}
5868
John McCall263a48b2010-01-04 23:31:57 +00005869/// Checks whether the given value, which currently has the given
5870/// source semantics, has the same value when coerced through the
5871/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005872static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5873 const llvm::fltSemantics &Src,
5874 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005875 llvm::APFloat truncated = value;
5876
5877 bool ignored;
5878 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5879 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5880
5881 return truncated.bitwiseIsEqual(value);
5882}
5883
5884/// Checks whether the given value, which currently has the given
5885/// source semantics, has the same value when coerced through the
5886/// target semantics.
5887///
5888/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005889static bool IsSameFloatAfterCast(const APValue &value,
5890 const llvm::fltSemantics &Src,
5891 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00005892 if (value.isFloat())
5893 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5894
5895 if (value.isVector()) {
5896 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5897 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5898 return false;
5899 return true;
5900 }
5901
5902 assert(value.isComplexFloat());
5903 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5904 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5905}
5906
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005907static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00005908
Ted Kremenek6274be42010-09-23 21:43:44 +00005909static bool IsZero(Sema &S, Expr *E) {
5910 // Suppress cases where we are comparing against an enum constant.
5911 if (const DeclRefExpr *DR =
5912 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5913 if (isa<EnumConstantDecl>(DR->getDecl()))
5914 return false;
5915
5916 // Suppress cases where the '0' value is expanded from a macro.
5917 if (E->getLocStart().isMacroID())
5918 return false;
5919
John McCallcc7e5bf2010-05-06 08:58:33 +00005920 llvm::APSInt Value;
5921 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5922}
5923
John McCall2551c1b2010-10-06 00:25:24 +00005924static bool HasEnumType(Expr *E) {
5925 // Strip off implicit integral promotions.
5926 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005927 if (ICE->getCastKind() != CK_IntegralCast &&
5928 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00005929 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00005930 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00005931 }
5932
5933 return E->getType()->isEnumeralType();
5934}
5935
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005936static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00005937 // Disable warning in template instantiations.
5938 if (!S.ActiveTemplateInstantiations.empty())
5939 return;
5940
John McCalle3027922010-08-25 11:45:40 +00005941 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00005942 if (E->isValueDependent())
5943 return;
5944
John McCalle3027922010-08-25 11:45:40 +00005945 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005946 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005947 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005948 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005949 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005950 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005951 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005952 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005953 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005954 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005955 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005956 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00005957 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00005958 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00005959 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00005960 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5961 }
5962}
5963
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005964static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005965 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005966 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00005967 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00005968 // Disable warning in template instantiations.
5969 if (!S.ActiveTemplateInstantiations.empty())
5970 return;
5971
Richard Trieu0f097742014-04-04 04:13:47 +00005972 // TODO: Investigate using GetExprRange() to get tighter bounds
5973 // on the bit ranges.
5974 QualType OtherT = Other->getType();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005975 if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5976 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00005977 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5978 unsigned OtherWidth = OtherRange.Width;
5979
5980 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5981
Richard Trieu560910c2012-11-14 22:50:24 +00005982 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00005983 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00005984 return;
5985
Fariborz Jahanianb1885422012-09-18 17:37:21 +00005986 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00005987 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00005988
Richard Trieu0f097742014-04-04 04:13:47 +00005989 // Used for diagnostic printout.
5990 enum {
5991 LiteralConstant = 0,
5992 CXXBoolLiteralTrue,
5993 CXXBoolLiteralFalse
5994 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00005995
Richard Trieu0f097742014-04-04 04:13:47 +00005996 if (!OtherIsBooleanType) {
5997 QualType ConstantT = Constant->getType();
5998 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00005999
Richard Trieu0f097742014-04-04 04:13:47 +00006000 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6001 return;
6002 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6003 "comparison with non-integer type");
6004
6005 bool ConstantSigned = ConstantT->isSignedIntegerType();
6006 bool CommonSigned = CommonT->isSignedIntegerType();
6007
6008 bool EqualityOnly = false;
6009
6010 if (CommonSigned) {
6011 // The common type is signed, therefore no signed to unsigned conversion.
6012 if (!OtherRange.NonNegative) {
6013 // Check that the constant is representable in type OtherT.
6014 if (ConstantSigned) {
6015 if (OtherWidth >= Value.getMinSignedBits())
6016 return;
6017 } else { // !ConstantSigned
6018 if (OtherWidth >= Value.getActiveBits() + 1)
6019 return;
6020 }
6021 } else { // !OtherSigned
6022 // Check that the constant is representable in type OtherT.
6023 // Negative values are out of range.
6024 if (ConstantSigned) {
6025 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6026 return;
6027 } else { // !ConstantSigned
6028 if (OtherWidth >= Value.getActiveBits())
6029 return;
6030 }
Richard Trieu560910c2012-11-14 22:50:24 +00006031 }
Richard Trieu0f097742014-04-04 04:13:47 +00006032 } else { // !CommonSigned
6033 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006034 if (OtherWidth >= Value.getActiveBits())
6035 return;
Craig Toppercf360162014-06-18 05:13:11 +00006036 } else { // OtherSigned
6037 assert(!ConstantSigned &&
6038 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006039 // Check to see if the constant is representable in OtherT.
6040 if (OtherWidth > Value.getActiveBits())
6041 return;
6042 // Check to see if the constant is equivalent to a negative value
6043 // cast to CommonT.
6044 if (S.Context.getIntWidth(ConstantT) ==
6045 S.Context.getIntWidth(CommonT) &&
6046 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6047 return;
6048 // The constant value rests between values that OtherT can represent
6049 // after conversion. Relational comparison still works, but equality
6050 // comparisons will be tautological.
6051 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006052 }
6053 }
Richard Trieu0f097742014-04-04 04:13:47 +00006054
6055 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6056
6057 if (op == BO_EQ || op == BO_NE) {
6058 IsTrue = op == BO_NE;
6059 } else if (EqualityOnly) {
6060 return;
6061 } else if (RhsConstant) {
6062 if (op == BO_GT || op == BO_GE)
6063 IsTrue = !PositiveConstant;
6064 else // op == BO_LT || op == BO_LE
6065 IsTrue = PositiveConstant;
6066 } else {
6067 if (op == BO_LT || op == BO_LE)
6068 IsTrue = !PositiveConstant;
6069 else // op == BO_GT || op == BO_GE
6070 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006071 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006072 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006073 // Other isKnownToHaveBooleanValue
6074 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6075 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6076 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6077
6078 static const struct LinkedConditions {
6079 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6080 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6081 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6082 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6083 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6084 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6085
6086 } TruthTable = {
6087 // Constant on LHS. | Constant on RHS. |
6088 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6089 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6090 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6091 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6092 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6093 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6094 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6095 };
6096
6097 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6098
6099 enum ConstantValue ConstVal = Zero;
6100 if (Value.isUnsigned() || Value.isNonNegative()) {
6101 if (Value == 0) {
6102 LiteralOrBoolConstant =
6103 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6104 ConstVal = Zero;
6105 } else if (Value == 1) {
6106 LiteralOrBoolConstant =
6107 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6108 ConstVal = One;
6109 } else {
6110 LiteralOrBoolConstant = LiteralConstant;
6111 ConstVal = GT_One;
6112 }
6113 } else {
6114 ConstVal = LT_Zero;
6115 }
6116
6117 CompareBoolWithConstantResult CmpRes;
6118
6119 switch (op) {
6120 case BO_LT:
6121 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6122 break;
6123 case BO_GT:
6124 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6125 break;
6126 case BO_LE:
6127 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6128 break;
6129 case BO_GE:
6130 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6131 break;
6132 case BO_EQ:
6133 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6134 break;
6135 case BO_NE:
6136 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6137 break;
6138 default:
6139 CmpRes = Unkwn;
6140 break;
6141 }
6142
6143 if (CmpRes == AFals) {
6144 IsTrue = false;
6145 } else if (CmpRes == ATrue) {
6146 IsTrue = true;
6147 } else {
6148 return;
6149 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006150 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006151
6152 // If this is a comparison to an enum constant, include that
6153 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006154 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006155 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6156 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6157
6158 SmallString<64> PrettySourceValue;
6159 llvm::raw_svector_ostream OS(PrettySourceValue);
6160 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006161 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006162 else
6163 OS << Value;
6164
Richard Trieu0f097742014-04-04 04:13:47 +00006165 S.DiagRuntimeBehavior(
6166 E->getOperatorLoc(), E,
6167 S.PDiag(diag::warn_out_of_range_compare)
6168 << OS.str() << LiteralOrBoolConstant
6169 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6170 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006171}
6172
John McCallcc7e5bf2010-05-06 08:58:33 +00006173/// Analyze the operands of the given comparison. Implements the
6174/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006175static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006176 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6177 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006178}
John McCall263a48b2010-01-04 23:31:57 +00006179
John McCallca01b222010-01-04 23:21:16 +00006180/// \brief Implements -Wsign-compare.
6181///
Richard Trieu82402a02011-09-15 21:56:47 +00006182/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006183static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006184 // The type the comparison is being performed in.
6185 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006186
6187 // Only analyze comparison operators where both sides have been converted to
6188 // the same type.
6189 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6190 return AnalyzeImpConvsInComparison(S, E);
6191
6192 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006193 if (E->isValueDependent())
6194 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006195
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006196 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6197 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006198
6199 bool IsComparisonConstant = false;
6200
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006201 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006202 // of 'true' or 'false'.
6203 if (T->isIntegralType(S.Context)) {
6204 llvm::APSInt RHSValue;
6205 bool IsRHSIntegralLiteral =
6206 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6207 llvm::APSInt LHSValue;
6208 bool IsLHSIntegralLiteral =
6209 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6210 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6211 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6212 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6213 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6214 else
6215 IsComparisonConstant =
6216 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006217 } else if (!T->hasUnsignedIntegerRepresentation())
6218 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006219
John McCallcc7e5bf2010-05-06 08:58:33 +00006220 // We don't do anything special if this isn't an unsigned integral
6221 // comparison: we're only interested in integral comparisons, and
6222 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006223 //
6224 // We also don't care about value-dependent expressions or expressions
6225 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006226 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006227 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006228
John McCallcc7e5bf2010-05-06 08:58:33 +00006229 // Check to see if one of the (unmodified) operands is of different
6230 // signedness.
6231 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006232 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6233 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006234 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006235 signedOperand = LHS;
6236 unsignedOperand = RHS;
6237 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6238 signedOperand = RHS;
6239 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006240 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006241 CheckTrivialUnsignedComparison(S, E);
6242 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006243 }
6244
John McCallcc7e5bf2010-05-06 08:58:33 +00006245 // Otherwise, calculate the effective range of the signed operand.
6246 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006247
John McCallcc7e5bf2010-05-06 08:58:33 +00006248 // Go ahead and analyze implicit conversions in the operands. Note
6249 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006250 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6251 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006252
John McCallcc7e5bf2010-05-06 08:58:33 +00006253 // If the signed range is non-negative, -Wsign-compare won't fire,
6254 // but we should still check for comparisons which are always true
6255 // or false.
6256 if (signedRange.NonNegative)
6257 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006258
6259 // For (in)equality comparisons, if the unsigned operand is a
6260 // constant which cannot collide with a overflowed signed operand,
6261 // then reinterpreting the signed operand as unsigned will not
6262 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006263 if (E->isEqualityOp()) {
6264 unsigned comparisonWidth = S.Context.getIntWidth(T);
6265 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006266
John McCallcc7e5bf2010-05-06 08:58:33 +00006267 // We should never be unable to prove that the unsigned operand is
6268 // non-negative.
6269 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6270
6271 if (unsignedRange.Width < comparisonWidth)
6272 return;
6273 }
6274
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006275 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6276 S.PDiag(diag::warn_mixed_sign_comparison)
6277 << LHS->getType() << RHS->getType()
6278 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006279}
6280
John McCall1f425642010-11-11 03:21:53 +00006281/// Analyzes an attempt to assign the given value to a bitfield.
6282///
6283/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006284static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6285 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006286 assert(Bitfield->isBitField());
6287 if (Bitfield->isInvalidDecl())
6288 return false;
6289
John McCalldeebbcf2010-11-11 05:33:51 +00006290 // White-list bool bitfields.
6291 if (Bitfield->getType()->isBooleanType())
6292 return false;
6293
Douglas Gregor789adec2011-02-04 13:09:01 +00006294 // Ignore value- or type-dependent expressions.
6295 if (Bitfield->getBitWidth()->isValueDependent() ||
6296 Bitfield->getBitWidth()->isTypeDependent() ||
6297 Init->isValueDependent() ||
6298 Init->isTypeDependent())
6299 return false;
6300
John McCall1f425642010-11-11 03:21:53 +00006301 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6302
Richard Smith5fab0c92011-12-28 19:48:30 +00006303 llvm::APSInt Value;
6304 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006305 return false;
6306
John McCall1f425642010-11-11 03:21:53 +00006307 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006308 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006309
6310 if (OriginalWidth <= FieldWidth)
6311 return false;
6312
Eli Friedmanc267a322012-01-26 23:11:39 +00006313 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006314 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006315 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006316
Eli Friedmanc267a322012-01-26 23:11:39 +00006317 // Check whether the stored value is equal to the original value.
6318 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006319 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006320 return false;
6321
Eli Friedmanc267a322012-01-26 23:11:39 +00006322 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006323 // therefore don't strictly fit into a signed bitfield of width 1.
6324 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006325 return false;
6326
John McCall1f425642010-11-11 03:21:53 +00006327 std::string PrettyValue = Value.toString(10);
6328 std::string PrettyTrunc = TruncatedValue.toString(10);
6329
6330 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6331 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6332 << Init->getSourceRange();
6333
6334 return true;
6335}
6336
John McCalld2a53122010-11-09 23:24:47 +00006337/// Analyze the given simple or compound assignment for warning-worthy
6338/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006339static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006340 // Just recurse on the LHS.
6341 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6342
6343 // We want to recurse on the RHS as normal unless we're assigning to
6344 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006345 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006346 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006347 E->getOperatorLoc())) {
6348 // Recurse, ignoring any implicit conversions on the RHS.
6349 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6350 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006351 }
6352 }
6353
6354 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6355}
6356
John McCall263a48b2010-01-04 23:31:57 +00006357/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006358static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006359 SourceLocation CContext, unsigned diag,
6360 bool pruneControlFlow = false) {
6361 if (pruneControlFlow) {
6362 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6363 S.PDiag(diag)
6364 << SourceType << T << E->getSourceRange()
6365 << SourceRange(CContext));
6366 return;
6367 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006368 S.Diag(E->getExprLoc(), diag)
6369 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6370}
6371
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006372/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006373static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006374 SourceLocation CContext, unsigned diag,
6375 bool pruneControlFlow = false) {
6376 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006377}
6378
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006379/// Diagnose an implicit cast from a literal expression. Does not warn when the
6380/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006381void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6382 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006383 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006384 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006385 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006386 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6387 T->hasUnsignedIntegerRepresentation());
6388 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006389 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006390 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006391 return;
6392
Eli Friedman07185912013-08-29 23:44:43 +00006393 // FIXME: Force the precision of the source value down so we don't print
6394 // digits which are usually useless (we don't really care here if we
6395 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6396 // would automatically print the shortest representation, but it's a bit
6397 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006398 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006399 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6400 precision = (precision * 59 + 195) / 196;
6401 Value.toString(PrettySourceValue, precision);
6402
David Blaikie9b88cc02012-05-15 17:18:27 +00006403 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006404 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6405 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6406 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006407 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006408
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006409 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006410 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6411 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006412}
6413
John McCall18a2c2c2010-11-09 22:22:12 +00006414std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6415 if (!Range.Width) return "0";
6416
6417 llvm::APSInt ValueInRange = Value;
6418 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006419 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006420 return ValueInRange.toString(10);
6421}
6422
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006423static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6424 if (!isa<ImplicitCastExpr>(Ex))
6425 return false;
6426
6427 Expr *InnerE = Ex->IgnoreParenImpCasts();
6428 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6429 const Type *Source =
6430 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6431 if (Target->isDependentType())
6432 return false;
6433
6434 const BuiltinType *FloatCandidateBT =
6435 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6436 const Type *BoolCandidateType = ToBool ? Target : Source;
6437
6438 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6439 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6440}
6441
6442void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6443 SourceLocation CC) {
6444 unsigned NumArgs = TheCall->getNumArgs();
6445 for (unsigned i = 0; i < NumArgs; ++i) {
6446 Expr *CurrA = TheCall->getArg(i);
6447 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6448 continue;
6449
6450 bool IsSwapped = ((i > 0) &&
6451 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6452 IsSwapped |= ((i < (NumArgs - 1)) &&
6453 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6454 if (IsSwapped) {
6455 // Warn on this floating-point to bool conversion.
6456 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6457 CurrA->getType(), CC,
6458 diag::warn_impcast_floating_point_to_bool);
6459 }
6460 }
6461}
6462
Richard Trieu5b993502014-10-15 03:42:06 +00006463static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6464 SourceLocation CC) {
6465 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6466 E->getExprLoc()))
6467 return;
6468
6469 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6470 const Expr::NullPointerConstantKind NullKind =
6471 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6472 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6473 return;
6474
6475 // Return if target type is a safe conversion.
6476 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6477 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6478 return;
6479
6480 SourceLocation Loc = E->getSourceRange().getBegin();
6481
6482 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6483 if (NullKind == Expr::NPCK_GNUNull) {
6484 if (Loc.isMacroID())
6485 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6486 }
6487
6488 // Only warn if the null and context location are in the same macro expansion.
6489 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6490 return;
6491
6492 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6493 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6494 << FixItHint::CreateReplacement(Loc,
6495 S.getFixItZeroLiteralForType(T, Loc));
6496}
6497
John McCallcc7e5bf2010-05-06 08:58:33 +00006498void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006499 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006500 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006501
John McCallcc7e5bf2010-05-06 08:58:33 +00006502 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6503 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6504 if (Source == Target) return;
6505 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006506
Chandler Carruthc22845a2011-07-26 05:40:03 +00006507 // If the conversion context location is invalid don't complain. We also
6508 // don't want to emit a warning if the issue occurs from the expansion of
6509 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6510 // delay this check as long as possible. Once we detect we are in that
6511 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006512 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006513 return;
6514
Richard Trieu021baa32011-09-23 20:10:00 +00006515 // Diagnose implicit casts to bool.
6516 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6517 if (isa<StringLiteral>(E))
6518 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006519 // and expressions, for instance, assert(0 && "error here"), are
6520 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006521 return DiagnoseImpCast(S, E, T, CC,
6522 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006523 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6524 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6525 // This covers the literal expressions that evaluate to Objective-C
6526 // objects.
6527 return DiagnoseImpCast(S, E, T, CC,
6528 diag::warn_impcast_objective_c_literal_to_bool);
6529 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006530 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6531 // Warn on pointer to bool conversion that is always true.
6532 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6533 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006534 }
Richard Trieu021baa32011-09-23 20:10:00 +00006535 }
John McCall263a48b2010-01-04 23:31:57 +00006536
6537 // Strip vector types.
6538 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006539 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006540 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006541 return;
John McCallacf0ee52010-10-08 02:01:28 +00006542 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006543 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006544
6545 // If the vector cast is cast between two vectors of the same size, it is
6546 // a bitcast, not a conversion.
6547 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6548 return;
John McCall263a48b2010-01-04 23:31:57 +00006549
6550 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6551 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6552 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006553 if (auto VecTy = dyn_cast<VectorType>(Target))
6554 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006555
6556 // Strip complex types.
6557 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006558 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006559 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006560 return;
6561
John McCallacf0ee52010-10-08 02:01:28 +00006562 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006563 }
John McCall263a48b2010-01-04 23:31:57 +00006564
6565 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6566 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6567 }
6568
6569 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6570 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6571
6572 // If the source is floating point...
6573 if (SourceBT && SourceBT->isFloatingPoint()) {
6574 // ...and the target is floating point...
6575 if (TargetBT && TargetBT->isFloatingPoint()) {
6576 // ...then warn if we're dropping FP rank.
6577
6578 // Builtin FP kinds are ordered by increasing FP rank.
6579 if (SourceBT->getKind() > TargetBT->getKind()) {
6580 // Don't warn about float constants that are precisely
6581 // representable in the target type.
6582 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006583 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006584 // Value might be a float, a float vector, or a float complex.
6585 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006586 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6587 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006588 return;
6589 }
6590
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006591 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006592 return;
6593
John McCallacf0ee52010-10-08 02:01:28 +00006594 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006595 }
6596 return;
6597 }
6598
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006599 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006600 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006601 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006602 return;
6603
Chandler Carruth22c7a792011-02-17 11:05:49 +00006604 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006605 // We also want to warn on, e.g., "int i = -1.234"
6606 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6607 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6608 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6609
Chandler Carruth016ef402011-04-10 08:36:24 +00006610 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6611 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006612 } else {
6613 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6614 }
6615 }
John McCall263a48b2010-01-04 23:31:57 +00006616
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006617 // If the target is bool, warn if expr is a function or method call.
6618 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6619 isa<CallExpr>(E)) {
6620 // Check last argument of function call to see if it is an
6621 // implicit cast from a type matching the type the result
6622 // is being cast to.
6623 CallExpr *CEx = cast<CallExpr>(E);
6624 unsigned NumArgs = CEx->getNumArgs();
6625 if (NumArgs > 0) {
6626 Expr *LastA = CEx->getArg(NumArgs - 1);
6627 Expr *InnerE = LastA->IgnoreParenImpCasts();
6628 const Type *InnerType =
6629 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6630 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6631 // Warn on this floating-point to bool conversion
6632 DiagnoseImpCast(S, E, T, CC,
6633 diag::warn_impcast_floating_point_to_bool);
6634 }
6635 }
6636 }
John McCall263a48b2010-01-04 23:31:57 +00006637 return;
6638 }
6639
Richard Trieu5b993502014-10-15 03:42:06 +00006640 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006641
David Blaikie9366d2b2012-06-19 21:19:06 +00006642 if (!Source->isIntegerType() || !Target->isIntegerType())
6643 return;
6644
David Blaikie7555b6a2012-05-15 16:56:36 +00006645 // TODO: remove this early return once the false positives for constant->bool
6646 // in templates, macros, etc, are reduced or removed.
6647 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6648 return;
6649
John McCallcc7e5bf2010-05-06 08:58:33 +00006650 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006651 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006652
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006653 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006654 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006655 // TODO: this should happen for bitfield stores, too.
6656 llvm::APSInt Value(32);
6657 if (E->isIntegerConstantExpr(Value, S.Context)) {
6658 if (S.SourceMgr.isInSystemMacro(CC))
6659 return;
6660
John McCall18a2c2c2010-11-09 22:22:12 +00006661 std::string PrettySourceValue = Value.toString(10);
6662 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006663
Ted Kremenek33ba9952011-10-22 02:37:33 +00006664 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6665 S.PDiag(diag::warn_impcast_integer_precision_constant)
6666 << PrettySourceValue << PrettyTargetValue
6667 << E->getType() << T << E->getSourceRange()
6668 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006669 return;
6670 }
6671
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006672 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6673 if (S.SourceMgr.isInSystemMacro(CC))
6674 return;
6675
David Blaikie9455da02012-04-12 22:40:54 +00006676 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006677 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6678 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00006679 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00006680 }
6681
6682 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6683 (!TargetRange.NonNegative && SourceRange.NonNegative &&
6684 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006685
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006686 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006687 return;
6688
John McCallcc7e5bf2010-05-06 08:58:33 +00006689 unsigned DiagID = diag::warn_impcast_integer_sign;
6690
6691 // Traditionally, gcc has warned about this under -Wsign-compare.
6692 // We also want to warn about it in -Wconversion.
6693 // So if -Wconversion is off, use a completely identical diagnostic
6694 // in the sign-compare group.
6695 // The conditional-checking code will
6696 if (ICContext) {
6697 DiagID = diag::warn_impcast_integer_sign_conditional;
6698 *ICContext = true;
6699 }
6700
John McCallacf0ee52010-10-08 02:01:28 +00006701 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00006702 }
6703
Douglas Gregora78f1932011-02-22 02:45:07 +00006704 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00006705 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6706 // type, to give us better diagnostics.
6707 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00006708 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00006709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6710 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6711 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6712 SourceType = S.Context.getTypeDeclType(Enum);
6713 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6714 }
6715 }
6716
Douglas Gregora78f1932011-02-22 02:45:07 +00006717 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6718 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00006719 if (SourceEnum->getDecl()->hasNameForLinkage() &&
6720 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006721 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006722 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006723 return;
6724
Douglas Gregor364f7db2011-03-12 00:14:31 +00006725 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00006726 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006727 }
Douglas Gregora78f1932011-02-22 02:45:07 +00006728
John McCall263a48b2010-01-04 23:31:57 +00006729 return;
6730}
6731
David Blaikie18e9ac72012-05-15 21:57:38 +00006732void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6733 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006734
6735void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00006736 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006737 E = E->IgnoreParenImpCasts();
6738
6739 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00006740 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006741
John McCallacf0ee52010-10-08 02:01:28 +00006742 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006743 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006744 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00006745 return;
6746}
6747
David Blaikie18e9ac72012-05-15 21:57:38 +00006748void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6749 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00006750 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006751
6752 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00006753 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6754 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006755
6756 // If -Wconversion would have warned about either of the candidates
6757 // for a signedness conversion to the context type...
6758 if (!Suspicious) return;
6759
6760 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00006761 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00006762 return;
6763
John McCallcc7e5bf2010-05-06 08:58:33 +00006764 // ...then check whether it would have warned about either of the
6765 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00006766 if (E->getType() == T) return;
6767
6768 Suspicious = false;
6769 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6770 E->getType(), CC, &Suspicious);
6771 if (!Suspicious)
6772 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00006773 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00006774}
6775
Richard Trieu65724892014-11-15 06:37:39 +00006776/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6777/// Input argument E is a logical expression.
6778static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6779 if (S.getLangOpts().Bool)
6780 return;
6781 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6782}
6783
John McCallcc7e5bf2010-05-06 08:58:33 +00006784/// AnalyzeImplicitConversions - Find and report any interesting
6785/// implicit conversions in the given expression. There are a couple
6786/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00006787void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00006788 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00006789 Expr *E = OrigE->IgnoreParenImpCasts();
6790
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00006791 if (E->isTypeDependent() || E->isValueDependent())
6792 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00006793
John McCallcc7e5bf2010-05-06 08:58:33 +00006794 // For conditional operators, we analyze the arguments as if they
6795 // were being fed directly into the output.
6796 if (isa<ConditionalOperator>(E)) {
6797 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00006798 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00006799 return;
6800 }
6801
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006802 // Check implicit argument conversions for function calls.
6803 if (CallExpr *Call = dyn_cast<CallExpr>(E))
6804 CheckImplicitArgumentConversions(S, Call, CC);
6805
John McCallcc7e5bf2010-05-06 08:58:33 +00006806 // Go ahead and check any implicit conversions we might have skipped.
6807 // The non-canonical typecheck is just an optimization;
6808 // CheckImplicitConversion will filter out dead implicit conversions.
6809 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00006810 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006811
6812 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006813
6814 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006815 if (POE->getResultExpr())
6816 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00006817 }
6818
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00006819 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
6820 if (OVE->getSourceExpr())
6821 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6822 return;
6823 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00006824
John McCallcc7e5bf2010-05-06 08:58:33 +00006825 // Skip past explicit casts.
6826 if (isa<ExplicitCastExpr>(E)) {
6827 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00006828 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006829 }
6830
John McCalld2a53122010-11-09 23:24:47 +00006831 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6832 // Do a somewhat different check with comparison operators.
6833 if (BO->isComparisonOp())
6834 return AnalyzeComparison(S, BO);
6835
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006836 // And with simple assignments.
6837 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00006838 return AnalyzeAssignment(S, BO);
6839 }
John McCallcc7e5bf2010-05-06 08:58:33 +00006840
6841 // These break the otherwise-useful invariant below. Fortunately,
6842 // we don't really need to recurse into them, because any internal
6843 // expressions should have been analyzed already when they were
6844 // built into statements.
6845 if (isa<StmtExpr>(E)) return;
6846
6847 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00006848 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00006849
6850 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00006851 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00006852 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00006853 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00006854 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00006855 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00006856 if (!ChildExpr)
6857 continue;
6858
Richard Trieu955231d2014-01-25 01:10:35 +00006859 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00006860 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00006861 // Ignore checking string literals that are in logical and operators.
6862 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00006863 continue;
6864 AnalyzeImplicitConversions(S, ChildExpr, CC);
6865 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006866
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006867 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00006868 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6869 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006870 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00006871
6872 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6873 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00006874 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006875 }
Richard Trieu791b86e2014-11-19 06:08:18 +00006876
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00006877 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6878 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00006879 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006880}
6881
6882} // end anonymous namespace
6883
Richard Trieu3bb8b562014-02-26 02:36:06 +00006884enum {
6885 AddressOf,
6886 FunctionPointer,
6887 ArrayPointer
6888};
6889
Richard Trieuc1888e02014-06-28 23:25:37 +00006890// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6891// Returns true when emitting a warning about taking the address of a reference.
6892static bool CheckForReference(Sema &SemaRef, const Expr *E,
6893 PartialDiagnostic PD) {
6894 E = E->IgnoreParenImpCasts();
6895
6896 const FunctionDecl *FD = nullptr;
6897
6898 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6899 if (!DRE->getDecl()->getType()->isReferenceType())
6900 return false;
6901 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6902 if (!M->getMemberDecl()->getType()->isReferenceType())
6903 return false;
6904 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00006905 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00006906 return false;
6907 FD = Call->getDirectCallee();
6908 } else {
6909 return false;
6910 }
6911
6912 SemaRef.Diag(E->getExprLoc(), PD);
6913
6914 // If possible, point to location of function.
6915 if (FD) {
6916 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6917 }
6918
6919 return true;
6920}
6921
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006922// Returns true if the SourceLocation is expanded from any macro body.
6923// Returns false if the SourceLocation is invalid, is from not in a macro
6924// expansion, or is from expanded from a top-level macro argument.
6925static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6926 if (Loc.isInvalid())
6927 return false;
6928
6929 while (Loc.isMacroID()) {
6930 if (SM.isMacroBodyExpansion(Loc))
6931 return true;
6932 Loc = SM.getImmediateMacroCallerLoc(Loc);
6933 }
6934
6935 return false;
6936}
6937
Richard Trieu3bb8b562014-02-26 02:36:06 +00006938/// \brief Diagnose pointers that are always non-null.
6939/// \param E the expression containing the pointer
6940/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6941/// compared to a null pointer
6942/// \param IsEqual True when the comparison is equal to a null pointer
6943/// \param Range Extra SourceRange to highlight in the diagnostic
6944void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6945 Expr::NullPointerConstantKind NullKind,
6946 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00006947 if (!E)
6948 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006949
6950 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006951 if (E->getExprLoc().isMacroID()) {
6952 const SourceManager &SM = getSourceManager();
6953 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6954 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00006955 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00006956 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006957 E = E->IgnoreImpCasts();
6958
6959 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6960
Richard Trieuf7432752014-06-06 21:39:26 +00006961 if (isa<CXXThisExpr>(E)) {
6962 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6963 : diag::warn_this_bool_conversion;
6964 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6965 return;
6966 }
6967
Richard Trieu3bb8b562014-02-26 02:36:06 +00006968 bool IsAddressOf = false;
6969
6970 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6971 if (UO->getOpcode() != UO_AddrOf)
6972 return;
6973 IsAddressOf = true;
6974 E = UO->getSubExpr();
6975 }
6976
Richard Trieuc1888e02014-06-28 23:25:37 +00006977 if (IsAddressOf) {
6978 unsigned DiagID = IsCompare
6979 ? diag::warn_address_of_reference_null_compare
6980 : diag::warn_address_of_reference_bool_conversion;
6981 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6982 << IsEqual;
6983 if (CheckForReference(*this, E, PD)) {
6984 return;
6985 }
6986 }
6987
Richard Trieu3bb8b562014-02-26 02:36:06 +00006988 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00006989 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00006990 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6991 D = R->getDecl();
6992 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6993 D = M->getMemberDecl();
6994 }
6995
6996 // Weak Decls can be null.
6997 if (!D || D->isWeak())
6998 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00006999
7000 // Check for parameter decl with nonnull attribute
7001 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7002 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7003 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7004 unsigned NumArgs = FD->getNumParams();
7005 llvm::SmallBitVector AttrNonNull(NumArgs);
7006 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7007 if (!NonNull->args_size()) {
7008 AttrNonNull.set(0, NumArgs);
7009 break;
7010 }
7011 for (unsigned Val : NonNull->args()) {
7012 if (Val >= NumArgs)
7013 continue;
7014 AttrNonNull.set(Val);
7015 }
7016 }
7017 if (!AttrNonNull.empty())
7018 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007019 if (FD->getParamDecl(i) == PV &&
7020 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007021 std::string Str;
7022 llvm::raw_string_ostream S(Str);
7023 E->printPretty(S, nullptr, getPrintingPolicy());
7024 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7025 : diag::warn_cast_nonnull_to_bool;
7026 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7027 << Range << IsEqual;
7028 return;
7029 }
7030 }
7031 }
7032
Richard Trieu3bb8b562014-02-26 02:36:06 +00007033 QualType T = D->getType();
7034 const bool IsArray = T->isArrayType();
7035 const bool IsFunction = T->isFunctionType();
7036
Richard Trieuc1888e02014-06-28 23:25:37 +00007037 // Address of function is used to silence the function warning.
7038 if (IsAddressOf && IsFunction) {
7039 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007040 }
7041
7042 // Found nothing.
7043 if (!IsAddressOf && !IsFunction && !IsArray)
7044 return;
7045
7046 // Pretty print the expression for the diagnostic.
7047 std::string Str;
7048 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007049 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007050
7051 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7052 : diag::warn_impcast_pointer_to_bool;
7053 unsigned DiagType;
7054 if (IsAddressOf)
7055 DiagType = AddressOf;
7056 else if (IsFunction)
7057 DiagType = FunctionPointer;
7058 else if (IsArray)
7059 DiagType = ArrayPointer;
7060 else
7061 llvm_unreachable("Could not determine diagnostic.");
7062 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7063 << Range << IsEqual;
7064
7065 if (!IsFunction)
7066 return;
7067
7068 // Suggest '&' to silence the function warning.
7069 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7070 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7071
7072 // Check to see if '()' fixit should be emitted.
7073 QualType ReturnType;
7074 UnresolvedSet<4> NonTemplateOverloads;
7075 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7076 if (ReturnType.isNull())
7077 return;
7078
7079 if (IsCompare) {
7080 // There are two cases here. If there is null constant, the only suggest
7081 // for a pointer return type. If the null is 0, then suggest if the return
7082 // type is a pointer or an integer type.
7083 if (!ReturnType->isPointerType()) {
7084 if (NullKind == Expr::NPCK_ZeroExpression ||
7085 NullKind == Expr::NPCK_ZeroLiteral) {
7086 if (!ReturnType->isIntegerType())
7087 return;
7088 } else {
7089 return;
7090 }
7091 }
7092 } else { // !IsCompare
7093 // For function to bool, only suggest if the function pointer has bool
7094 // return type.
7095 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7096 return;
7097 }
7098 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007099 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007100}
7101
7102
John McCallcc7e5bf2010-05-06 08:58:33 +00007103/// Diagnoses "dangerous" implicit conversions within the given
7104/// expression (which is a full expression). Implements -Wconversion
7105/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007106///
7107/// \param CC the "context" location of the implicit conversion, i.e.
7108/// the most location of the syntactic entity requiring the implicit
7109/// conversion
7110void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007111 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007112 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007113 return;
7114
7115 // Don't diagnose for value- or type-dependent expressions.
7116 if (E->isTypeDependent() || E->isValueDependent())
7117 return;
7118
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007119 // Check for array bounds violations in cases where the check isn't triggered
7120 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7121 // ArraySubscriptExpr is on the RHS of a variable initialization.
7122 CheckArrayAccess(E);
7123
John McCallacf0ee52010-10-08 02:01:28 +00007124 // This is not the right CC for (e.g.) a variable initialization.
7125 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007126}
7127
Richard Trieu65724892014-11-15 06:37:39 +00007128/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7129/// Input argument E is a logical expression.
7130void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7131 ::CheckBoolLikeConversion(*this, E, CC);
7132}
7133
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007134/// Diagnose when expression is an integer constant expression and its evaluation
7135/// results in integer overflow
7136void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007137 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7138 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007139}
7140
Richard Smithc406cb72013-01-17 01:17:56 +00007141namespace {
7142/// \brief Visitor for expressions which looks for unsequenced operations on the
7143/// same object.
7144class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007145 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7146
Richard Smithc406cb72013-01-17 01:17:56 +00007147 /// \brief A tree of sequenced regions within an expression. Two regions are
7148 /// unsequenced if one is an ancestor or a descendent of the other. When we
7149 /// finish processing an expression with sequencing, such as a comma
7150 /// expression, we fold its tree nodes into its parent, since they are
7151 /// unsequenced with respect to nodes we will visit later.
7152 class SequenceTree {
7153 struct Value {
7154 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7155 unsigned Parent : 31;
7156 bool Merged : 1;
7157 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007158 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007159
7160 public:
7161 /// \brief A region within an expression which may be sequenced with respect
7162 /// to some other region.
7163 class Seq {
7164 explicit Seq(unsigned N) : Index(N) {}
7165 unsigned Index;
7166 friend class SequenceTree;
7167 public:
7168 Seq() : Index(0) {}
7169 };
7170
7171 SequenceTree() { Values.push_back(Value(0)); }
7172 Seq root() const { return Seq(0); }
7173
7174 /// \brief Create a new sequence of operations, which is an unsequenced
7175 /// subset of \p Parent. This sequence of operations is sequenced with
7176 /// respect to other children of \p Parent.
7177 Seq allocate(Seq Parent) {
7178 Values.push_back(Value(Parent.Index));
7179 return Seq(Values.size() - 1);
7180 }
7181
7182 /// \brief Merge a sequence of operations into its parent.
7183 void merge(Seq S) {
7184 Values[S.Index].Merged = true;
7185 }
7186
7187 /// \brief Determine whether two operations are unsequenced. This operation
7188 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7189 /// should have been merged into its parent as appropriate.
7190 bool isUnsequenced(Seq Cur, Seq Old) {
7191 unsigned C = representative(Cur.Index);
7192 unsigned Target = representative(Old.Index);
7193 while (C >= Target) {
7194 if (C == Target)
7195 return true;
7196 C = Values[C].Parent;
7197 }
7198 return false;
7199 }
7200
7201 private:
7202 /// \brief Pick a representative for a sequence.
7203 unsigned representative(unsigned K) {
7204 if (Values[K].Merged)
7205 // Perform path compression as we go.
7206 return Values[K].Parent = representative(Values[K].Parent);
7207 return K;
7208 }
7209 };
7210
7211 /// An object for which we can track unsequenced uses.
7212 typedef NamedDecl *Object;
7213
7214 /// Different flavors of object usage which we track. We only track the
7215 /// least-sequenced usage of each kind.
7216 enum UsageKind {
7217 /// A read of an object. Multiple unsequenced reads are OK.
7218 UK_Use,
7219 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007220 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007221 UK_ModAsValue,
7222 /// A modification of an object which is not sequenced before the value
7223 /// computation of the expression, such as n++.
7224 UK_ModAsSideEffect,
7225
7226 UK_Count = UK_ModAsSideEffect + 1
7227 };
7228
7229 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007230 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007231 Expr *Use;
7232 SequenceTree::Seq Seq;
7233 };
7234
7235 struct UsageInfo {
7236 UsageInfo() : Diagnosed(false) {}
7237 Usage Uses[UK_Count];
7238 /// Have we issued a diagnostic for this variable already?
7239 bool Diagnosed;
7240 };
7241 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7242
7243 Sema &SemaRef;
7244 /// Sequenced regions within the expression.
7245 SequenceTree Tree;
7246 /// Declaration modifications and references which we have seen.
7247 UsageInfoMap UsageMap;
7248 /// The region we are currently within.
7249 SequenceTree::Seq Region;
7250 /// Filled in with declarations which were modified as a side-effect
7251 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007252 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007253 /// Expressions to check later. We defer checking these to reduce
7254 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007255 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007256
7257 /// RAII object wrapping the visitation of a sequenced subexpression of an
7258 /// expression. At the end of this process, the side-effects of the evaluation
7259 /// become sequenced with respect to the value computation of the result, so
7260 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7261 /// UK_ModAsValue.
7262 struct SequencedSubexpression {
7263 SequencedSubexpression(SequenceChecker &Self)
7264 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7265 Self.ModAsSideEffect = &ModAsSideEffect;
7266 }
7267 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007268 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7269 MI != ME; ++MI) {
7270 UsageInfo &U = Self.UsageMap[MI->first];
7271 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7272 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7273 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007274 }
7275 Self.ModAsSideEffect = OldModAsSideEffect;
7276 }
7277
7278 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007279 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7280 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007281 };
7282
Richard Smith40238f02013-06-20 22:21:56 +00007283 /// RAII object wrapping the visitation of a subexpression which we might
7284 /// choose to evaluate as a constant. If any subexpression is evaluated and
7285 /// found to be non-constant, this allows us to suppress the evaluation of
7286 /// the outer expression.
7287 class EvaluationTracker {
7288 public:
7289 EvaluationTracker(SequenceChecker &Self)
7290 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7291 Self.EvalTracker = this;
7292 }
7293 ~EvaluationTracker() {
7294 Self.EvalTracker = Prev;
7295 if (Prev)
7296 Prev->EvalOK &= EvalOK;
7297 }
7298
7299 bool evaluate(const Expr *E, bool &Result) {
7300 if (!EvalOK || E->isValueDependent())
7301 return false;
7302 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7303 return EvalOK;
7304 }
7305
7306 private:
7307 SequenceChecker &Self;
7308 EvaluationTracker *Prev;
7309 bool EvalOK;
7310 } *EvalTracker;
7311
Richard Smithc406cb72013-01-17 01:17:56 +00007312 /// \brief Find the object which is produced by the specified expression,
7313 /// if any.
7314 Object getObject(Expr *E, bool Mod) const {
7315 E = E->IgnoreParenCasts();
7316 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7317 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7318 return getObject(UO->getSubExpr(), Mod);
7319 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7320 if (BO->getOpcode() == BO_Comma)
7321 return getObject(BO->getRHS(), Mod);
7322 if (Mod && BO->isAssignmentOp())
7323 return getObject(BO->getLHS(), Mod);
7324 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7325 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7326 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7327 return ME->getMemberDecl();
7328 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7329 // FIXME: If this is a reference, map through to its value.
7330 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007331 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007332 }
7333
7334 /// \brief Note that an object was modified or used by an expression.
7335 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7336 Usage &U = UI.Uses[UK];
7337 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7338 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7339 ModAsSideEffect->push_back(std::make_pair(O, U));
7340 U.Use = Ref;
7341 U.Seq = Region;
7342 }
7343 }
7344 /// \brief Check whether a modification or use conflicts with a prior usage.
7345 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7346 bool IsModMod) {
7347 if (UI.Diagnosed)
7348 return;
7349
7350 const Usage &U = UI.Uses[OtherKind];
7351 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7352 return;
7353
7354 Expr *Mod = U.Use;
7355 Expr *ModOrUse = Ref;
7356 if (OtherKind == UK_Use)
7357 std::swap(Mod, ModOrUse);
7358
7359 SemaRef.Diag(Mod->getExprLoc(),
7360 IsModMod ? diag::warn_unsequenced_mod_mod
7361 : diag::warn_unsequenced_mod_use)
7362 << O << SourceRange(ModOrUse->getExprLoc());
7363 UI.Diagnosed = true;
7364 }
7365
7366 void notePreUse(Object O, Expr *Use) {
7367 UsageInfo &U = UsageMap[O];
7368 // Uses conflict with other modifications.
7369 checkUsage(O, U, Use, UK_ModAsValue, false);
7370 }
7371 void notePostUse(Object O, Expr *Use) {
7372 UsageInfo &U = UsageMap[O];
7373 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7374 addUsage(U, O, Use, UK_Use);
7375 }
7376
7377 void notePreMod(Object O, Expr *Mod) {
7378 UsageInfo &U = UsageMap[O];
7379 // Modifications conflict with other modifications and with uses.
7380 checkUsage(O, U, Mod, UK_ModAsValue, true);
7381 checkUsage(O, U, Mod, UK_Use, false);
7382 }
7383 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7384 UsageInfo &U = UsageMap[O];
7385 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7386 addUsage(U, O, Use, UK);
7387 }
7388
7389public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007390 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007391 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7392 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007393 Visit(E);
7394 }
7395
7396 void VisitStmt(Stmt *S) {
7397 // Skip all statements which aren't expressions for now.
7398 }
7399
7400 void VisitExpr(Expr *E) {
7401 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007402 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007403 }
7404
7405 void VisitCastExpr(CastExpr *E) {
7406 Object O = Object();
7407 if (E->getCastKind() == CK_LValueToRValue)
7408 O = getObject(E->getSubExpr(), false);
7409
7410 if (O)
7411 notePreUse(O, E);
7412 VisitExpr(E);
7413 if (O)
7414 notePostUse(O, E);
7415 }
7416
7417 void VisitBinComma(BinaryOperator *BO) {
7418 // C++11 [expr.comma]p1:
7419 // Every value computation and side effect associated with the left
7420 // expression is sequenced before every value computation and side
7421 // effect associated with the right expression.
7422 SequenceTree::Seq LHS = Tree.allocate(Region);
7423 SequenceTree::Seq RHS = Tree.allocate(Region);
7424 SequenceTree::Seq OldRegion = Region;
7425
7426 {
7427 SequencedSubexpression SeqLHS(*this);
7428 Region = LHS;
7429 Visit(BO->getLHS());
7430 }
7431
7432 Region = RHS;
7433 Visit(BO->getRHS());
7434
7435 Region = OldRegion;
7436
7437 // Forget that LHS and RHS are sequenced. They are both unsequenced
7438 // with respect to other stuff.
7439 Tree.merge(LHS);
7440 Tree.merge(RHS);
7441 }
7442
7443 void VisitBinAssign(BinaryOperator *BO) {
7444 // The modification is sequenced after the value computation of the LHS
7445 // and RHS, so check it before inspecting the operands and update the
7446 // map afterwards.
7447 Object O = getObject(BO->getLHS(), true);
7448 if (!O)
7449 return VisitExpr(BO);
7450
7451 notePreMod(O, BO);
7452
7453 // C++11 [expr.ass]p7:
7454 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7455 // only once.
7456 //
7457 // Therefore, for a compound assignment operator, O is considered used
7458 // everywhere except within the evaluation of E1 itself.
7459 if (isa<CompoundAssignOperator>(BO))
7460 notePreUse(O, BO);
7461
7462 Visit(BO->getLHS());
7463
7464 if (isa<CompoundAssignOperator>(BO))
7465 notePostUse(O, BO);
7466
7467 Visit(BO->getRHS());
7468
Richard Smith83e37bee2013-06-26 23:16:51 +00007469 // C++11 [expr.ass]p1:
7470 // the assignment is sequenced [...] before the value computation of the
7471 // assignment expression.
7472 // C11 6.5.16/3 has no such rule.
7473 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7474 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007475 }
7476 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7477 VisitBinAssign(CAO);
7478 }
7479
7480 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7481 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7482 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7483 Object O = getObject(UO->getSubExpr(), true);
7484 if (!O)
7485 return VisitExpr(UO);
7486
7487 notePreMod(O, UO);
7488 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007489 // C++11 [expr.pre.incr]p1:
7490 // the expression ++x is equivalent to x+=1
7491 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7492 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007493 }
7494
7495 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7496 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7497 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7498 Object O = getObject(UO->getSubExpr(), true);
7499 if (!O)
7500 return VisitExpr(UO);
7501
7502 notePreMod(O, UO);
7503 Visit(UO->getSubExpr());
7504 notePostMod(O, UO, UK_ModAsSideEffect);
7505 }
7506
7507 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7508 void VisitBinLOr(BinaryOperator *BO) {
7509 // The side-effects of the LHS of an '&&' are sequenced before the
7510 // value computation of the RHS, and hence before the value computation
7511 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7512 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007513 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007514 {
7515 SequencedSubexpression Sequenced(*this);
7516 Visit(BO->getLHS());
7517 }
7518
7519 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007520 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007521 if (!Result)
7522 Visit(BO->getRHS());
7523 } else {
7524 // Check for unsequenced operations in the RHS, treating it as an
7525 // entirely separate evaluation.
7526 //
7527 // FIXME: If there are operations in the RHS which are unsequenced
7528 // with respect to operations outside the RHS, and those operations
7529 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007530 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007531 }
Richard Smithc406cb72013-01-17 01:17:56 +00007532 }
7533 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007534 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007535 {
7536 SequencedSubexpression Sequenced(*this);
7537 Visit(BO->getLHS());
7538 }
7539
7540 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007541 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007542 if (Result)
7543 Visit(BO->getRHS());
7544 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007545 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007546 }
Richard Smithc406cb72013-01-17 01:17:56 +00007547 }
7548
7549 // Only visit the condition, unless we can be sure which subexpression will
7550 // be chosen.
7551 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007552 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007553 {
7554 SequencedSubexpression Sequenced(*this);
7555 Visit(CO->getCond());
7556 }
Richard Smithc406cb72013-01-17 01:17:56 +00007557
7558 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007559 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007560 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007561 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007562 WorkList.push_back(CO->getTrueExpr());
7563 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007564 }
Richard Smithc406cb72013-01-17 01:17:56 +00007565 }
7566
Richard Smithe3dbfe02013-06-30 10:40:20 +00007567 void VisitCallExpr(CallExpr *CE) {
7568 // C++11 [intro.execution]p15:
7569 // When calling a function [...], every value computation and side effect
7570 // associated with any argument expression, or with the postfix expression
7571 // designating the called function, is sequenced before execution of every
7572 // expression or statement in the body of the function [and thus before
7573 // the value computation of its result].
7574 SequencedSubexpression Sequenced(*this);
7575 Base::VisitCallExpr(CE);
7576
7577 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7578 }
7579
Richard Smithc406cb72013-01-17 01:17:56 +00007580 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007581 // This is a call, so all subexpressions are sequenced before the result.
7582 SequencedSubexpression Sequenced(*this);
7583
Richard Smithc406cb72013-01-17 01:17:56 +00007584 if (!CCE->isListInitialization())
7585 return VisitExpr(CCE);
7586
7587 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007588 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007589 SequenceTree::Seq Parent = Region;
7590 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7591 E = CCE->arg_end();
7592 I != E; ++I) {
7593 Region = Tree.allocate(Parent);
7594 Elts.push_back(Region);
7595 Visit(*I);
7596 }
7597
7598 // Forget that the initializers are sequenced.
7599 Region = Parent;
7600 for (unsigned I = 0; I < Elts.size(); ++I)
7601 Tree.merge(Elts[I]);
7602 }
7603
7604 void VisitInitListExpr(InitListExpr *ILE) {
7605 if (!SemaRef.getLangOpts().CPlusPlus11)
7606 return VisitExpr(ILE);
7607
7608 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007609 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007610 SequenceTree::Seq Parent = Region;
7611 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7612 Expr *E = ILE->getInit(I);
7613 if (!E) continue;
7614 Region = Tree.allocate(Parent);
7615 Elts.push_back(Region);
7616 Visit(E);
7617 }
7618
7619 // Forget that the initializers are sequenced.
7620 Region = Parent;
7621 for (unsigned I = 0; I < Elts.size(); ++I)
7622 Tree.merge(Elts[I]);
7623 }
7624};
7625}
7626
7627void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007628 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007629 WorkList.push_back(E);
7630 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007631 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007632 SequenceChecker(*this, Item, WorkList);
7633 }
Richard Smithc406cb72013-01-17 01:17:56 +00007634}
7635
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007636void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7637 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007638 CheckImplicitConversions(E, CheckLoc);
7639 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007640 if (!IsConstexpr && !E->isValueDependent())
7641 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007642}
7643
John McCall1f425642010-11-11 03:21:53 +00007644void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7645 FieldDecl *BitField,
7646 Expr *Init) {
7647 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7648}
7649
Mike Stump0c2ec772010-01-21 03:59:47 +00007650/// CheckParmsForFunctionDef - Check that the parameters of the given
7651/// function are appropriate for the definition of a function. This
7652/// takes care of any checks that cannot be performed on the
7653/// declaration itself, e.g., that the types of each of the function
7654/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00007655bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7656 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00007657 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007658 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00007659 for (; P != PEnd; ++P) {
7660 ParmVarDecl *Param = *P;
7661
Mike Stump0c2ec772010-01-21 03:59:47 +00007662 // C99 6.7.5.3p4: the parameters in a parameter type list in a
7663 // function declarator that is part of a function definition of
7664 // that function shall not have incomplete type.
7665 //
7666 // This is also C++ [dcl.fct]p6.
7667 if (!Param->isInvalidDecl() &&
7668 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007669 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00007670 Param->setInvalidDecl();
7671 HasInvalidParm = true;
7672 }
7673
7674 // C99 6.9.1p5: If the declarator includes a parameter type list, the
7675 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00007676 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00007677 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00007678 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007679 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00007680 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00007681
7682 // C99 6.7.5.3p12:
7683 // If the function declarator is not part of a definition of that
7684 // function, parameters may have incomplete type and may use the [*]
7685 // notation in their sequences of declarator specifiers to specify
7686 // variable length array types.
7687 QualType PType = Param->getOriginalType();
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007688 while (const ArrayType *AT = Context.getAsArrayType(PType)) {
Sam Weinigdeb55d52010-02-01 05:02:49 +00007689 if (AT->getSizeModifier() == ArrayType::Star) {
Stefanus Du Toitb3318502013-03-01 21:41:22 +00007690 // FIXME: This diagnostic should point the '[*]' if source-location
Sam Weinigdeb55d52010-02-01 05:02:49 +00007691 // information is added for it.
7692 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007693 break;
Sam Weinigdeb55d52010-02-01 05:02:49 +00007694 }
Fariborz Jahanian4289a5a2013-04-29 22:01:25 +00007695 PType= AT->getElementType();
Sam Weinigdeb55d52010-02-01 05:02:49 +00007696 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007697
7698 // MSVC destroys objects passed by value in the callee. Therefore a
7699 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007700 // object's destructor. However, we don't perform any direct access check
7701 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00007702 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7703 .getCXXABI()
7704 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00007705 if (!Param->isInvalidDecl()) {
7706 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7707 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7708 if (!ClassDecl->isInvalidDecl() &&
7709 !ClassDecl->hasIrrelevantDestructor() &&
7710 !ClassDecl->isDependentContext()) {
7711 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7712 MarkFunctionReferenced(Param->getLocation(), Destructor);
7713 DiagnoseUseOfDecl(Destructor, Param->getLocation());
7714 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00007715 }
7716 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00007717 }
Mike Stump0c2ec772010-01-21 03:59:47 +00007718 }
7719
7720 return HasInvalidParm;
7721}
John McCall2b5c1b22010-08-12 21:44:57 +00007722
7723/// CheckCastAlign - Implements -Wcast-align, which warns when a
7724/// pointer cast increases the alignment requirements.
7725void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7726 // This is actually a lot of work to potentially be doing on every
7727 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007728 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00007729 return;
7730
7731 // Ignore dependent types.
7732 if (T->isDependentType() || Op->getType()->isDependentType())
7733 return;
7734
7735 // Require that the destination be a pointer type.
7736 const PointerType *DestPtr = T->getAs<PointerType>();
7737 if (!DestPtr) return;
7738
7739 // If the destination has alignment 1, we're done.
7740 QualType DestPointee = DestPtr->getPointeeType();
7741 if (DestPointee->isIncompleteType()) return;
7742 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7743 if (DestAlign.isOne()) return;
7744
7745 // Require that the source be a pointer type.
7746 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7747 if (!SrcPtr) return;
7748 QualType SrcPointee = SrcPtr->getPointeeType();
7749
7750 // Whitelist casts from cv void*. We already implicitly
7751 // whitelisted casts to cv void*, since they have alignment 1.
7752 // Also whitelist casts involving incomplete types, which implicitly
7753 // includes 'void'.
7754 if (SrcPointee->isIncompleteType()) return;
7755
7756 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7757 if (SrcAlign >= DestAlign) return;
7758
7759 Diag(TRange.getBegin(), diag::warn_cast_align)
7760 << Op->getType() << T
7761 << static_cast<unsigned>(SrcAlign.getQuantity())
7762 << static_cast<unsigned>(DestAlign.getQuantity())
7763 << TRange << Op->getSourceRange();
7764}
7765
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007766static const Type* getElementType(const Expr *BaseExpr) {
7767 const Type* EltType = BaseExpr->getType().getTypePtr();
7768 if (EltType->isAnyPointerType())
7769 return EltType->getPointeeType().getTypePtr();
7770 else if (EltType->isArrayType())
7771 return EltType->getBaseElementTypeUnsafe();
7772 return EltType;
7773}
7774
Chandler Carruth28389f02011-08-05 09:10:50 +00007775/// \brief Check whether this array fits the idiom of a size-one tail padded
7776/// array member of a struct.
7777///
7778/// We avoid emitting out-of-bounds access warnings for such arrays as they are
7779/// commonly used to emulate flexible arrays in C89 code.
7780static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7781 const NamedDecl *ND) {
7782 if (Size != 1 || !ND) return false;
7783
7784 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7785 if (!FD) return false;
7786
7787 // Don't consider sizes resulting from macro expansions or template argument
7788 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00007789
7790 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007791 while (TInfo) {
7792 TypeLoc TL = TInfo->getTypeLoc();
7793 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00007794 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7795 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007796 TInfo = TDL->getTypeSourceInfo();
7797 continue;
7798 }
David Blaikie6adc78e2013-02-18 22:06:02 +00007799 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7800 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00007801 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7802 return false;
7803 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00007804 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00007805 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007806
7807 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00007808 if (!RD) return false;
7809 if (RD->isUnion()) return false;
7810 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7811 if (!CRD->isStandardLayout()) return false;
7812 }
Chandler Carruth28389f02011-08-05 09:10:50 +00007813
Benjamin Kramer8c543672011-08-06 03:04:42 +00007814 // See if this is the last field decl in the record.
7815 const Decl *D = FD;
7816 while ((D = D->getNextDeclInContext()))
7817 if (isa<FieldDecl>(D))
7818 return false;
7819 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00007820}
7821
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007822void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007823 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00007824 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007825 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007826 if (IndexExpr->isValueDependent())
7827 return;
7828
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00007829 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007830 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007831 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007832 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007833 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00007834 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00007835
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007836 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007837 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00007838 return;
Richard Smith13f67182011-12-16 19:31:14 +00007839 if (IndexNegated)
7840 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00007841
Craig Topperc3ec1492014-05-26 06:22:03 +00007842 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00007843 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7844 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00007845 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00007846 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00007847
Ted Kremeneke4b316c2011-02-23 23:06:04 +00007848 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007849 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00007850 if (!size.isStrictlyPositive())
7851 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007852
7853 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00007854 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007855 // Make sure we're comparing apples to apples when comparing index to size
7856 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7857 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00007858 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00007859 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007860 if (ptrarith_typesize != array_typesize) {
7861 // There's a cast to a different size type involved
7862 uint64_t ratio = array_typesize / ptrarith_typesize;
7863 // TODO: Be smarter about handling cases where array_typesize is not a
7864 // multiple of ptrarith_typesize
7865 if (ptrarith_typesize * ratio == array_typesize)
7866 size *= llvm::APInt(size.getBitWidth(), ratio);
7867 }
7868 }
7869
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007870 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007871 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007872 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007873 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00007874
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007875 // For array subscripting the index must be less than size, but for pointer
7876 // arithmetic also allow the index (offset) to be equal to size since
7877 // computing the next address after the end of the array is legal and
7878 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00007879 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00007880 return;
7881
7882 // Also don't warn for arrays of size 1 which are members of some
7883 // structure. These are often used to approximate flexible arrays in C89
7884 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007885 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00007886 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007887
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007888 // Suppress the warning if the subscript expression (as identified by the
7889 // ']' location) and the index expression are both from macro expansions
7890 // within a system header.
7891 if (ASE) {
7892 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7893 ASE->getRBracketLoc());
7894 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7895 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7896 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00007897 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007898 return;
7899 }
7900 }
7901
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007902 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007903 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007904 DiagID = diag::warn_array_index_exceeds_bounds;
7905
7906 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7907 PDiag(DiagID) << index.toString(10, true)
7908 << size.toString(10, true)
7909 << (unsigned)size.getLimitedValue(~0U)
7910 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00007911 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007912 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007913 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007914 DiagID = diag::warn_ptr_arith_precedes_bounds;
7915 if (index.isNegative()) index = -index;
7916 }
7917
7918 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7919 PDiag(DiagID) << index.toString(10, true)
7920 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00007921 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00007922
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00007923 if (!ND) {
7924 // Try harder to find a NamedDecl to point at in the note.
7925 while (const ArraySubscriptExpr *ASE =
7926 dyn_cast<ArraySubscriptExpr>(BaseExpr))
7927 BaseExpr = ASE->getBase()->IgnoreParenCasts();
7928 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7929 ND = dyn_cast<NamedDecl>(DRE->getDecl());
7930 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7931 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7932 }
7933
Chandler Carruth1af88f12011-02-17 21:10:52 +00007934 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007935 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7936 PDiag(diag::note_array_index_out_of_bounds)
7937 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00007938}
7939
Ted Kremenekdf26df72011-03-01 18:41:00 +00007940void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007941 int AllowOnePastEnd = 0;
7942 while (expr) {
7943 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00007944 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007945 case Stmt::ArraySubscriptExprClass: {
7946 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00007947 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007948 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00007949 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007950 }
7951 case Stmt::UnaryOperatorClass: {
7952 // Only unwrap the * and & unary operators
7953 const UnaryOperator *UO = cast<UnaryOperator>(expr);
7954 expr = UO->getSubExpr();
7955 switch (UO->getOpcode()) {
7956 case UO_AddrOf:
7957 AllowOnePastEnd++;
7958 break;
7959 case UO_Deref:
7960 AllowOnePastEnd--;
7961 break;
7962 default:
7963 return;
7964 }
7965 break;
7966 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007967 case Stmt::ConditionalOperatorClass: {
7968 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7969 if (const Expr *lhs = cond->getLHS())
7970 CheckArrayAccess(lhs);
7971 if (const Expr *rhs = cond->getRHS())
7972 CheckArrayAccess(rhs);
7973 return;
7974 }
7975 default:
7976 return;
7977 }
Peter Collingbourne91147592011-04-15 00:35:48 +00007978 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00007979}
John McCall31168b02011-06-15 23:02:42 +00007980
7981//===--- CHECK: Objective-C retain cycles ----------------------------------//
7982
7983namespace {
7984 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00007985 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00007986 VarDecl *Variable;
7987 SourceRange Range;
7988 SourceLocation Loc;
7989 bool Indirect;
7990
7991 void setLocsFrom(Expr *e) {
7992 Loc = e->getExprLoc();
7993 Range = e->getSourceRange();
7994 }
7995 };
7996}
7997
7998/// Consider whether capturing the given variable can possibly lead to
7999/// a retain cycle.
8000static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008001 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008002 // lifetime. In MRR, it's captured strongly if the variable is
8003 // __block and has an appropriate type.
8004 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8005 return false;
8006
8007 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008008 if (ref)
8009 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008010 return true;
8011}
8012
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008013static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008014 while (true) {
8015 e = e->IgnoreParens();
8016 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8017 switch (cast->getCastKind()) {
8018 case CK_BitCast:
8019 case CK_LValueBitCast:
8020 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008021 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008022 e = cast->getSubExpr();
8023 continue;
8024
John McCall31168b02011-06-15 23:02:42 +00008025 default:
8026 return false;
8027 }
8028 }
8029
8030 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8031 ObjCIvarDecl *ivar = ref->getDecl();
8032 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8033 return false;
8034
8035 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008036 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008037 return false;
8038
8039 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8040 owner.Indirect = true;
8041 return true;
8042 }
8043
8044 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8045 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8046 if (!var) return false;
8047 return considerVariable(var, ref, owner);
8048 }
8049
John McCall31168b02011-06-15 23:02:42 +00008050 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8051 if (member->isArrow()) return false;
8052
8053 // Don't count this as an indirect ownership.
8054 e = member->getBase();
8055 continue;
8056 }
8057
John McCallfe96e0b2011-11-06 09:01:30 +00008058 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8059 // Only pay attention to pseudo-objects on property references.
8060 ObjCPropertyRefExpr *pre
8061 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8062 ->IgnoreParens());
8063 if (!pre) return false;
8064 if (pre->isImplicitProperty()) return false;
8065 ObjCPropertyDecl *property = pre->getExplicitProperty();
8066 if (!property->isRetaining() &&
8067 !(property->getPropertyIvarDecl() &&
8068 property->getPropertyIvarDecl()->getType()
8069 .getObjCLifetime() == Qualifiers::OCL_Strong))
8070 return false;
8071
8072 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008073 if (pre->isSuperReceiver()) {
8074 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8075 if (!owner.Variable)
8076 return false;
8077 owner.Loc = pre->getLocation();
8078 owner.Range = pre->getSourceRange();
8079 return true;
8080 }
John McCallfe96e0b2011-11-06 09:01:30 +00008081 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8082 ->getSourceExpr());
8083 continue;
8084 }
8085
John McCall31168b02011-06-15 23:02:42 +00008086 // Array ivars?
8087
8088 return false;
8089 }
8090}
8091
8092namespace {
8093 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8094 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8095 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008096 Context(Context), Variable(variable), Capturer(nullptr),
8097 VarWillBeReased(false) {}
8098 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008099 VarDecl *Variable;
8100 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008101 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008102
8103 void VisitDeclRefExpr(DeclRefExpr *ref) {
8104 if (ref->getDecl() == Variable && !Capturer)
8105 Capturer = ref;
8106 }
8107
John McCall31168b02011-06-15 23:02:42 +00008108 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8109 if (Capturer) return;
8110 Visit(ref->getBase());
8111 if (Capturer && ref->isFreeIvar())
8112 Capturer = ref;
8113 }
8114
8115 void VisitBlockExpr(BlockExpr *block) {
8116 // Look inside nested blocks
8117 if (block->getBlockDecl()->capturesVariable(Variable))
8118 Visit(block->getBlockDecl()->getBody());
8119 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008120
8121 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8122 if (Capturer) return;
8123 if (OVE->getSourceExpr())
8124 Visit(OVE->getSourceExpr());
8125 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008126 void VisitBinaryOperator(BinaryOperator *BinOp) {
8127 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8128 return;
8129 Expr *LHS = BinOp->getLHS();
8130 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8131 if (DRE->getDecl() != Variable)
8132 return;
8133 if (Expr *RHS = BinOp->getRHS()) {
8134 RHS = RHS->IgnoreParenCasts();
8135 llvm::APSInt Value;
8136 VarWillBeReased =
8137 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8138 }
8139 }
8140 }
John McCall31168b02011-06-15 23:02:42 +00008141 };
8142}
8143
8144/// Check whether the given argument is a block which captures a
8145/// variable.
8146static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8147 assert(owner.Variable && owner.Loc.isValid());
8148
8149 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008150
8151 // Look through [^{...} copy] and Block_copy(^{...}).
8152 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8153 Selector Cmd = ME->getSelector();
8154 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8155 e = ME->getInstanceReceiver();
8156 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008157 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008158 e = e->IgnoreParenCasts();
8159 }
8160 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8161 if (CE->getNumArgs() == 1) {
8162 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008163 if (Fn) {
8164 const IdentifierInfo *FnI = Fn->getIdentifier();
8165 if (FnI && FnI->isStr("_Block_copy")) {
8166 e = CE->getArg(0)->IgnoreParenCasts();
8167 }
8168 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008169 }
8170 }
8171
John McCall31168b02011-06-15 23:02:42 +00008172 BlockExpr *block = dyn_cast<BlockExpr>(e);
8173 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008174 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008175
8176 FindCaptureVisitor visitor(S.Context, owner.Variable);
8177 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008178 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008179}
8180
8181static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8182 RetainCycleOwner &owner) {
8183 assert(capturer);
8184 assert(owner.Variable && owner.Loc.isValid());
8185
8186 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8187 << owner.Variable << capturer->getSourceRange();
8188 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8189 << owner.Indirect << owner.Range;
8190}
8191
8192/// Check for a keyword selector that starts with the word 'add' or
8193/// 'set'.
8194static bool isSetterLikeSelector(Selector sel) {
8195 if (sel.isUnarySelector()) return false;
8196
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008197 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008198 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008199 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008200 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008201 else if (str.startswith("add")) {
8202 // Specially whitelist 'addOperationWithBlock:'.
8203 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8204 return false;
8205 str = str.substr(3);
8206 }
John McCall31168b02011-06-15 23:02:42 +00008207 else
8208 return false;
8209
8210 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008211 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008212}
8213
Benjamin Kramer3a743452015-03-09 15:03:32 +00008214static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8215 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008216 if (S.NSMutableArrayPointer.isNull()) {
8217 IdentifierInfo *NSMutableArrayId =
8218 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8219 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8220 Message->getLocStart(),
8221 Sema::LookupOrdinaryName);
8222 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8223 if (!InterfaceDecl) {
8224 return None;
8225 }
8226 QualType NSMutableArrayObject =
8227 S.Context.getObjCInterfaceType(InterfaceDecl);
8228 S.NSMutableArrayPointer =
8229 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8230 }
8231
8232 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8233 return None;
8234 }
8235
8236 Selector Sel = Message->getSelector();
8237
8238 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8239 S.NSAPIObj->getNSArrayMethodKind(Sel);
8240 if (!MKOpt) {
8241 return None;
8242 }
8243
8244 NSAPI::NSArrayMethodKind MK = *MKOpt;
8245
8246 switch (MK) {
8247 case NSAPI::NSMutableArr_addObject:
8248 case NSAPI::NSMutableArr_insertObjectAtIndex:
8249 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8250 return 0;
8251 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8252 return 1;
8253
8254 default:
8255 return None;
8256 }
8257
8258 return None;
8259}
8260
8261static
8262Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8263 ObjCMessageExpr *Message) {
8264
8265 if (S.NSMutableDictionaryPointer.isNull()) {
8266 IdentifierInfo *NSMutableDictionaryId =
8267 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8268 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8269 Message->getLocStart(),
8270 Sema::LookupOrdinaryName);
8271 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8272 if (!InterfaceDecl) {
8273 return None;
8274 }
8275 QualType NSMutableDictionaryObject =
8276 S.Context.getObjCInterfaceType(InterfaceDecl);
8277 S.NSMutableDictionaryPointer =
8278 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8279 }
8280
8281 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8282 return None;
8283 }
8284
8285 Selector Sel = Message->getSelector();
8286
8287 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8288 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8289 if (!MKOpt) {
8290 return None;
8291 }
8292
8293 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8294
8295 switch (MK) {
8296 case NSAPI::NSMutableDict_setObjectForKey:
8297 case NSAPI::NSMutableDict_setValueForKey:
8298 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8299 return 0;
8300
8301 default:
8302 return None;
8303 }
8304
8305 return None;
8306}
8307
8308static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8309
8310 ObjCInterfaceDecl *InterfaceDecl;
8311 if (S.NSMutableSetPointer.isNull()) {
8312 IdentifierInfo *NSMutableSetId =
8313 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8314 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8315 Message->getLocStart(),
8316 Sema::LookupOrdinaryName);
8317 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8318 if (InterfaceDecl) {
8319 QualType NSMutableSetObject =
8320 S.Context.getObjCInterfaceType(InterfaceDecl);
8321 S.NSMutableSetPointer =
8322 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8323 }
8324 }
8325
8326 if (S.NSCountedSetPointer.isNull()) {
8327 IdentifierInfo *NSCountedSetId =
8328 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8329 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8330 Message->getLocStart(),
8331 Sema::LookupOrdinaryName);
8332 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8333 if (InterfaceDecl) {
8334 QualType NSCountedSetObject =
8335 S.Context.getObjCInterfaceType(InterfaceDecl);
8336 S.NSCountedSetPointer =
8337 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8338 }
8339 }
8340
8341 if (S.NSMutableOrderedSetPointer.isNull()) {
8342 IdentifierInfo *NSOrderedSetId =
8343 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8344 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8345 Message->getLocStart(),
8346 Sema::LookupOrdinaryName);
8347 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8348 if (InterfaceDecl) {
8349 QualType NSOrderedSetObject =
8350 S.Context.getObjCInterfaceType(InterfaceDecl);
8351 S.NSMutableOrderedSetPointer =
8352 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8353 }
8354 }
8355
8356 QualType ReceiverType = Message->getReceiverType();
8357
8358 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8359 ReceiverType == S.NSMutableSetPointer;
8360 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8361 ReceiverType == S.NSMutableOrderedSetPointer;
8362 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8363 ReceiverType == S.NSCountedSetPointer;
8364
8365 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8366 return None;
8367 }
8368
8369 Selector Sel = Message->getSelector();
8370
8371 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8372 if (!MKOpt) {
8373 return None;
8374 }
8375
8376 NSAPI::NSSetMethodKind MK = *MKOpt;
8377
8378 switch (MK) {
8379 case NSAPI::NSMutableSet_addObject:
8380 case NSAPI::NSOrderedSet_setObjectAtIndex:
8381 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8382 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8383 return 0;
8384 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8385 return 1;
8386 }
8387
8388 return None;
8389}
8390
8391void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8392 if (!Message->isInstanceMessage()) {
8393 return;
8394 }
8395
8396 Optional<int> ArgOpt;
8397
8398 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8399 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8400 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8401 return;
8402 }
8403
8404 int ArgIndex = *ArgOpt;
8405
8406 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8407 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8408 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8409 }
8410
8411 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8412 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8413 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8414 }
8415
8416 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8417 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8418 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8419 ValueDecl *Decl = ReceiverRE->getDecl();
8420 Diag(Message->getSourceRange().getBegin(),
8421 diag::warn_objc_circular_container)
8422 << Decl->getName();
8423 Diag(Decl->getLocation(),
8424 diag::note_objc_circular_container_declared_here)
8425 << Decl->getName();
8426 }
8427 }
8428 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8429 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8430 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8431 ObjCIvarDecl *Decl = IvarRE->getDecl();
8432 Diag(Message->getSourceRange().getBegin(),
8433 diag::warn_objc_circular_container)
8434 << Decl->getName();
8435 Diag(Decl->getLocation(),
8436 diag::note_objc_circular_container_declared_here)
8437 << Decl->getName();
8438 }
8439 }
8440 }
8441
8442}
8443
John McCall31168b02011-06-15 23:02:42 +00008444/// Check a message send to see if it's likely to cause a retain cycle.
8445void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8446 // Only check instance methods whose selector looks like a setter.
8447 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8448 return;
8449
8450 // Try to find a variable that the receiver is strongly owned by.
8451 RetainCycleOwner owner;
8452 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008453 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008454 return;
8455 } else {
8456 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8457 owner.Variable = getCurMethodDecl()->getSelfDecl();
8458 owner.Loc = msg->getSuperLoc();
8459 owner.Range = msg->getSuperLoc();
8460 }
8461
8462 // Check whether the receiver is captured by any of the arguments.
8463 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8464 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8465 return diagnoseRetainCycle(*this, capturer, owner);
8466}
8467
8468/// Check a property assign to see if it's likely to cause a retain cycle.
8469void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8470 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008471 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008472 return;
8473
8474 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8475 diagnoseRetainCycle(*this, capturer, owner);
8476}
8477
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008478void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8479 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008480 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008481 return;
8482
8483 // Because we don't have an expression for the variable, we have to set the
8484 // location explicitly here.
8485 Owner.Loc = Var->getLocation();
8486 Owner.Range = Var->getSourceRange();
8487
8488 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8489 diagnoseRetainCycle(*this, Capturer, Owner);
8490}
8491
Ted Kremenek9304da92012-12-21 08:04:28 +00008492static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8493 Expr *RHS, bool isProperty) {
8494 // Check if RHS is an Objective-C object literal, which also can get
8495 // immediately zapped in a weak reference. Note that we explicitly
8496 // allow ObjCStringLiterals, since those are designed to never really die.
8497 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008498
Ted Kremenek64873352012-12-21 22:46:35 +00008499 // This enum needs to match with the 'select' in
8500 // warn_objc_arc_literal_assign (off-by-1).
8501 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8502 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8503 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008504
8505 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008506 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008507 << (isProperty ? 0 : 1)
8508 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008509
8510 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008511}
8512
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008513static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8514 Qualifiers::ObjCLifetime LT,
8515 Expr *RHS, bool isProperty) {
8516 // Strip off any implicit cast added to get to the one ARC-specific.
8517 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8518 if (cast->getCastKind() == CK_ARCConsumeObject) {
8519 S.Diag(Loc, diag::warn_arc_retained_assign)
8520 << (LT == Qualifiers::OCL_ExplicitNone)
8521 << (isProperty ? 0 : 1)
8522 << RHS->getSourceRange();
8523 return true;
8524 }
8525 RHS = cast->getSubExpr();
8526 }
8527
8528 if (LT == Qualifiers::OCL_Weak &&
8529 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8530 return true;
8531
8532 return false;
8533}
8534
Ted Kremenekb36234d2012-12-21 08:04:20 +00008535bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8536 QualType LHS, Expr *RHS) {
8537 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8538
8539 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8540 return false;
8541
8542 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8543 return true;
8544
8545 return false;
8546}
8547
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008548void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8549 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008550 QualType LHSType;
8551 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008552 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008553 ObjCPropertyRefExpr *PRE
8554 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8555 if (PRE && !PRE->isImplicitProperty()) {
8556 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8557 if (PD)
8558 LHSType = PD->getType();
8559 }
8560
8561 if (LHSType.isNull())
8562 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008563
8564 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8565
8566 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008567 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008568 getCurFunction()->markSafeWeakUse(LHS);
8569 }
8570
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008571 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8572 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008573
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008574 // FIXME. Check for other life times.
8575 if (LT != Qualifiers::OCL_None)
8576 return;
8577
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008578 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008579 if (PRE->isImplicitProperty())
8580 return;
8581 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8582 if (!PD)
8583 return;
8584
Bill Wendling44426052012-12-20 19:22:21 +00008585 unsigned Attributes = PD->getPropertyAttributes();
8586 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008587 // when 'assign' attribute was not explicitly specified
8588 // by user, ignore it and rely on property type itself
8589 // for lifetime info.
8590 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8591 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8592 LHSType->isObjCRetainableType())
8593 return;
8594
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008595 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008596 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008597 Diag(Loc, diag::warn_arc_retained_property_assign)
8598 << RHS->getSourceRange();
8599 return;
8600 }
8601 RHS = cast->getSubExpr();
8602 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008603 }
Bill Wendling44426052012-12-20 19:22:21 +00008604 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008605 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8606 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008607 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008608 }
8609}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008610
8611//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8612
8613namespace {
8614bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8615 SourceLocation StmtLoc,
8616 const NullStmt *Body) {
8617 // Do not warn if the body is a macro that expands to nothing, e.g:
8618 //
8619 // #define CALL(x)
8620 // if (condition)
8621 // CALL(0);
8622 //
8623 if (Body->hasLeadingEmptyMacro())
8624 return false;
8625
8626 // Get line numbers of statement and body.
8627 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008628 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008629 &StmtLineInvalid);
8630 if (StmtLineInvalid)
8631 return false;
8632
8633 bool BodyLineInvalid;
8634 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8635 &BodyLineInvalid);
8636 if (BodyLineInvalid)
8637 return false;
8638
8639 // Warn if null statement and body are on the same line.
8640 if (StmtLine != BodyLine)
8641 return false;
8642
8643 return true;
8644}
8645} // Unnamed namespace
8646
8647void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8648 const Stmt *Body,
8649 unsigned DiagID) {
8650 // Since this is a syntactic check, don't emit diagnostic for template
8651 // instantiations, this just adds noise.
8652 if (CurrentInstantiationScope)
8653 return;
8654
8655 // The body should be a null statement.
8656 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8657 if (!NBody)
8658 return;
8659
8660 // Do the usual checks.
8661 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8662 return;
8663
8664 Diag(NBody->getSemiLoc(), DiagID);
8665 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8666}
8667
8668void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8669 const Stmt *PossibleBody) {
8670 assert(!CurrentInstantiationScope); // Ensured by caller
8671
8672 SourceLocation StmtLoc;
8673 const Stmt *Body;
8674 unsigned DiagID;
8675 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8676 StmtLoc = FS->getRParenLoc();
8677 Body = FS->getBody();
8678 DiagID = diag::warn_empty_for_body;
8679 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8680 StmtLoc = WS->getCond()->getSourceRange().getEnd();
8681 Body = WS->getBody();
8682 DiagID = diag::warn_empty_while_body;
8683 } else
8684 return; // Neither `for' nor `while'.
8685
8686 // The body should be a null statement.
8687 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8688 if (!NBody)
8689 return;
8690
8691 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008692 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008693 return;
8694
8695 // Do the usual checks.
8696 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8697 return;
8698
8699 // `for(...);' and `while(...);' are popular idioms, so in order to keep
8700 // noise level low, emit diagnostics only if for/while is followed by a
8701 // CompoundStmt, e.g.:
8702 // for (int i = 0; i < n; i++);
8703 // {
8704 // a(i);
8705 // }
8706 // or if for/while is followed by a statement with more indentation
8707 // than for/while itself:
8708 // for (int i = 0; i < n; i++);
8709 // a(i);
8710 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8711 if (!ProbableTypo) {
8712 bool BodyColInvalid;
8713 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8714 PossibleBody->getLocStart(),
8715 &BodyColInvalid);
8716 if (BodyColInvalid)
8717 return;
8718
8719 bool StmtColInvalid;
8720 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8721 S->getLocStart(),
8722 &StmtColInvalid);
8723 if (StmtColInvalid)
8724 return;
8725
8726 if (BodyCol > StmtCol)
8727 ProbableTypo = true;
8728 }
8729
8730 if (ProbableTypo) {
8731 Diag(NBody->getSemiLoc(), DiagID);
8732 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8733 }
8734}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008735
Richard Trieu36d0b2b2015-01-13 02:32:02 +00008736//===--- CHECK: Warn on self move with std::move. -------------------------===//
8737
8738/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8739void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8740 SourceLocation OpLoc) {
8741
8742 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8743 return;
8744
8745 if (!ActiveTemplateInstantiations.empty())
8746 return;
8747
8748 // Strip parens and casts away.
8749 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8750 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8751
8752 // Check for a call expression
8753 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8754 if (!CE || CE->getNumArgs() != 1)
8755 return;
8756
8757 // Check for a call to std::move
8758 const FunctionDecl *FD = CE->getDirectCallee();
8759 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8760 !FD->getIdentifier()->isStr("move"))
8761 return;
8762
8763 // Get argument from std::move
8764 RHSExpr = CE->getArg(0);
8765
8766 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8767 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8768
8769 // Two DeclRefExpr's, check that the decls are the same.
8770 if (LHSDeclRef && RHSDeclRef) {
8771 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8772 return;
8773 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8774 RHSDeclRef->getDecl()->getCanonicalDecl())
8775 return;
8776
8777 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8778 << LHSExpr->getSourceRange()
8779 << RHSExpr->getSourceRange();
8780 return;
8781 }
8782
8783 // Member variables require a different approach to check for self moves.
8784 // MemberExpr's are the same if every nested MemberExpr refers to the same
8785 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8786 // the base Expr's are CXXThisExpr's.
8787 const Expr *LHSBase = LHSExpr;
8788 const Expr *RHSBase = RHSExpr;
8789 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8790 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8791 if (!LHSME || !RHSME)
8792 return;
8793
8794 while (LHSME && RHSME) {
8795 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8796 RHSME->getMemberDecl()->getCanonicalDecl())
8797 return;
8798
8799 LHSBase = LHSME->getBase();
8800 RHSBase = RHSME->getBase();
8801 LHSME = dyn_cast<MemberExpr>(LHSBase);
8802 RHSME = dyn_cast<MemberExpr>(RHSBase);
8803 }
8804
8805 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8806 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8807 if (LHSDeclRef && RHSDeclRef) {
8808 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8809 return;
8810 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8811 RHSDeclRef->getDecl()->getCanonicalDecl())
8812 return;
8813
8814 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8815 << LHSExpr->getSourceRange()
8816 << RHSExpr->getSourceRange();
8817 return;
8818 }
8819
8820 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8821 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8822 << LHSExpr->getSourceRange()
8823 << RHSExpr->getSourceRange();
8824}
8825
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008826//===--- Layout compatibility ----------------------------------------------//
8827
8828namespace {
8829
8830bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8831
8832/// \brief Check if two enumeration types are layout-compatible.
8833bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8834 // C++11 [dcl.enum] p8:
8835 // Two enumeration types are layout-compatible if they have the same
8836 // underlying type.
8837 return ED1->isComplete() && ED2->isComplete() &&
8838 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8839}
8840
8841/// \brief Check if two fields are layout-compatible.
8842bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8843 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8844 return false;
8845
8846 if (Field1->isBitField() != Field2->isBitField())
8847 return false;
8848
8849 if (Field1->isBitField()) {
8850 // Make sure that the bit-fields are the same length.
8851 unsigned Bits1 = Field1->getBitWidthValue(C);
8852 unsigned Bits2 = Field2->getBitWidthValue(C);
8853
8854 if (Bits1 != Bits2)
8855 return false;
8856 }
8857
8858 return true;
8859}
8860
8861/// \brief Check if two standard-layout structs are layout-compatible.
8862/// (C++11 [class.mem] p17)
8863bool isLayoutCompatibleStruct(ASTContext &C,
8864 RecordDecl *RD1,
8865 RecordDecl *RD2) {
8866 // If both records are C++ classes, check that base classes match.
8867 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8868 // If one of records is a CXXRecordDecl we are in C++ mode,
8869 // thus the other one is a CXXRecordDecl, too.
8870 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8871 // Check number of base classes.
8872 if (D1CXX->getNumBases() != D2CXX->getNumBases())
8873 return false;
8874
8875 // Check the base classes.
8876 for (CXXRecordDecl::base_class_const_iterator
8877 Base1 = D1CXX->bases_begin(),
8878 BaseEnd1 = D1CXX->bases_end(),
8879 Base2 = D2CXX->bases_begin();
8880 Base1 != BaseEnd1;
8881 ++Base1, ++Base2) {
8882 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8883 return false;
8884 }
8885 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8886 // If only RD2 is a C++ class, it should have zero base classes.
8887 if (D2CXX->getNumBases() > 0)
8888 return false;
8889 }
8890
8891 // Check the fields.
8892 RecordDecl::field_iterator Field2 = RD2->field_begin(),
8893 Field2End = RD2->field_end(),
8894 Field1 = RD1->field_begin(),
8895 Field1End = RD1->field_end();
8896 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8897 if (!isLayoutCompatible(C, *Field1, *Field2))
8898 return false;
8899 }
8900 if (Field1 != Field1End || Field2 != Field2End)
8901 return false;
8902
8903 return true;
8904}
8905
8906/// \brief Check if two standard-layout unions are layout-compatible.
8907/// (C++11 [class.mem] p18)
8908bool isLayoutCompatibleUnion(ASTContext &C,
8909 RecordDecl *RD1,
8910 RecordDecl *RD2) {
8911 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008912 for (auto *Field2 : RD2->fields())
8913 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008914
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008915 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008916 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8917 I = UnmatchedFields.begin(),
8918 E = UnmatchedFields.end();
8919
8920 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00008921 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00008922 bool Result = UnmatchedFields.erase(*I);
8923 (void) Result;
8924 assert(Result);
8925 break;
8926 }
8927 }
8928 if (I == E)
8929 return false;
8930 }
8931
8932 return UnmatchedFields.empty();
8933}
8934
8935bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8936 if (RD1->isUnion() != RD2->isUnion())
8937 return false;
8938
8939 if (RD1->isUnion())
8940 return isLayoutCompatibleUnion(C, RD1, RD2);
8941 else
8942 return isLayoutCompatibleStruct(C, RD1, RD2);
8943}
8944
8945/// \brief Check if two types are layout-compatible in C++11 sense.
8946bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8947 if (T1.isNull() || T2.isNull())
8948 return false;
8949
8950 // C++11 [basic.types] p11:
8951 // If two types T1 and T2 are the same type, then T1 and T2 are
8952 // layout-compatible types.
8953 if (C.hasSameType(T1, T2))
8954 return true;
8955
8956 T1 = T1.getCanonicalType().getUnqualifiedType();
8957 T2 = T2.getCanonicalType().getUnqualifiedType();
8958
8959 const Type::TypeClass TC1 = T1->getTypeClass();
8960 const Type::TypeClass TC2 = T2->getTypeClass();
8961
8962 if (TC1 != TC2)
8963 return false;
8964
8965 if (TC1 == Type::Enum) {
8966 return isLayoutCompatible(C,
8967 cast<EnumType>(T1)->getDecl(),
8968 cast<EnumType>(T2)->getDecl());
8969 } else if (TC1 == Type::Record) {
8970 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8971 return false;
8972
8973 return isLayoutCompatible(C,
8974 cast<RecordType>(T1)->getDecl(),
8975 cast<RecordType>(T2)->getDecl());
8976 }
8977
8978 return false;
8979}
8980}
8981
8982//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8983
8984namespace {
8985/// \brief Given a type tag expression find the type tag itself.
8986///
8987/// \param TypeExpr Type tag expression, as it appears in user's code.
8988///
8989/// \param VD Declaration of an identifier that appears in a type tag.
8990///
8991/// \param MagicValue Type tag magic value.
8992bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8993 const ValueDecl **VD, uint64_t *MagicValue) {
8994 while(true) {
8995 if (!TypeExpr)
8996 return false;
8997
8998 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8999
9000 switch (TypeExpr->getStmtClass()) {
9001 case Stmt::UnaryOperatorClass: {
9002 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9003 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9004 TypeExpr = UO->getSubExpr();
9005 continue;
9006 }
9007 return false;
9008 }
9009
9010 case Stmt::DeclRefExprClass: {
9011 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9012 *VD = DRE->getDecl();
9013 return true;
9014 }
9015
9016 case Stmt::IntegerLiteralClass: {
9017 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9018 llvm::APInt MagicValueAPInt = IL->getValue();
9019 if (MagicValueAPInt.getActiveBits() <= 64) {
9020 *MagicValue = MagicValueAPInt.getZExtValue();
9021 return true;
9022 } else
9023 return false;
9024 }
9025
9026 case Stmt::BinaryConditionalOperatorClass:
9027 case Stmt::ConditionalOperatorClass: {
9028 const AbstractConditionalOperator *ACO =
9029 cast<AbstractConditionalOperator>(TypeExpr);
9030 bool Result;
9031 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9032 if (Result)
9033 TypeExpr = ACO->getTrueExpr();
9034 else
9035 TypeExpr = ACO->getFalseExpr();
9036 continue;
9037 }
9038 return false;
9039 }
9040
9041 case Stmt::BinaryOperatorClass: {
9042 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9043 if (BO->getOpcode() == BO_Comma) {
9044 TypeExpr = BO->getRHS();
9045 continue;
9046 }
9047 return false;
9048 }
9049
9050 default:
9051 return false;
9052 }
9053 }
9054}
9055
9056/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9057///
9058/// \param TypeExpr Expression that specifies a type tag.
9059///
9060/// \param MagicValues Registered magic values.
9061///
9062/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9063/// kind.
9064///
9065/// \param TypeInfo Information about the corresponding C type.
9066///
9067/// \returns true if the corresponding C type was found.
9068bool GetMatchingCType(
9069 const IdentifierInfo *ArgumentKind,
9070 const Expr *TypeExpr, const ASTContext &Ctx,
9071 const llvm::DenseMap<Sema::TypeTagMagicValue,
9072 Sema::TypeTagData> *MagicValues,
9073 bool &FoundWrongKind,
9074 Sema::TypeTagData &TypeInfo) {
9075 FoundWrongKind = false;
9076
9077 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009078 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009079
9080 uint64_t MagicValue;
9081
9082 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9083 return false;
9084
9085 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009086 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009087 if (I->getArgumentKind() != ArgumentKind) {
9088 FoundWrongKind = true;
9089 return false;
9090 }
9091 TypeInfo.Type = I->getMatchingCType();
9092 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9093 TypeInfo.MustBeNull = I->getMustBeNull();
9094 return true;
9095 }
9096 return false;
9097 }
9098
9099 if (!MagicValues)
9100 return false;
9101
9102 llvm::DenseMap<Sema::TypeTagMagicValue,
9103 Sema::TypeTagData>::const_iterator I =
9104 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9105 if (I == MagicValues->end())
9106 return false;
9107
9108 TypeInfo = I->second;
9109 return true;
9110}
9111} // unnamed namespace
9112
9113void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9114 uint64_t MagicValue, QualType Type,
9115 bool LayoutCompatible,
9116 bool MustBeNull) {
9117 if (!TypeTagForDatatypeMagicValues)
9118 TypeTagForDatatypeMagicValues.reset(
9119 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9120
9121 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9122 (*TypeTagForDatatypeMagicValues)[Magic] =
9123 TypeTagData(Type, LayoutCompatible, MustBeNull);
9124}
9125
9126namespace {
9127bool IsSameCharType(QualType T1, QualType T2) {
9128 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9129 if (!BT1)
9130 return false;
9131
9132 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9133 if (!BT2)
9134 return false;
9135
9136 BuiltinType::Kind T1Kind = BT1->getKind();
9137 BuiltinType::Kind T2Kind = BT2->getKind();
9138
9139 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9140 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9141 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9142 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9143}
9144} // unnamed namespace
9145
9146void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9147 const Expr * const *ExprArgs) {
9148 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9149 bool IsPointerAttr = Attr->getIsPointer();
9150
9151 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9152 bool FoundWrongKind;
9153 TypeTagData TypeInfo;
9154 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9155 TypeTagForDatatypeMagicValues.get(),
9156 FoundWrongKind, TypeInfo)) {
9157 if (FoundWrongKind)
9158 Diag(TypeTagExpr->getExprLoc(),
9159 diag::warn_type_tag_for_datatype_wrong_kind)
9160 << TypeTagExpr->getSourceRange();
9161 return;
9162 }
9163
9164 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9165 if (IsPointerAttr) {
9166 // Skip implicit cast of pointer to `void *' (as a function argument).
9167 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009168 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009169 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009170 ArgumentExpr = ICE->getSubExpr();
9171 }
9172 QualType ArgumentType = ArgumentExpr->getType();
9173
9174 // Passing a `void*' pointer shouldn't trigger a warning.
9175 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9176 return;
9177
9178 if (TypeInfo.MustBeNull) {
9179 // Type tag with matching void type requires a null pointer.
9180 if (!ArgumentExpr->isNullPointerConstant(Context,
9181 Expr::NPC_ValueDependentIsNotNull)) {
9182 Diag(ArgumentExpr->getExprLoc(),
9183 diag::warn_type_safety_null_pointer_required)
9184 << ArgumentKind->getName()
9185 << ArgumentExpr->getSourceRange()
9186 << TypeTagExpr->getSourceRange();
9187 }
9188 return;
9189 }
9190
9191 QualType RequiredType = TypeInfo.Type;
9192 if (IsPointerAttr)
9193 RequiredType = Context.getPointerType(RequiredType);
9194
9195 bool mismatch = false;
9196 if (!TypeInfo.LayoutCompatible) {
9197 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9198
9199 // C++11 [basic.fundamental] p1:
9200 // Plain char, signed char, and unsigned char are three distinct types.
9201 //
9202 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9203 // char' depending on the current char signedness mode.
9204 if (mismatch)
9205 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9206 RequiredType->getPointeeType())) ||
9207 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9208 mismatch = false;
9209 } else
9210 if (IsPointerAttr)
9211 mismatch = !isLayoutCompatible(Context,
9212 ArgumentType->getPointeeType(),
9213 RequiredType->getPointeeType());
9214 else
9215 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9216
9217 if (mismatch)
9218 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009219 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009220 << TypeInfo.LayoutCompatible << RequiredType
9221 << ArgumentExpr->getSourceRange()
9222 << TypeTagExpr->getSourceRange();
9223}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009224