blob: f76727cad881981808d6fdd47158b986c947dd03 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000016#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000017#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000018#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000019#include "clang/AST/DeclObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/EvaluatedExprVisitor.h"
David Blaikie7555b6a2012-05-15 16:56:36 +000021#include "clang/AST/Expr.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000022#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000023#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Analysis/Analyses/FormatString.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000027#include "clang/Basic/CharInfo.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000028#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000029#include "clang/Basic/TargetInfo.h"
Alp Tokerb6cc5922014-05-03 03:45:55 +000030#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Sema/Initialization.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000035#include "llvm/ADT/STLExtras.h"
Richard Smithd7293d72013-08-05 18:49:43 +000036#include "llvm/ADT/SmallBitVector.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "llvm/ADT/SmallString.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000038#include "llvm/Support/ConvertUTF.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "llvm/Support/raw_ostream.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000040#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000042using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000043
Chris Lattnera26fb342009-02-18 17:49:48 +000044SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45 unsigned ByteNo) const {
Alp Tokerb6cc5922014-05-03 03:45:55 +000046 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47 Context.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000048}
49
John McCallbebede42011-02-26 05:39:39 +000050/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking. Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53 unsigned argCount = call->getNumArgs();
54 if (argCount == desiredArgCount) return false;
55
56 if (argCount < desiredArgCount)
57 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 /*function call*/ << desiredArgCount << argCount
59 << call->getSourceRange();
60
61 // Highlight all the excess arguments.
62 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63 call->getArg(argCount - 1)->getLocEnd());
64
65 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 /*function call*/ << desiredArgCount << argCount
67 << call->getArg(1)->getSourceRange();
68}
69
Julien Lerouge4a5b4442012-04-28 17:39:16 +000070/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73 if (checkArgCount(S, TheCall, 2))
74 return true;
75
76 // First argument should be an integer.
77 Expr *ValArg = TheCall->getArg(0);
78 QualType Ty = ValArg->getType();
79 if (!Ty->isIntegerType()) {
80 S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
Julien Lerouge5a6b6982011-09-09 22:41:49 +000082 return true;
83 }
Julien Lerouge4a5b4442012-04-28 17:39:16 +000084
85 // Second argument should be a constant string.
86 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88 if (!Literal || !Literal->isAscii()) {
89 S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
91 return true;
92 }
93
94 TheCall->setType(Ty);
Julien Lerouge5a6b6982011-09-09 22:41:49 +000095 return false;
96}
97
Richard Smith6cbd65d2013-07-11 02:27:57 +000098/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101 if (checkArgCount(S, TheCall, 1))
102 return true;
103
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000104 ExprResult Arg(TheCall->getArg(0));
Richard Smith6cbd65d2013-07-11 02:27:57 +0000105 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106 if (ResultType.isNull())
107 return true;
108
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000109 TheCall->setArg(0, Arg.get());
Richard Smith6cbd65d2013-07-11 02:27:57 +0000110 TheCall->setType(ResultType);
111 return false;
112}
113
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000114static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 CallExpr *TheCall, unsigned SizeIdx,
116 unsigned DstSizeIdx) {
117 if (TheCall->getNumArgs() <= SizeIdx ||
118 TheCall->getNumArgs() <= DstSizeIdx)
119 return;
120
121 const Expr *SizeArg = TheCall->getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123
124 llvm::APSInt Size, DstSize;
125
126 // find out if both sizes are known at compile time
127 if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128 !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129 return;
130
131 if (Size.ule(DstSize))
132 return;
133
134 // confirmed overflow so generate the diagnostic.
135 IdentifierInfo *FnName = FDecl->getIdentifier();
136 SourceLocation SL = TheCall->getLocStart();
137 SourceRange SR = TheCall->getSourceRange();
138
139 S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140}
141
Peter Collingbournef7706832014-12-12 23:41:25 +0000142static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143 if (checkArgCount(S, BuiltinCall, 2))
144 return true;
145
146 SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148 Expr *Call = BuiltinCall->getArg(0);
149 Expr *Chain = BuiltinCall->getArg(1);
150
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
154 return true;
155 }
156
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
161 return true;
162 }
163
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
169 return true;
170 }
171
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
175 return true;
176 }
177
178 ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179 if (ChainResult.isInvalid())
180 return true;
181 if (!ChainResult.get()->getType()->isPointerType()) {
182 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
184 return true;
185 }
186
David Majnemerced8bdf2015-02-25 17:36:15 +0000187 QualType ReturnTy = CE->getCallReturnType(S.Context);
Peter Collingbournef7706832014-12-12 23:41:25 +0000188 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189 QualType BuiltinTy = S.Context.getFunctionType(
190 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192
193 Builtin =
194 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195
196 BuiltinCall->setType(CE->getType());
197 BuiltinCall->setValueKind(CE->getValueKind());
198 BuiltinCall->setObjectKind(CE->getObjectKind());
199 BuiltinCall->setCallee(Builtin);
200 BuiltinCall->setArg(1, ChainResult.get());
201
202 return false;
203}
204
Reid Kleckner1d59f992015-01-22 01:36:17 +0000205static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206 Scope::ScopeFlags NeededScopeFlags,
207 unsigned DiagID) {
208 // Scopes aren't available during instantiation. Fortunately, builtin
209 // functions cannot be template args so they cannot be formed through template
210 // instantiation. Therefore checking once during the parse is sufficient.
211 if (!SemaRef.ActiveTemplateInstantiations.empty())
212 return false;
213
214 Scope *S = SemaRef.getCurScope();
215 while (S && !S->isSEHExceptScope())
216 S = S->getParent();
217 if (!S || !(S->getFlags() & NeededScopeFlags)) {
218 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219 SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220 << DRE->getDecl()->getIdentifier();
221 return true;
222 }
223
224 return false;
225}
226
John McCalldadc5752010-08-24 06:29:42 +0000227ExprResult
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000228Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229 CallExpr *TheCall) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000230 ExprResult TheCallResult(TheCall);
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000231
Chris Lattner3be167f2010-10-01 23:23:24 +0000232 // Find out if any arguments are required to be integer constant expressions.
233 unsigned ICEArguments = 0;
234 ASTContext::GetBuiltinTypeError Error;
235 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236 if (Error != ASTContext::GE_None)
237 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
238
239 // If any arguments are required to be ICE's, check and diagnose.
240 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241 // Skip arguments not required to be ICE's.
242 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243
244 llvm::APSInt Result;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247 ICEArguments &= ~(1 << ArgNo);
248 }
249
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000250 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000251 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000252 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000253 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000254 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000255 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000256 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000257 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000258 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000259 if (SemaBuiltinVAStart(TheCall))
260 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000261 break;
Saleem Abdulrasool202aac12014-07-22 02:01:04 +0000262 case Builtin::BI__va_start: {
263 switch (Context.getTargetInfo().getTriple().getArch()) {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
267 return ExprError();
268 break;
269 default:
270 if (SemaBuiltinVAStart(TheCall))
271 return ExprError();
272 break;
273 }
274 break;
275 }
Chris Lattner2da14fb2007-12-20 00:26:33 +0000276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000282 if (SemaBuiltinUnorderedCompare(TheCall))
283 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000284 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
287 return ExprError();
288 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000294 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000295 return ExprError();
296 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000297 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000298 return SemaBuiltinShuffleVector(TheCall);
299 // TheCall will be freed by the smart pointer here, but that's fine, since
300 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000301 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000302 if (SemaBuiltinPrefetch(TheCall))
303 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000304 break;
Hal Finkelf0417332014-07-17 14:25:55 +0000305 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +0000306 case Builtin::BI__builtin_assume:
Hal Finkelf0417332014-07-17 14:25:55 +0000307 if (SemaBuiltinAssume(TheCall))
308 return ExprError();
309 break;
Hal Finkelbcc06082014-09-07 22:58:14 +0000310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
312 return ExprError();
313 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000314 case Builtin::BI__builtin_object_size:
Richard Sandiford28940af2014-04-16 08:47:51 +0000315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000316 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000317 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
320 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000321 break;
Joerg Sonnenberger27173282015-03-11 23:46:32 +0000322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
324 return ExprError();
325 break;
David Majnemerc403a1c2015-03-20 17:03:35 +0000326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
328 if (checkArgCount(*this, TheCall, 1))
329 return true;
330 break;
John McCallbebede42011-02-26 05:39:39 +0000331
332 case Builtin::BI__builtin_classify_type:
333 if (checkArgCount(*this, TheCall, 1)) return true;
334 TheCall->setType(Context.IntTy);
335 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000336 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000337 if (checkArgCount(*this, TheCall, 1)) return true;
338 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000339 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000340 case Builtin::BI__sync_fetch_and_add:
Douglas Gregor73722482011-11-28 16:30:08 +0000341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000346 case Builtin::BI__sync_fetch_and_sub:
Douglas Gregor73722482011-11-28 16:30:08 +0000347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000352 case Builtin::BI__sync_fetch_and_or:
Douglas Gregor73722482011-11-28 16:30:08 +0000353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000358 case Builtin::BI__sync_fetch_and_and:
Douglas Gregor73722482011-11-28 16:30:08 +0000359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000364 case Builtin::BI__sync_fetch_and_xor:
Douglas Gregor73722482011-11-28 16:30:08 +0000365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000376 case Builtin::BI__sync_add_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000382 case Builtin::BI__sync_sub_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000388 case Builtin::BI__sync_and_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000394 case Builtin::BI__sync_or_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000400 case Builtin::BI__sync_xor_and_fetch:
Douglas Gregor73722482011-11-28 16:30:08 +0000401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +0000406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000412 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000418 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000424 case Builtin::BI__sync_lock_test_and_set:
Douglas Gregor73722482011-11-28 16:30:08 +0000425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
Chris Lattnerdc046542009-05-08 06:58:22 +0000430 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +0000431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000436 case Builtin::BI__sync_swap:
Douglas Gregor73722482011-11-28 16:30:08 +0000437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000442 return SemaBuiltinAtomicOverloaded(TheCallResult);
Richard Smithfeea8832012-04-12 05:08:17 +0000443#define BUILTIN(ID, TYPE, ATTRS)
444#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
Richard Smithfeea8832012-04-12 05:08:17 +0000447#include "clang/Basic/Builtins.def"
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000448 case Builtin::BI__builtin_annotation:
Julien Lerouge4a5b4442012-04-28 17:39:16 +0000449 if (SemaBuiltinAnnotation(*this, TheCall))
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000450 return ExprError();
451 break;
Richard Smith6cbd65d2013-07-11 02:27:57 +0000452 case Builtin::BI__builtin_addressof:
453 if (SemaBuiltinAddressof(*this, TheCall))
454 return ExprError();
455 break;
Richard Smith760520b2014-06-03 23:27:44 +0000456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
458 if (!getLangOpts().CPlusPlus) {
459 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ? "__builtin_operator_new"
462 : "__builtin_operator_delete")
463 << "C++";
464 return ExprError();
465 }
466 // CodeGen assumes it can find the global new and delete to call,
467 // so ensure that they are declared.
468 DeclareGlobalNewDelete();
469 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000470
471 // check secure string manipulation functions where overflows
472 // are detectable at compile time
473 case Builtin::BI__builtin___memcpy_chk:
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
481 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
482 break;
Steven Wu566c14e2014-09-24 04:37:33 +0000483 case Builtin::BI__builtin___memccpy_chk:
484 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
485 break;
Fariborz Jahanian3e6a0be2014-09-18 17:58:27 +0000486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
488 SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
489 break;
Peter Collingbournef7706832014-12-12 23:41:25 +0000490
491 case Builtin::BI__builtin_call_with_static_chain:
492 if (SemaBuiltinCallWithStaticChain(*this, TheCall))
493 return ExprError();
494 break;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000495
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
498 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
499 diag::err_seh___except_block))
500 return ExprError();
501 break;
502 }
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
505 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
506 diag::err_seh___except_filter))
507 return ExprError();
508 break;
509 }
510
David Majnemerba3e5ec2015-03-13 18:26:17 +0000511 case Builtin::BI__GetExceptionInfo:
512 if (checkArgCount(*this, TheCall, 1))
513 return ExprError();
514
515 if (CheckCXXThrowOperand(
516 TheCall->getLocStart(),
517 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
518 TheCall))
519 return ExprError();
520
521 TheCall->setType(Context.VoidPtrTy);
522 break;
523
Nate Begeman4904e322010-06-08 02:47:44 +0000524 }
Richard Smith760520b2014-06-03 23:27:44 +0000525
Nate Begeman4904e322010-06-08 02:47:44 +0000526 // Since the target specific builtins for each arch overlap, only check those
527 // of the arch we are compiling for.
528 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000529 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000530 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000531 case llvm::Triple::armeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000532 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +0000533 case llvm::Triple::thumbeb:
Nate Begeman4904e322010-06-08 02:47:44 +0000534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
535 return ExprError();
536 break;
Tim Northover25e8a672014-05-24 12:51:25 +0000537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
Tim Northover573cbee2014-05-24 12:52:07 +0000539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
Tim Northovera2ee4332014-03-29 15:09:45 +0000540 return ExprError();
541 break;
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
547 return ExprError();
548 break;
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
551 return ExprError();
552 break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +0000553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
556 return ExprError();
557 break;
Kit Bartone50adcb2015-03-30 19:40:59 +0000558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
562 return ExprError();
563 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000564 default:
565 break;
566 }
567 }
568
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000569 return TheCallResult;
Nate Begeman4904e322010-06-08 02:47:44 +0000570}
571
Nate Begeman91e1fea2010-06-14 05:21:25 +0000572// Get the valid immediate range for the specified NEON type code.
Tim Northover3402dc72014-02-12 12:04:59 +0000573static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000574 NeonTypeFlags Type(t);
Tim Northover3402dc72014-02-12 12:04:59 +0000575 int IsQuad = ForceQuad ? true : Type.isQuad();
Bob Wilson98bc98c2011-11-08 01:16:11 +0000576 switch (Type.getEltType()) {
577 case NeonTypeFlags::Int8:
578 case NeonTypeFlags::Poly8:
579 return shift ? 7 : (8 << IsQuad) - 1;
580 case NeonTypeFlags::Int16:
581 case NeonTypeFlags::Poly16:
582 return shift ? 15 : (4 << IsQuad) - 1;
583 case NeonTypeFlags::Int32:
584 return shift ? 31 : (2 << IsQuad) - 1;
585 case NeonTypeFlags::Int64:
Kevin Qincaac85e2013-11-14 03:29:16 +0000586 case NeonTypeFlags::Poly64:
Bob Wilson98bc98c2011-11-08 01:16:11 +0000587 return shift ? 63 : (1 << IsQuad) - 1;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000588 case NeonTypeFlags::Poly128:
589 return shift ? 127 : (1 << IsQuad) - 1;
Bob Wilson98bc98c2011-11-08 01:16:11 +0000590 case NeonTypeFlags::Float16:
591 assert(!shift && "cannot shift float types!");
592 return (4 << IsQuad) - 1;
593 case NeonTypeFlags::Float32:
594 assert(!shift && "cannot shift float types!");
595 return (2 << IsQuad) - 1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000596 case NeonTypeFlags::Float64:
597 assert(!shift && "cannot shift float types!");
598 return (1 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000599 }
David Blaikie8a40f702012-01-17 06:56:22 +0000600 llvm_unreachable("Invalid NeonTypeFlag!");
Nate Begeman91e1fea2010-06-14 05:21:25 +0000601}
602
Bob Wilsone4d77232011-11-08 05:04:11 +0000603/// getNeonEltType - Return the QualType corresponding to the elements of
604/// the vector type specified by the NeonTypeFlags. This is used to check
605/// the pointer arguments for Neon load/store intrinsics.
Kevin Qincaac85e2013-11-14 03:29:16 +0000606static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
Tim Northovera2ee4332014-03-29 15:09:45 +0000607 bool IsPolyUnsigned, bool IsInt64Long) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000608 switch (Flags.getEltType()) {
609 case NeonTypeFlags::Int8:
610 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
611 case NeonTypeFlags::Int16:
612 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
613 case NeonTypeFlags::Int32:
614 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
615 case NeonTypeFlags::Int64:
Tim Northovera2ee4332014-03-29 15:09:45 +0000616 if (IsInt64Long)
Kevin Qinad64f6d2014-02-24 02:45:03 +0000617 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
618 else
619 return Flags.isUnsigned() ? Context.UnsignedLongLongTy
620 : Context.LongLongTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000621 case NeonTypeFlags::Poly8:
Tim Northovera2ee4332014-03-29 15:09:45 +0000622 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000623 case NeonTypeFlags::Poly16:
Tim Northovera2ee4332014-03-29 15:09:45 +0000624 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
Kevin Qincaac85e2013-11-14 03:29:16 +0000625 case NeonTypeFlags::Poly64:
Kevin Qin78b86532015-05-14 08:18:05 +0000626 if (IsInt64Long)
627 return Context.UnsignedLongTy;
628 else
629 return Context.UnsignedLongLongTy;
Kevin Qinfb79d7f2013-12-10 06:49:01 +0000630 case NeonTypeFlags::Poly128:
631 break;
Bob Wilsone4d77232011-11-08 05:04:11 +0000632 case NeonTypeFlags::Float16:
Kevin Qincaac85e2013-11-14 03:29:16 +0000633 return Context.HalfTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000634 case NeonTypeFlags::Float32:
635 return Context.FloatTy;
Tim Northover2fe823a2013-08-01 09:23:19 +0000636 case NeonTypeFlags::Float64:
637 return Context.DoubleTy;
Bob Wilsone4d77232011-11-08 05:04:11 +0000638 }
David Blaikie8a40f702012-01-17 06:56:22 +0000639 llvm_unreachable("Invalid NeonTypeFlag!");
Bob Wilsone4d77232011-11-08 05:04:11 +0000640}
641
Tim Northover12670412014-02-19 10:37:05 +0000642bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Tim Northover2fe823a2013-08-01 09:23:19 +0000643 llvm::APSInt Result;
Tim Northover2fe823a2013-08-01 09:23:19 +0000644 uint64_t mask = 0;
645 unsigned TV = 0;
646 int PtrArgNum = -1;
647 bool HasConstPtr = false;
648 switch (BuiltinID) {
Tim Northover12670412014-02-19 10:37:05 +0000649#define GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000650#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000651#undef GET_NEON_OVERLOAD_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000652 }
653
654 // For NEON intrinsics which are overloaded on vector element type, validate
655 // the immediate which specifies which variant to emit.
Tim Northover12670412014-02-19 10:37:05 +0000656 unsigned ImmArg = TheCall->getNumArgs()-1;
Tim Northover2fe823a2013-08-01 09:23:19 +0000657 if (mask) {
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
659 return true;
660
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
663 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Tim Northover12670412014-02-19 10:37:05 +0000664 << TheCall->getArg(ImmArg)->getSourceRange();
Tim Northover2fe823a2013-08-01 09:23:19 +0000665 }
666
667 if (PtrArgNum >= 0) {
668 // Check that pointer arguments have the specified type.
669 Expr *Arg = TheCall->getArg(PtrArgNum);
670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
673 QualType RHSTy = RHS.get()->getType();
Tim Northover12670412014-02-19 10:37:05 +0000674
Tim Northovera2ee4332014-03-29 15:09:45 +0000675 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
Tim Northover40956e62014-07-23 12:32:58 +0000676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
Tim Northovera2ee4332014-03-29 15:09:45 +0000677 bool IsInt64Long =
678 Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
679 QualType EltTy =
680 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
Tim Northover2fe823a2013-08-01 09:23:19 +0000681 if (HasConstPtr)
682 EltTy = EltTy.withConst();
683 QualType LHSTy = Context.getPointerType(EltTy);
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
686 if (RHS.isInvalid())
687 return true;
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.get(), AA_Assigning))
690 return true;
691 }
692
693 // For NEON intrinsics which take an immediate value as part of the
694 // instruction, range check them here.
695 unsigned i = 0, l = 0, u = 0;
696 switch (BuiltinID) {
697 default:
698 return false;
Tim Northover12670412014-02-19 10:37:05 +0000699#define GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000700#include "clang/Basic/arm_neon.inc"
Tim Northover12670412014-02-19 10:37:05 +0000701#undef GET_NEON_IMMEDIATE_CHECK
Tim Northover2fe823a2013-08-01 09:23:19 +0000702 }
Tim Northover2fe823a2013-08-01 09:23:19 +0000703
Richard Sandiford28940af2014-04-16 08:47:51 +0000704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northover2fe823a2013-08-01 09:23:19 +0000705}
706
Tim Northovera2ee4332014-03-29 15:09:45 +0000707bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
708 unsigned MaxWidth) {
Tim Northover6aacd492013-07-16 09:47:53 +0000709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
Tim Northovera2ee4332014-03-29 15:09:45 +0000711 BuiltinID == ARM::BI__builtin_arm_strex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000712 BuiltinID == ARM::BI__builtin_arm_stlex ||
Tim Northover573cbee2014-05-24 12:52:07 +0000713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
Tim Northover6aacd492013-07-16 09:47:53 +0000717 "unexpected ARM builtin");
Tim Northovera2ee4332014-03-29 15:09:45 +0000718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
Tim Northover6aacd492013-07-16 09:47:53 +0000722
723 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
724
725 // Ensure that we have the proper number of arguments.
726 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
727 return true;
728
729 // Inspect the pointer argument of the atomic builtin. This should always be
730 // a pointer type, whose element is an integral scalar or pointer type.
731 // Because it is a pointer type, we don't have to worry about any implicit
732 // casts here.
733 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
735 if (PointerArgRes.isInvalid())
736 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000737 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000738
739 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
740 if (!pointerType) {
741 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
742 << PointerArg->getType() << PointerArg->getSourceRange();
743 return true;
744 }
745
746 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
747 // task is to insert the appropriate casts into the AST. First work out just
748 // what the appropriate type is.
749 QualType ValType = pointerType->getPointeeType();
750 QualType AddrType = ValType.getUnqualifiedType().withVolatile();
751 if (IsLdrex)
752 AddrType.addConst();
753
754 // Issue a warning if the cast is dodgy.
755 CastKind CastNeeded = CK_NoOp;
756 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
757 CastNeeded = CK_BitCast;
758 Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
759 << PointerArg->getType()
760 << Context.getPointerType(AddrType)
761 << AA_Passing << PointerArg->getSourceRange();
762 }
763
764 // Finally, do the cast and replace the argument with the corrected version.
765 AddrType = Context.getPointerType(AddrType);
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
767 if (PointerArgRes.isInvalid())
768 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000769 PointerArg = PointerArgRes.get();
Tim Northover6aacd492013-07-16 09:47:53 +0000770
771 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
772
773 // In general, we allow ints, floats and pointers to be loaded and stored.
774 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
775 !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
776 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->getType() << PointerArg->getSourceRange();
778 return true;
779 }
780
781 // But ARM doesn't have instructions to deal with 128-bit versions.
Tim Northovera2ee4332014-03-29 15:09:45 +0000782 if (Context.getTypeSize(ValType) > MaxWidth) {
783 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
Tim Northover6aacd492013-07-16 09:47:53 +0000784 Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->getType() << PointerArg->getSourceRange();
786 return true;
787 }
788
789 switch (ValType.getObjCLifetime()) {
790 case Qualifiers::OCL_None:
791 case Qualifiers::OCL_ExplicitNone:
792 // okay
793 break;
794
795 case Qualifiers::OCL_Weak:
796 case Qualifiers::OCL_Strong:
797 case Qualifiers::OCL_Autoreleasing:
798 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
799 << ValType << PointerArg->getSourceRange();
800 return true;
801 }
802
803
804 if (IsLdrex) {
805 TheCall->setType(ValType);
806 return false;
807 }
808
809 // Initialize the argument to be stored.
810 ExprResult ValArg = TheCall->getArg(0);
811 InitializedEntity Entity = InitializedEntity::InitializeParameter(
812 Context, ValType, /*consume*/ false);
813 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
814 if (ValArg.isInvalid())
815 return true;
Tim Northover6aacd492013-07-16 09:47:53 +0000816 TheCall->setArg(0, ValArg.get());
Tim Northover58d2bb12013-10-29 12:32:58 +0000817
818 // __builtin_arm_strex always returns an int. It's marked as such in the .def,
819 // but the custom checker bypasses all default analysis.
820 TheCall->setType(Context.IntTy);
Tim Northover6aacd492013-07-16 09:47:53 +0000821 return false;
822}
823
Nate Begeman4904e322010-06-08 02:47:44 +0000824bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000825 llvm::APSInt Result;
826
Tim Northover6aacd492013-07-16 09:47:53 +0000827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
Tim Northover6aacd492013-07-16 09:47:53 +0000832 }
833
Yi Kong26d104a2014-08-13 19:18:14 +0000834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
837 }
838
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000839 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
840 BuiltinID == ARM::BI__builtin_arm_wsr64)
841 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
842
843 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
844 BuiltinID == ARM::BI__builtin_arm_rsrp ||
845 BuiltinID == ARM::BI__builtin_arm_wsr ||
846 BuiltinID == ARM::BI__builtin_arm_wsrp)
847 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
848
Tim Northover12670412014-02-19 10:37:05 +0000849 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
850 return true;
Nico Weber0e6daef2013-12-26 23:38:39 +0000851
Yi Kong4efadfb2014-07-03 16:01:25 +0000852 // For intrinsics which take an immediate value as part of the instruction,
853 // range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000854 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000855 switch (BuiltinID) {
856 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000857 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
858 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000859 case ARM::BI__builtin_arm_vcvtr_f:
860 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Weiming Zhao87bb4922013-11-12 21:42:50 +0000861 case ARM::BI__builtin_arm_dmb:
Yi Kong4efadfb2014-07-03 16:01:25 +0000862 case ARM::BI__builtin_arm_dsb:
Yi Kong1d268af2014-08-26 12:48:06 +0000863 case ARM::BI__builtin_arm_isb:
864 case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000865 }
Nate Begemand773fe62010-06-13 04:47:52 +0000866
Nate Begemanf568b072010-08-03 21:32:34 +0000867 // FIXME: VFP Intrinsics should error if VFP not present.
Richard Sandiford28940af2014-04-16 08:47:51 +0000868 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000869}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000870
Tim Northover573cbee2014-05-24 12:52:07 +0000871bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
Tim Northovera2ee4332014-03-29 15:09:45 +0000872 CallExpr *TheCall) {
873 llvm::APSInt Result;
874
Tim Northover573cbee2014-05-24 12:52:07 +0000875 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
Tim Northover3acd6bd2014-07-02 12:56:02 +0000876 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
877 BuiltinID == AArch64::BI__builtin_arm_strex ||
878 BuiltinID == AArch64::BI__builtin_arm_stlex) {
Tim Northovera2ee4332014-03-29 15:09:45 +0000879 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
880 }
881
Yi Konga5548432014-08-13 19:18:20 +0000882 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
883 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
884 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
885 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
886 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
887 }
888
Luke Cheeseman59b2d832015-06-15 17:51:01 +0000889 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
890 BuiltinID == AArch64::BI__builtin_arm_wsr64)
891 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, false);
892
893 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
894 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
895 BuiltinID == AArch64::BI__builtin_arm_wsr ||
896 BuiltinID == AArch64::BI__builtin_arm_wsrp)
897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
898
Tim Northovera2ee4332014-03-29 15:09:45 +0000899 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
900 return true;
901
Yi Kong19a29ac2014-07-17 10:52:06 +0000902 // For intrinsics which take an immediate value as part of the instruction,
903 // range check them here.
904 unsigned i = 0, l = 0, u = 0;
905 switch (BuiltinID) {
906 default: return false;
907 case AArch64::BI__builtin_arm_dmb:
908 case AArch64::BI__builtin_arm_dsb:
909 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
910 }
911
Yi Kong19a29ac2014-07-17 10:52:06 +0000912 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
Tim Northovera2ee4332014-03-29 15:09:45 +0000913}
914
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000915bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
916 unsigned i = 0, l = 0, u = 0;
917 switch (BuiltinID) {
918 default: return false;
919 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
920 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
Simon Atanasyan8f06f2f2012-08-27 12:29:20 +0000921 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
922 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
923 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
924 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
925 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
Richard Sandiford28940af2014-04-16 08:47:51 +0000926 }
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000927
Richard Sandiford28940af2014-04-16 08:47:51 +0000928 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Simon Atanasyanecedf3d2012-07-08 09:30:00 +0000929}
930
Kit Bartone50adcb2015-03-30 19:40:59 +0000931bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
932 unsigned i = 0, l = 0, u = 0;
Nemanja Ivanovic239eec72015-04-09 23:58:16 +0000933 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
934 BuiltinID == PPC::BI__builtin_divdeu ||
935 BuiltinID == PPC::BI__builtin_bpermd;
936 bool IsTarget64Bit = Context.getTargetInfo()
937 .getTypeWidth(Context
938 .getTargetInfo()
939 .getIntPtrType()) == 64;
940 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
941 BuiltinID == PPC::BI__builtin_divweu ||
942 BuiltinID == PPC::BI__builtin_divde ||
943 BuiltinID == PPC::BI__builtin_divdeu;
944
945 if (Is64BitBltin && !IsTarget64Bit)
946 return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
947 << TheCall->getSourceRange();
948
949 if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
950 (BuiltinID == PPC::BI__builtin_bpermd &&
951 !Context.getTargetInfo().hasFeature("bpermd")))
952 return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
953 << TheCall->getSourceRange();
954
Kit Bartone50adcb2015-03-30 19:40:59 +0000955 switch (BuiltinID) {
956 default: return false;
957 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
958 case PPC::BI__builtin_altivec_crypto_vshasigmad:
959 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
960 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
961 case PPC::BI__builtin_tbegin:
962 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
963 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
964 case PPC::BI__builtin_tabortwc:
965 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
966 case PPC::BI__builtin_tabortwci:
967 case PPC::BI__builtin_tabortdci:
968 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
969 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
970 }
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
972}
973
Ulrich Weigand3a610eb2015-04-01 12:54:25 +0000974bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
975 CallExpr *TheCall) {
976 if (BuiltinID == SystemZ::BI__builtin_tabort) {
977 Expr *Arg = TheCall->getArg(0);
978 llvm::APSInt AbortCode(32);
979 if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
980 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
981 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
982 << Arg->getSourceRange();
983 }
984
Ulrich Weigand5722c0f2015-05-05 19:36:42 +0000985 // For intrinsics which take an immediate value as part of the instruction,
986 // range check them here.
987 unsigned i = 0, l = 0, u = 0;
988 switch (BuiltinID) {
989 default: return false;
990 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
991 case SystemZ::BI__builtin_s390_verimb:
992 case SystemZ::BI__builtin_s390_verimh:
993 case SystemZ::BI__builtin_s390_verimf:
994 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
995 case SystemZ::BI__builtin_s390_vfaeb:
996 case SystemZ::BI__builtin_s390_vfaeh:
997 case SystemZ::BI__builtin_s390_vfaef:
998 case SystemZ::BI__builtin_s390_vfaebs:
999 case SystemZ::BI__builtin_s390_vfaehs:
1000 case SystemZ::BI__builtin_s390_vfaefs:
1001 case SystemZ::BI__builtin_s390_vfaezb:
1002 case SystemZ::BI__builtin_s390_vfaezh:
1003 case SystemZ::BI__builtin_s390_vfaezf:
1004 case SystemZ::BI__builtin_s390_vfaezbs:
1005 case SystemZ::BI__builtin_s390_vfaezhs:
1006 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1007 case SystemZ::BI__builtin_s390_vfidb:
1008 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1009 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1010 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1011 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1012 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1013 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1014 case SystemZ::BI__builtin_s390_vstrcb:
1015 case SystemZ::BI__builtin_s390_vstrch:
1016 case SystemZ::BI__builtin_s390_vstrcf:
1017 case SystemZ::BI__builtin_s390_vstrczb:
1018 case SystemZ::BI__builtin_s390_vstrczh:
1019 case SystemZ::BI__builtin_s390_vstrczf:
1020 case SystemZ::BI__builtin_s390_vstrcbs:
1021 case SystemZ::BI__builtin_s390_vstrchs:
1022 case SystemZ::BI__builtin_s390_vstrcfs:
1023 case SystemZ::BI__builtin_s390_vstrczbs:
1024 case SystemZ::BI__builtin_s390_vstrczhs:
1025 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1026 }
1027 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Ulrich Weigand3a610eb2015-04-01 12:54:25 +00001028}
1029
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001030bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001031 unsigned i = 0, l = 0, u = 0;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001032 switch (BuiltinID) {
Craig Topperdd84ec52014-12-27 07:00:08 +00001033 default: return false;
1034 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
Craig Topper16015252015-01-31 06:31:23 +00001035 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
Craig Topper1a8b0472015-01-31 08:57:52 +00001036 case X86::BI__builtin_ia32_vpermil2pd:
1037 case X86::BI__builtin_ia32_vpermil2pd256:
1038 case X86::BI__builtin_ia32_vpermil2ps:
1039 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
Craig Topper95b0d732015-01-25 23:30:05 +00001040 case X86::BI__builtin_ia32_cmpb128_mask:
1041 case X86::BI__builtin_ia32_cmpw128_mask:
1042 case X86::BI__builtin_ia32_cmpd128_mask:
1043 case X86::BI__builtin_ia32_cmpq128_mask:
1044 case X86::BI__builtin_ia32_cmpb256_mask:
1045 case X86::BI__builtin_ia32_cmpw256_mask:
1046 case X86::BI__builtin_ia32_cmpd256_mask:
1047 case X86::BI__builtin_ia32_cmpq256_mask:
1048 case X86::BI__builtin_ia32_cmpb512_mask:
1049 case X86::BI__builtin_ia32_cmpw512_mask:
1050 case X86::BI__builtin_ia32_cmpd512_mask:
1051 case X86::BI__builtin_ia32_cmpq512_mask:
1052 case X86::BI__builtin_ia32_ucmpb128_mask:
1053 case X86::BI__builtin_ia32_ucmpw128_mask:
1054 case X86::BI__builtin_ia32_ucmpd128_mask:
1055 case X86::BI__builtin_ia32_ucmpq128_mask:
1056 case X86::BI__builtin_ia32_ucmpb256_mask:
1057 case X86::BI__builtin_ia32_ucmpw256_mask:
1058 case X86::BI__builtin_ia32_ucmpd256_mask:
1059 case X86::BI__builtin_ia32_ucmpq256_mask:
1060 case X86::BI__builtin_ia32_ucmpb512_mask:
1061 case X86::BI__builtin_ia32_ucmpw512_mask:
1062 case X86::BI__builtin_ia32_ucmpd512_mask:
1063 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
Craig Topper16015252015-01-31 06:31:23 +00001064 case X86::BI__builtin_ia32_roundps:
1065 case X86::BI__builtin_ia32_roundpd:
1066 case X86::BI__builtin_ia32_roundps256:
1067 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
1068 case X86::BI__builtin_ia32_roundss:
1069 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
1070 case X86::BI__builtin_ia32_cmpps:
1071 case X86::BI__builtin_ia32_cmpss:
1072 case X86::BI__builtin_ia32_cmppd:
1073 case X86::BI__builtin_ia32_cmpsd:
1074 case X86::BI__builtin_ia32_cmpps256:
1075 case X86::BI__builtin_ia32_cmppd256:
1076 case X86::BI__builtin_ia32_cmpps512_mask:
1077 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
Craig Topper8dd7d0d2015-02-13 06:04:48 +00001078 case X86::BI__builtin_ia32_vpcomub:
1079 case X86::BI__builtin_ia32_vpcomuw:
1080 case X86::BI__builtin_ia32_vpcomud:
1081 case X86::BI__builtin_ia32_vpcomuq:
1082 case X86::BI__builtin_ia32_vpcomb:
1083 case X86::BI__builtin_ia32_vpcomw:
1084 case X86::BI__builtin_ia32_vpcomd:
1085 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001086 }
Craig Topperdd84ec52014-12-27 07:00:08 +00001087 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
Warren Hunt20e4a5d2014-02-21 23:08:53 +00001088}
1089
Richard Smith55ce3522012-06-25 20:30:08 +00001090/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1091/// parameter with the FormatAttr's correct format_idx and firstDataArg.
1092/// Returns true when the format fits the function and the FormatStringInfo has
1093/// been populated.
1094bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1095 FormatStringInfo *FSI) {
1096 FSI->HasVAListArg = Format->getFirstArg() == 0;
1097 FSI->FormatIdx = Format->getFormatIdx() - 1;
1098 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001099
Richard Smith55ce3522012-06-25 20:30:08 +00001100 // The way the format attribute works in GCC, the implicit this argument
1101 // of member functions is counted. However, it doesn't appear in our own
1102 // lists, so decrement format_idx in that case.
1103 if (IsCXXMember) {
1104 if(FSI->FormatIdx == 0)
1105 return false;
1106 --FSI->FormatIdx;
1107 if (FSI->FirstDataArg != 0)
1108 --FSI->FirstDataArg;
1109 }
1110 return true;
1111}
Mike Stump11289f42009-09-09 15:08:12 +00001112
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001113/// Checks if a the given expression evaluates to null.
1114///
1115/// \brief Returns true if the value evaluates to null.
1116static bool CheckNonNullExpr(Sema &S,
1117 const Expr *Expr) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001118 // If the expression has non-null type, it doesn't evaluate to null.
1119 if (auto nullability
1120 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1121 if (*nullability == NullabilityKind::NonNull)
1122 return false;
1123 }
1124
Ted Kremeneka146db32014-01-17 06:24:47 +00001125 // As a special case, transparent unions initialized with zero are
1126 // considered null for the purposes of the nonnull attribute.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001127 if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
Ted Kremeneka146db32014-01-17 06:24:47 +00001128 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1129 if (const CompoundLiteralExpr *CLE =
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001130 dyn_cast<CompoundLiteralExpr>(Expr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001131 if (const InitListExpr *ILE =
1132 dyn_cast<InitListExpr>(CLE->getInitializer()))
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001133 Expr = ILE->getInit(0);
Ted Kremeneka146db32014-01-17 06:24:47 +00001134 }
1135
1136 bool Result;
Artyom Skrobov9f213442014-01-24 11:10:39 +00001137 return (!Expr->isValueDependent() &&
1138 Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1139 !Result);
Ted Kremenekef9e7f82014-01-22 06:10:28 +00001140}
1141
1142static void CheckNonNullArgument(Sema &S,
1143 const Expr *ArgExpr,
1144 SourceLocation CallSiteLoc) {
1145 if (CheckNonNullExpr(S, ArgExpr))
Ted Kremeneka146db32014-01-17 06:24:47 +00001146 S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1147}
1148
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001149bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1150 FormatStringInfo FSI;
1151 if ((GetFormatStringType(Format) == FST_NSString) &&
1152 getFormatStringInfo(Format, false, &FSI)) {
1153 Idx = FSI.FormatIdx;
1154 return true;
1155 }
1156 return false;
1157}
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001158/// \brief Diagnose use of %s directive in an NSString which is being passed
1159/// as formatting string to formatting method.
1160static void
1161DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1162 const NamedDecl *FDecl,
1163 Expr **Args,
1164 unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001165 unsigned Idx = 0;
1166 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001167 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1168 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001169 Idx = 2;
1170 Format = true;
1171 }
1172 else
1173 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1174 if (S.GetFormatNSStringIdx(I, Idx)) {
1175 Format = true;
1176 break;
1177 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001178 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001179 if (!Format || NumArgs <= Idx)
1180 return;
1181 const Expr *FormatExpr = Args[Idx];
1182 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1183 FormatExpr = CSCE->getSubExpr();
1184 const StringLiteral *FormatString;
1185 if (const ObjCStringLiteral *OSL =
1186 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1187 FormatString = OSL->getString();
1188 else
1189 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1190 if (!FormatString)
1191 return;
1192 if (S.FormatStringHasSArg(FormatString)) {
1193 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1194 << "%s" << 1 << 1;
1195 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1196 << FDecl->getDeclName();
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00001197 }
1198}
1199
Douglas Gregorb4866e82015-06-19 18:13:19 +00001200/// Determine whether the given type has a non-null nullability annotation.
1201static bool isNonNullType(ASTContext &ctx, QualType type) {
1202 if (auto nullability = type->getNullability(ctx))
1203 return *nullability == NullabilityKind::NonNull;
1204
1205 return false;
1206}
1207
Ted Kremenek2bc73332014-01-17 06:24:43 +00001208static void CheckNonNullArguments(Sema &S,
Ted Kremeneka146db32014-01-17 06:24:47 +00001209 const NamedDecl *FDecl,
Douglas Gregorb4866e82015-06-19 18:13:19 +00001210 const FunctionProtoType *Proto,
Richard Smith588bd9b2014-08-27 04:59:42 +00001211 ArrayRef<const Expr *> Args,
Ted Kremenek2bc73332014-01-17 06:24:43 +00001212 SourceLocation CallSiteLoc) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001213 assert((FDecl || Proto) && "Need a function declaration or prototype");
1214
Ted Kremenek9aedc152014-01-17 06:24:56 +00001215 // Check the attributes attached to the method/function itself.
Richard Smith588bd9b2014-08-27 04:59:42 +00001216 llvm::SmallBitVector NonNullArgs;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001217 if (FDecl) {
1218 // Handle the nonnull attribute on the function/method declaration itself.
1219 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1220 if (!NonNull->args_size()) {
1221 // Easy case: all pointer arguments are nonnull.
1222 for (const auto *Arg : Args)
1223 if (S.isValidPointerAttrType(Arg->getType()))
1224 CheckNonNullArgument(S, Arg, CallSiteLoc);
1225 return;
1226 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001227
Douglas Gregorb4866e82015-06-19 18:13:19 +00001228 for (unsigned Val : NonNull->args()) {
1229 if (Val >= Args.size())
1230 continue;
1231 if (NonNullArgs.empty())
1232 NonNullArgs.resize(Args.size());
1233 NonNullArgs.set(Val);
1234 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001235 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001236 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001237
Douglas Gregorb4866e82015-06-19 18:13:19 +00001238 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1239 // Handle the nonnull attribute on the parameters of the
1240 // function/method.
1241 ArrayRef<ParmVarDecl*> parms;
1242 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1243 parms = FD->parameters();
1244 else
1245 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1246
1247 unsigned ParamIndex = 0;
1248 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1249 I != E; ++I, ++ParamIndex) {
1250 const ParmVarDecl *PVD = *I;
1251 if (PVD->hasAttr<NonNullAttr>() ||
1252 isNonNullType(S.Context, PVD->getType())) {
1253 if (NonNullArgs.empty())
1254 NonNullArgs.resize(Args.size());
Ted Kremenek9aedc152014-01-17 06:24:56 +00001255
Douglas Gregorb4866e82015-06-19 18:13:19 +00001256 NonNullArgs.set(ParamIndex);
1257 }
1258 }
1259 } else {
1260 // If we have a non-function, non-method declaration but no
1261 // function prototype, try to dig out the function prototype.
1262 if (!Proto) {
1263 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1264 QualType type = VD->getType().getNonReferenceType();
1265 if (auto pointerType = type->getAs<PointerType>())
1266 type = pointerType->getPointeeType();
1267 else if (auto blockType = type->getAs<BlockPointerType>())
1268 type = blockType->getPointeeType();
1269 // FIXME: data member pointers?
1270
1271 // Dig out the function prototype, if there is one.
1272 Proto = type->getAs<FunctionProtoType>();
1273 }
1274 }
1275
1276 // Fill in non-null argument information from the nullability
1277 // information on the parameter types (if we have them).
1278 if (Proto) {
1279 unsigned Index = 0;
1280 for (auto paramType : Proto->getParamTypes()) {
1281 if (isNonNullType(S.Context, paramType)) {
1282 if (NonNullArgs.empty())
1283 NonNullArgs.resize(Args.size());
1284
1285 NonNullArgs.set(Index);
1286 }
1287
1288 ++Index;
1289 }
1290 }
Ted Kremenek9aedc152014-01-17 06:24:56 +00001291 }
Richard Smith588bd9b2014-08-27 04:59:42 +00001292
Douglas Gregorb4866e82015-06-19 18:13:19 +00001293 // Check for non-null arguments.
1294 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1295 ArgIndex != ArgIndexEnd; ++ArgIndex) {
Richard Smith588bd9b2014-08-27 04:59:42 +00001296 if (NonNullArgs[ArgIndex])
1297 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
Douglas Gregorb4866e82015-06-19 18:13:19 +00001298 }
Ted Kremenek2bc73332014-01-17 06:24:43 +00001299}
1300
Richard Smith55ce3522012-06-25 20:30:08 +00001301/// Handles the checks for format strings, non-POD arguments to vararg
1302/// functions, and NULL arguments passed to non-NULL parameters.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001303void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1304 ArrayRef<const Expr *> Args, bool IsMemberFunction,
Alp Toker9cacbab2014-01-20 20:26:09 +00001305 SourceLocation Loc, SourceRange Range,
Richard Smith55ce3522012-06-25 20:30:08 +00001306 VariadicCallType CallType) {
Richard Smithd7293d72013-08-05 18:49:43 +00001307 // FIXME: We should check as much as we can in the template definition.
Jordan Rose3c14b232012-10-02 01:49:54 +00001308 if (CurContext->isDependentContext())
1309 return;
Daniel Dunbardd9b2d12008-10-02 18:44:07 +00001310
Ted Kremenekb8176da2010-09-09 04:33:05 +00001311 // Printf and scanf checking.
Richard Smithd7293d72013-08-05 18:49:43 +00001312 llvm::SmallBitVector CheckedVarArgs;
1313 if (FDecl) {
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001314 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001315 // Only create vector if there are format attributes.
1316 CheckedVarArgs.resize(Args.size());
1317
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00001318 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
Benjamin Kramerf62e81d2013-08-08 11:08:26 +00001319 CheckedVarArgs);
Benjamin Kramer989ab8b2013-08-09 09:39:17 +00001320 }
Richard Smithd7293d72013-08-05 18:49:43 +00001321 }
Richard Smith55ce3522012-06-25 20:30:08 +00001322
1323 // Refuse POD arguments that weren't caught by the format string
1324 // checks above.
Richard Smithd7293d72013-08-05 18:49:43 +00001325 if (CallType != VariadicDoesNotApply) {
Douglas Gregorb4866e82015-06-19 18:13:19 +00001326 unsigned NumParams = Proto ? Proto->getNumParams()
1327 : FDecl && isa<FunctionDecl>(FDecl)
1328 ? cast<FunctionDecl>(FDecl)->getNumParams()
1329 : FDecl && isa<ObjCMethodDecl>(FDecl)
1330 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1331 : 0;
1332
Alp Toker9cacbab2014-01-20 20:26:09 +00001333 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001334 // Args[ArgIdx] can be null in malformed code.
Richard Smithd7293d72013-08-05 18:49:43 +00001335 if (const Expr *Arg = Args[ArgIdx]) {
1336 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1337 checkVariadicArgument(Arg, CallType);
1338 }
Ted Kremenek241f1ef2012-10-11 19:06:43 +00001339 }
Richard Smithd7293d72013-08-05 18:49:43 +00001340 }
Mike Stump11289f42009-09-09 15:08:12 +00001341
Douglas Gregorb4866e82015-06-19 18:13:19 +00001342 if (FDecl || Proto) {
1343 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001344
Richard Trieu41bc0992013-06-22 00:20:41 +00001345 // Type safety checking.
Douglas Gregorb4866e82015-06-19 18:13:19 +00001346 if (FDecl) {
1347 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1348 CheckArgumentWithTypeTag(I, Args.data());
1349 }
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00001350 }
Richard Smith55ce3522012-06-25 20:30:08 +00001351}
1352
1353/// CheckConstructorCall - Check a constructor call for correctness and safety
1354/// properties not enforced by the C type system.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00001355void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1356 ArrayRef<const Expr *> Args,
Richard Smith55ce3522012-06-25 20:30:08 +00001357 const FunctionProtoType *Proto,
1358 SourceLocation Loc) {
1359 VariadicCallType CallType =
1360 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
Douglas Gregorb4866e82015-06-19 18:13:19 +00001361 checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1362 CallType);
Richard Smith55ce3522012-06-25 20:30:08 +00001363}
1364
1365/// CheckFunctionCall - Check a direct function call for various correctness
1366/// and safety properties not strictly enforced by the C type system.
1367bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1368 const FunctionProtoType *Proto) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001369 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1370 isa<CXXMethodDecl>(FDecl);
1371 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1372 IsMemberOperatorCall;
Richard Smith55ce3522012-06-25 20:30:08 +00001373 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1374 TheCall->getCallee());
Eli Friedman726d11c2012-10-11 00:30:58 +00001375 Expr** Args = TheCall->getArgs();
1376 unsigned NumArgs = TheCall->getNumArgs();
Eli Friedmanadf42182012-10-11 00:34:15 +00001377 if (IsMemberOperatorCall) {
Eli Friedman726d11c2012-10-11 00:30:58 +00001378 // If this is a call to a member operator, hide the first argument
1379 // from checkCall.
1380 // FIXME: Our choice of AST representation here is less than ideal.
1381 ++Args;
1382 --NumArgs;
1383 }
Douglas Gregorb4866e82015-06-19 18:13:19 +00001384 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
Richard Smith55ce3522012-06-25 20:30:08 +00001385 IsMemberFunction, TheCall->getRParenLoc(),
1386 TheCall->getCallee()->getSourceRange(), CallType);
1387
1388 IdentifierInfo *FnInfo = FDecl->getIdentifier();
1389 // None of the checks below are needed for functions that don't have
1390 // simple names (e.g., C++ conversion functions).
1391 if (!FnInfo)
1392 return false;
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001393
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001394 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00001395 if (getLangOpts().ObjC1)
1396 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00001397
Anna Zaks22122702012-01-17 00:37:07 +00001398 unsigned CMId = FDecl->getMemoryFunctionKind();
1399 if (CMId == 0)
Anna Zaks201d4892012-01-13 21:52:01 +00001400 return false;
Ted Kremenek6865f772011-08-18 20:55:45 +00001401
Anna Zaks201d4892012-01-13 21:52:01 +00001402 // Handle memory setting and copying functions.
Anna Zaks22122702012-01-17 00:37:07 +00001403 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
Ted Kremenek6865f772011-08-18 20:55:45 +00001404 CheckStrlcpycatArguments(TheCall, FnInfo);
Anna Zaks314cd092012-02-01 19:08:57 +00001405 else if (CMId == Builtin::BIstrncat)
1406 CheckStrncatArguments(TheCall, FnInfo);
Anna Zaks201d4892012-01-13 21:52:01 +00001407 else
Anna Zaks22122702012-01-17 00:37:07 +00001408 CheckMemaccessArguments(TheCall, CMId, FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +00001409
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001410 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +00001411}
1412
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001413bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
Dmitri Gribenko1debc462013-05-05 19:42:09 +00001414 ArrayRef<const Expr *> Args) {
Richard Smith55ce3522012-06-25 20:30:08 +00001415 VariadicCallType CallType =
1416 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001417
Douglas Gregorb4866e82015-06-19 18:13:19 +00001418 checkCall(Method, nullptr, Args,
1419 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1420 CallType);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001421
1422 return false;
1423}
1424
Richard Trieu664c4c62013-06-20 21:03:13 +00001425bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1426 const FunctionProtoType *Proto) {
Aaron Ballmanb673c652015-04-23 16:14:19 +00001427 QualType Ty;
1428 if (const auto *V = dyn_cast<VarDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001429 Ty = V->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001430 else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
Douglas Gregorb4866e82015-06-19 18:13:19 +00001431 Ty = F->getType().getNonReferenceType();
Aaron Ballmanb673c652015-04-23 16:14:19 +00001432 else
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001433 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001434
Douglas Gregorb4866e82015-06-19 18:13:19 +00001435 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1436 !Ty->isFunctionProtoType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001437 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001438
Richard Trieu664c4c62013-06-20 21:03:13 +00001439 VariadicCallType CallType;
Richard Trieu72ae1732013-06-20 23:21:54 +00001440 if (!Proto || !Proto->isVariadic()) {
Richard Trieu664c4c62013-06-20 21:03:13 +00001441 CallType = VariadicDoesNotApply;
1442 } else if (Ty->isBlockPointerType()) {
1443 CallType = VariadicBlock;
1444 } else { // Ty->isFunctionPointerType()
1445 CallType = VariadicFunction;
1446 }
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001447
Douglas Gregorb4866e82015-06-19 18:13:19 +00001448 checkCall(NDecl, Proto,
1449 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1450 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Smith55ce3522012-06-25 20:30:08 +00001451 TheCall->getCallee()->getSourceRange(), CallType);
Alp Toker9cacbab2014-01-20 20:26:09 +00001452
Anders Carlssonbc4c1072009-08-16 01:56:34 +00001453 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +00001454}
1455
Richard Trieu41bc0992013-06-22 00:20:41 +00001456/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1457/// such as function pointers returned from functions.
1458bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001459 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
Richard Trieu41bc0992013-06-22 00:20:41 +00001460 TheCall->getCallee());
Douglas Gregorb4866e82015-06-19 18:13:19 +00001461 checkCall(/*FDecl=*/nullptr, Proto,
Craig Topper8c2a2a02014-08-30 16:55:39 +00001462 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
Douglas Gregorb4866e82015-06-19 18:13:19 +00001463 /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
Richard Trieu41bc0992013-06-22 00:20:41 +00001464 TheCall->getCallee()->getSourceRange(), CallType);
1465
1466 return false;
1467}
1468
Tim Northovere94a34c2014-03-11 10:49:14 +00001469static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1470 if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1471 Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1472 return false;
1473
1474 switch (Op) {
1475 case AtomicExpr::AO__c11_atomic_init:
1476 llvm_unreachable("There is no ordering argument for an init");
1477
1478 case AtomicExpr::AO__c11_atomic_load:
1479 case AtomicExpr::AO__atomic_load_n:
1480 case AtomicExpr::AO__atomic_load:
1481 return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1482 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1483
1484 case AtomicExpr::AO__c11_atomic_store:
1485 case AtomicExpr::AO__atomic_store:
1486 case AtomicExpr::AO__atomic_store_n:
1487 return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1488 Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1489 Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1490
1491 default:
1492 return true;
1493 }
1494}
1495
Richard Smithfeea8832012-04-12 05:08:17 +00001496ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1497 AtomicExpr::AtomicOp Op) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001498 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1499 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001500
Richard Smithfeea8832012-04-12 05:08:17 +00001501 // All these operations take one of the following forms:
1502 enum {
1503 // C __c11_atomic_init(A *, C)
1504 Init,
1505 // C __c11_atomic_load(A *, int)
1506 Load,
1507 // void __atomic_load(A *, CP, int)
1508 Copy,
1509 // C __c11_atomic_add(A *, M, int)
1510 Arithmetic,
1511 // C __atomic_exchange_n(A *, CP, int)
1512 Xchg,
1513 // void __atomic_exchange(A *, C *, CP, int)
1514 GNUXchg,
1515 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1516 C11CmpXchg,
1517 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1518 GNUCmpXchg
1519 } Form = Init;
1520 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1521 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1522 // where:
1523 // C is an appropriate type,
1524 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1525 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1526 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1527 // the int parameters are for orderings.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001528
Gabor Horvath98bd0982015-03-16 09:59:54 +00001529 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1530 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1531 AtomicExpr::AO__atomic_load,
1532 "need to update code for modified C11 atomics");
Richard Smithfeea8832012-04-12 05:08:17 +00001533 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1534 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1535 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1536 Op == AtomicExpr::AO__atomic_store_n ||
1537 Op == AtomicExpr::AO__atomic_exchange_n ||
1538 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1539 bool IsAddSub = false;
1540
1541 switch (Op) {
1542 case AtomicExpr::AO__c11_atomic_init:
1543 Form = Init;
1544 break;
1545
1546 case AtomicExpr::AO__c11_atomic_load:
1547 case AtomicExpr::AO__atomic_load_n:
1548 Form = Load;
1549 break;
1550
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_load:
1553 case AtomicExpr::AO__atomic_store:
1554 case AtomicExpr::AO__atomic_store_n:
1555 Form = Copy;
1556 break;
1557
1558 case AtomicExpr::AO__c11_atomic_fetch_add:
1559 case AtomicExpr::AO__c11_atomic_fetch_sub:
1560 case AtomicExpr::AO__atomic_fetch_add:
1561 case AtomicExpr::AO__atomic_fetch_sub:
1562 case AtomicExpr::AO__atomic_add_fetch:
1563 case AtomicExpr::AO__atomic_sub_fetch:
1564 IsAddSub = true;
1565 // Fall through.
1566 case AtomicExpr::AO__c11_atomic_fetch_and:
1567 case AtomicExpr::AO__c11_atomic_fetch_or:
1568 case AtomicExpr::AO__c11_atomic_fetch_xor:
1569 case AtomicExpr::AO__atomic_fetch_and:
1570 case AtomicExpr::AO__atomic_fetch_or:
1571 case AtomicExpr::AO__atomic_fetch_xor:
Richard Smithd65cee92012-04-13 06:31:38 +00001572 case AtomicExpr::AO__atomic_fetch_nand:
Richard Smithfeea8832012-04-12 05:08:17 +00001573 case AtomicExpr::AO__atomic_and_fetch:
1574 case AtomicExpr::AO__atomic_or_fetch:
1575 case AtomicExpr::AO__atomic_xor_fetch:
Richard Smithd65cee92012-04-13 06:31:38 +00001576 case AtomicExpr::AO__atomic_nand_fetch:
Richard Smithfeea8832012-04-12 05:08:17 +00001577 Form = Arithmetic;
1578 break;
1579
1580 case AtomicExpr::AO__c11_atomic_exchange:
1581 case AtomicExpr::AO__atomic_exchange_n:
1582 Form = Xchg;
1583 break;
1584
1585 case AtomicExpr::AO__atomic_exchange:
1586 Form = GNUXchg;
1587 break;
1588
1589 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1590 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1591 Form = C11CmpXchg;
1592 break;
1593
1594 case AtomicExpr::AO__atomic_compare_exchange:
1595 case AtomicExpr::AO__atomic_compare_exchange_n:
1596 Form = GNUCmpXchg;
1597 break;
1598 }
1599
1600 // Check we have the right number of arguments.
1601 if (TheCall->getNumArgs() < NumArgs[Form]) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001602 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001603 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001604 << TheCall->getCallee()->getSourceRange();
1605 return ExprError();
Richard Smithfeea8832012-04-12 05:08:17 +00001606 } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1607 Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001608 diag::err_typecheck_call_too_many_args)
Richard Smithfeea8832012-04-12 05:08:17 +00001609 << 0 << NumArgs[Form] << TheCall->getNumArgs()
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001610 << TheCall->getCallee()->getSourceRange();
1611 return ExprError();
1612 }
1613
Richard Smithfeea8832012-04-12 05:08:17 +00001614 // Inspect the first argument of the atomic operation.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001615 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001616 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1617 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1618 if (!pointerType) {
Richard Smithfeea8832012-04-12 05:08:17 +00001619 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001620 << Ptr->getType() << Ptr->getSourceRange();
1621 return ExprError();
1622 }
1623
Richard Smithfeea8832012-04-12 05:08:17 +00001624 // For a __c11 builtin, this should be a pointer to an _Atomic type.
1625 QualType AtomTy = pointerType->getPointeeType(); // 'A'
1626 QualType ValType = AtomTy; // 'C'
1627 if (IsC11) {
1628 if (!AtomTy->isAtomicType()) {
1629 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1630 << Ptr->getType() << Ptr->getSourceRange();
1631 return ExprError();
1632 }
Richard Smithe00921a2012-09-15 06:09:58 +00001633 if (AtomTy.isConstQualified()) {
1634 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1635 << Ptr->getType() << Ptr->getSourceRange();
1636 return ExprError();
1637 }
Richard Smithfeea8832012-04-12 05:08:17 +00001638 ValType = AtomTy->getAs<AtomicType>()->getValueType();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001639 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001640
Richard Smithfeea8832012-04-12 05:08:17 +00001641 // For an arithmetic operation, the implied arithmetic must be well-formed.
1642 if (Form == Arithmetic) {
1643 // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1644 if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1645 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1646 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1647 return ExprError();
1648 }
1649 if (!IsAddSub && !ValType->isIntegerType()) {
1650 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1651 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1652 return ExprError();
1653 }
David Majnemere85cff82015-01-28 05:48:06 +00001654 if (IsC11 && ValType->isPointerType() &&
1655 RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1656 diag::err_incomplete_type)) {
1657 return ExprError();
1658 }
Richard Smithfeea8832012-04-12 05:08:17 +00001659 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1660 // For __atomic_*_n operations, the value type must be a scalar integral or
1661 // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001662 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
Richard Smithfeea8832012-04-12 05:08:17 +00001663 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1664 return ExprError();
1665 }
1666
Eli Friedmanaa769812013-09-11 03:49:34 +00001667 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1668 !AtomTy->isScalarType()) {
Richard Smithfeea8832012-04-12 05:08:17 +00001669 // For GNU atomics, require a trivially-copyable type. This is not part of
1670 // the GNU atomics specification, but we enforce it for sanity.
1671 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001672 << Ptr->getType() << Ptr->getSourceRange();
1673 return ExprError();
1674 }
1675
Richard Smithfeea8832012-04-12 05:08:17 +00001676 // FIXME: For any builtin other than a load, the ValType must not be
1677 // const-qualified.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001678
1679 switch (ValType.getObjCLifetime()) {
1680 case Qualifiers::OCL_None:
1681 case Qualifiers::OCL_ExplicitNone:
1682 // okay
1683 break;
1684
1685 case Qualifiers::OCL_Weak:
1686 case Qualifiers::OCL_Strong:
1687 case Qualifiers::OCL_Autoreleasing:
Richard Smithfeea8832012-04-12 05:08:17 +00001688 // FIXME: Can this happen? By this point, ValType should be known
1689 // to be trivially copyable.
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001690 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1691 << ValType << Ptr->getSourceRange();
1692 return ExprError();
1693 }
1694
David Majnemerc6eb6502015-06-03 00:26:35 +00001695 // atomic_fetch_or takes a pointer to a volatile 'A'. We shouldn't let the
1696 // volatile-ness of the pointee-type inject itself into the result or the
1697 // other operands.
1698 ValType.removeLocalVolatile();
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001699 QualType ResultType = ValType;
Richard Smithfeea8832012-04-12 05:08:17 +00001700 if (Form == Copy || Form == GNUXchg || Form == Init)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001701 ResultType = Context.VoidTy;
Richard Smithfeea8832012-04-12 05:08:17 +00001702 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001703 ResultType = Context.BoolTy;
1704
Richard Smithfeea8832012-04-12 05:08:17 +00001705 // The type of a parameter passed 'by value'. In the GNU atomics, such
1706 // arguments are actually passed as pointers.
1707 QualType ByValType = ValType; // 'CP'
1708 if (!IsC11 && !IsN)
1709 ByValType = Ptr->getType();
1710
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001711 // The first argument --- the pointer --- has a fixed type; we
1712 // deduce the types of the rest of the arguments accordingly. Walk
1713 // the remaining arguments, converting them to the deduced value type.
Richard Smithfeea8832012-04-12 05:08:17 +00001714 for (unsigned i = 1; i != NumArgs[Form]; ++i) {
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001715 QualType Ty;
Richard Smithfeea8832012-04-12 05:08:17 +00001716 if (i < NumVals[Form] + 1) {
1717 switch (i) {
1718 case 1:
1719 // The second argument is the non-atomic operand. For arithmetic, this
1720 // is always passed by value, and for a compare_exchange it is always
1721 // passed by address. For the rest, GNU uses by-address and C11 uses
1722 // by-value.
1723 assert(Form != Load);
1724 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1725 Ty = ValType;
1726 else if (Form == Copy || Form == Xchg)
1727 Ty = ByValType;
1728 else if (Form == Arithmetic)
1729 Ty = Context.getPointerDiffType();
1730 else
1731 Ty = Context.getPointerType(ValType.getUnqualifiedType());
1732 break;
1733 case 2:
1734 // The third argument to compare_exchange / GNU exchange is a
1735 // (pointer to a) desired value.
1736 Ty = ByValType;
1737 break;
1738 case 3:
1739 // The fourth argument to GNU compare_exchange is a 'weak' flag.
1740 Ty = Context.BoolTy;
1741 break;
1742 }
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001743 } else {
1744 // The order(s) are always converted to int.
1745 Ty = Context.IntTy;
1746 }
Richard Smithfeea8832012-04-12 05:08:17 +00001747
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001748 InitializedEntity Entity =
1749 InitializedEntity::InitializeParameter(Context, Ty, false);
Richard Smithfeea8832012-04-12 05:08:17 +00001750 ExprResult Arg = TheCall->getArg(i);
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001751 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1752 if (Arg.isInvalid())
1753 return true;
1754 TheCall->setArg(i, Arg.get());
1755 }
1756
Richard Smithfeea8832012-04-12 05:08:17 +00001757 // Permute the arguments into a 'consistent' order.
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001758 SmallVector<Expr*, 5> SubExprs;
1759 SubExprs.push_back(Ptr);
Richard Smithfeea8832012-04-12 05:08:17 +00001760 switch (Form) {
1761 case Init:
1762 // Note, AtomicExpr::getVal1() has a special case for this atomic.
David Chisnallfa35df62012-01-16 17:27:18 +00001763 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001764 break;
1765 case Load:
1766 SubExprs.push_back(TheCall->getArg(1)); // Order
1767 break;
1768 case Copy:
1769 case Arithmetic:
1770 case Xchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001771 SubExprs.push_back(TheCall->getArg(2)); // Order
1772 SubExprs.push_back(TheCall->getArg(1)); // Val1
Richard Smithfeea8832012-04-12 05:08:17 +00001773 break;
1774 case GNUXchg:
1775 // Note, AtomicExpr::getVal2() has a special case for this atomic.
1776 SubExprs.push_back(TheCall->getArg(3)); // Order
1777 SubExprs.push_back(TheCall->getArg(1)); // Val1
1778 SubExprs.push_back(TheCall->getArg(2)); // Val2
1779 break;
1780 case C11CmpXchg:
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001781 SubExprs.push_back(TheCall->getArg(3)); // Order
1782 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001783 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
David Chisnall891ec282012-03-29 17:58:59 +00001784 SubExprs.push_back(TheCall->getArg(2)); // Val2
Richard Smithfeea8832012-04-12 05:08:17 +00001785 break;
1786 case GNUCmpXchg:
1787 SubExprs.push_back(TheCall->getArg(4)); // Order
1788 SubExprs.push_back(TheCall->getArg(1)); // Val1
1789 SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1790 SubExprs.push_back(TheCall->getArg(2)); // Val2
1791 SubExprs.push_back(TheCall->getArg(3)); // Weak
1792 break;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001793 }
Tim Northovere94a34c2014-03-11 10:49:14 +00001794
1795 if (SubExprs.size() >= 2 && Form != Init) {
1796 llvm::APSInt Result(32);
1797 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1798 !isValidOrderingForOp(Result.getSExtValue(), Op))
Tim Northoverc83472e2014-03-11 11:35:10 +00001799 Diag(SubExprs[1]->getLocStart(),
1800 diag::warn_atomic_op_has_invalid_memory_order)
1801 << SubExprs[1]->getSourceRange();
Tim Northovere94a34c2014-03-11 10:49:14 +00001802 }
1803
Fariborz Jahanian615de762013-05-28 17:37:39 +00001804 AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1805 SubExprs, ResultType, Op,
1806 TheCall->getRParenLoc());
1807
1808 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1809 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1810 Context.AtomicUsesUnsupportedLibcall(AE))
1811 Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1812 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
Eli Friedman8d3e43f2011-10-14 22:48:56 +00001813
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001814 return AE;
Eli Friedmandf14b3a2011-10-11 02:20:01 +00001815}
1816
1817
John McCall29ad95b2011-08-27 01:09:30 +00001818/// checkBuiltinArgument - Given a call to a builtin function, perform
1819/// normal type-checking on the given argument, updating the call in
1820/// place. This is useful when a builtin function requires custom
1821/// type-checking for some of its arguments but not necessarily all of
1822/// them.
1823///
1824/// Returns true on error.
1825static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1826 FunctionDecl *Fn = E->getDirectCallee();
1827 assert(Fn && "builtin call without direct callee!");
1828
1829 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1830 InitializedEntity Entity =
1831 InitializedEntity::InitializeParameter(S.Context, Param);
1832
1833 ExprResult Arg = E->getArg(0);
1834 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1835 if (Arg.isInvalid())
1836 return true;
1837
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001838 E->setArg(ArgIndex, Arg.get());
John McCall29ad95b2011-08-27 01:09:30 +00001839 return false;
1840}
1841
Chris Lattnerdc046542009-05-08 06:58:22 +00001842/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1843/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1844/// type of its first argument. The main ActOnCallExpr routines have already
1845/// promoted the types of arguments because all of these calls are prototyped as
1846/// void(...).
1847///
1848/// This function goes through and does final semantic checking for these
1849/// builtins,
John McCalldadc5752010-08-24 06:29:42 +00001850ExprResult
1851Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001852 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +00001853 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1854 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1855
1856 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001857 if (TheCall->getNumArgs() < 1) {
1858 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1859 << 0 << 1 << TheCall->getNumArgs()
1860 << TheCall->getCallee()->getSourceRange();
1861 return ExprError();
1862 }
Mike Stump11289f42009-09-09 15:08:12 +00001863
Chris Lattnerdc046542009-05-08 06:58:22 +00001864 // Inspect the first argument of the atomic builtin. This should always be
1865 // a pointer type, whose element is an integral scalar or pointer type.
1866 // Because it is a pointer type, we don't have to worry about any implicit
1867 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001868 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +00001869 Expr *FirstArg = TheCall->getArg(0);
Eli Friedman844f9452012-01-23 02:35:22 +00001870 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1871 if (FirstArgResult.isInvalid())
1872 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001873 FirstArg = FirstArgResult.get();
Eli Friedman844f9452012-01-23 02:35:22 +00001874 TheCall->setArg(0, FirstArg);
1875
John McCall31168b02011-06-15 23:02:42 +00001876 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1877 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001878 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1879 << FirstArg->getType() << FirstArg->getSourceRange();
1880 return ExprError();
1881 }
Mike Stump11289f42009-09-09 15:08:12 +00001882
John McCall31168b02011-06-15 23:02:42 +00001883 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +00001884 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001885 !ValType->isBlockPointerType()) {
1886 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1887 << FirstArg->getType() << FirstArg->getSourceRange();
1888 return ExprError();
1889 }
Chris Lattnerdc046542009-05-08 06:58:22 +00001890
John McCall31168b02011-06-15 23:02:42 +00001891 switch (ValType.getObjCLifetime()) {
1892 case Qualifiers::OCL_None:
1893 case Qualifiers::OCL_ExplicitNone:
1894 // okay
1895 break;
1896
1897 case Qualifiers::OCL_Weak:
1898 case Qualifiers::OCL_Strong:
1899 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001900 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +00001901 << ValType << FirstArg->getSourceRange();
1902 return ExprError();
1903 }
1904
John McCallb50451a2011-10-05 07:41:44 +00001905 // Strip any qualifiers off ValType.
1906 ValType = ValType.getUnqualifiedType();
1907
Chandler Carruth3973af72010-07-18 20:54:12 +00001908 // The majority of builtins return a value, but a few have special return
1909 // types, so allow them to override appropriately below.
1910 QualType ResultType = ValType;
1911
Chris Lattnerdc046542009-05-08 06:58:22 +00001912 // We need to figure out which concrete builtin this maps onto. For example,
1913 // __sync_fetch_and_add with a 2 byte object turns into
1914 // __sync_fetch_and_add_2.
1915#define BUILTIN_ROW(x) \
1916 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1917 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Chris Lattnerdc046542009-05-08 06:58:22 +00001919 static const unsigned BuiltinIndices[][5] = {
1920 BUILTIN_ROW(__sync_fetch_and_add),
1921 BUILTIN_ROW(__sync_fetch_and_sub),
1922 BUILTIN_ROW(__sync_fetch_and_or),
1923 BUILTIN_ROW(__sync_fetch_and_and),
1924 BUILTIN_ROW(__sync_fetch_and_xor),
Hal Finkeld2208b52014-10-02 20:53:50 +00001925 BUILTIN_ROW(__sync_fetch_and_nand),
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattnerdc046542009-05-08 06:58:22 +00001927 BUILTIN_ROW(__sync_add_and_fetch),
1928 BUILTIN_ROW(__sync_sub_and_fetch),
1929 BUILTIN_ROW(__sync_and_and_fetch),
1930 BUILTIN_ROW(__sync_or_and_fetch),
1931 BUILTIN_ROW(__sync_xor_and_fetch),
Hal Finkeld2208b52014-10-02 20:53:50 +00001932 BUILTIN_ROW(__sync_nand_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattnerdc046542009-05-08 06:58:22 +00001934 BUILTIN_ROW(__sync_val_compare_and_swap),
1935 BUILTIN_ROW(__sync_bool_compare_and_swap),
1936 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +00001937 BUILTIN_ROW(__sync_lock_release),
1938 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +00001939 };
Mike Stump11289f42009-09-09 15:08:12 +00001940#undef BUILTIN_ROW
1941
Chris Lattnerdc046542009-05-08 06:58:22 +00001942 // Determine the index of the size.
1943 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +00001944 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +00001945 case 1: SizeIndex = 0; break;
1946 case 2: SizeIndex = 1; break;
1947 case 4: SizeIndex = 2; break;
1948 case 8: SizeIndex = 3; break;
1949 case 16: SizeIndex = 4; break;
1950 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +00001951 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1952 << FirstArg->getType() << FirstArg->getSourceRange();
1953 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +00001954 }
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattnerdc046542009-05-08 06:58:22 +00001956 // Each of these builtins has one pointer argument, followed by some number of
1957 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1958 // that we ignore. Find out which row of BuiltinIndices to read from as well
1959 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +00001960 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +00001961 unsigned BuiltinIndex, NumFixed = 1;
Hal Finkeld2208b52014-10-02 20:53:50 +00001962 bool WarnAboutSemanticsChange = false;
Chris Lattnerdc046542009-05-08 06:58:22 +00001963 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +00001964 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Douglas Gregor73722482011-11-28 16:30:08 +00001965 case Builtin::BI__sync_fetch_and_add:
1966 case Builtin::BI__sync_fetch_and_add_1:
1967 case Builtin::BI__sync_fetch_and_add_2:
1968 case Builtin::BI__sync_fetch_and_add_4:
1969 case Builtin::BI__sync_fetch_and_add_8:
1970 case Builtin::BI__sync_fetch_and_add_16:
1971 BuiltinIndex = 0;
1972 break;
1973
1974 case Builtin::BI__sync_fetch_and_sub:
1975 case Builtin::BI__sync_fetch_and_sub_1:
1976 case Builtin::BI__sync_fetch_and_sub_2:
1977 case Builtin::BI__sync_fetch_and_sub_4:
1978 case Builtin::BI__sync_fetch_and_sub_8:
1979 case Builtin::BI__sync_fetch_and_sub_16:
1980 BuiltinIndex = 1;
1981 break;
1982
1983 case Builtin::BI__sync_fetch_and_or:
1984 case Builtin::BI__sync_fetch_and_or_1:
1985 case Builtin::BI__sync_fetch_and_or_2:
1986 case Builtin::BI__sync_fetch_and_or_4:
1987 case Builtin::BI__sync_fetch_and_or_8:
1988 case Builtin::BI__sync_fetch_and_or_16:
1989 BuiltinIndex = 2;
1990 break;
1991
1992 case Builtin::BI__sync_fetch_and_and:
1993 case Builtin::BI__sync_fetch_and_and_1:
1994 case Builtin::BI__sync_fetch_and_and_2:
1995 case Builtin::BI__sync_fetch_and_and_4:
1996 case Builtin::BI__sync_fetch_and_and_8:
1997 case Builtin::BI__sync_fetch_and_and_16:
1998 BuiltinIndex = 3;
1999 break;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor73722482011-11-28 16:30:08 +00002001 case Builtin::BI__sync_fetch_and_xor:
2002 case Builtin::BI__sync_fetch_and_xor_1:
2003 case Builtin::BI__sync_fetch_and_xor_2:
2004 case Builtin::BI__sync_fetch_and_xor_4:
2005 case Builtin::BI__sync_fetch_and_xor_8:
2006 case Builtin::BI__sync_fetch_and_xor_16:
2007 BuiltinIndex = 4;
2008 break;
2009
Hal Finkeld2208b52014-10-02 20:53:50 +00002010 case Builtin::BI__sync_fetch_and_nand:
2011 case Builtin::BI__sync_fetch_and_nand_1:
2012 case Builtin::BI__sync_fetch_and_nand_2:
2013 case Builtin::BI__sync_fetch_and_nand_4:
2014 case Builtin::BI__sync_fetch_and_nand_8:
2015 case Builtin::BI__sync_fetch_and_nand_16:
2016 BuiltinIndex = 5;
2017 WarnAboutSemanticsChange = true;
2018 break;
2019
Douglas Gregor73722482011-11-28 16:30:08 +00002020 case Builtin::BI__sync_add_and_fetch:
2021 case Builtin::BI__sync_add_and_fetch_1:
2022 case Builtin::BI__sync_add_and_fetch_2:
2023 case Builtin::BI__sync_add_and_fetch_4:
2024 case Builtin::BI__sync_add_and_fetch_8:
2025 case Builtin::BI__sync_add_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002026 BuiltinIndex = 6;
Douglas Gregor73722482011-11-28 16:30:08 +00002027 break;
2028
2029 case Builtin::BI__sync_sub_and_fetch:
2030 case Builtin::BI__sync_sub_and_fetch_1:
2031 case Builtin::BI__sync_sub_and_fetch_2:
2032 case Builtin::BI__sync_sub_and_fetch_4:
2033 case Builtin::BI__sync_sub_and_fetch_8:
2034 case Builtin::BI__sync_sub_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002035 BuiltinIndex = 7;
Douglas Gregor73722482011-11-28 16:30:08 +00002036 break;
2037
2038 case Builtin::BI__sync_and_and_fetch:
2039 case Builtin::BI__sync_and_and_fetch_1:
2040 case Builtin::BI__sync_and_and_fetch_2:
2041 case Builtin::BI__sync_and_and_fetch_4:
2042 case Builtin::BI__sync_and_and_fetch_8:
2043 case Builtin::BI__sync_and_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002044 BuiltinIndex = 8;
Douglas Gregor73722482011-11-28 16:30:08 +00002045 break;
2046
2047 case Builtin::BI__sync_or_and_fetch:
2048 case Builtin::BI__sync_or_and_fetch_1:
2049 case Builtin::BI__sync_or_and_fetch_2:
2050 case Builtin::BI__sync_or_and_fetch_4:
2051 case Builtin::BI__sync_or_and_fetch_8:
2052 case Builtin::BI__sync_or_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002053 BuiltinIndex = 9;
Douglas Gregor73722482011-11-28 16:30:08 +00002054 break;
2055
2056 case Builtin::BI__sync_xor_and_fetch:
2057 case Builtin::BI__sync_xor_and_fetch_1:
2058 case Builtin::BI__sync_xor_and_fetch_2:
2059 case Builtin::BI__sync_xor_and_fetch_4:
2060 case Builtin::BI__sync_xor_and_fetch_8:
2061 case Builtin::BI__sync_xor_and_fetch_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002062 BuiltinIndex = 10;
2063 break;
2064
2065 case Builtin::BI__sync_nand_and_fetch:
2066 case Builtin::BI__sync_nand_and_fetch_1:
2067 case Builtin::BI__sync_nand_and_fetch_2:
2068 case Builtin::BI__sync_nand_and_fetch_4:
2069 case Builtin::BI__sync_nand_and_fetch_8:
2070 case Builtin::BI__sync_nand_and_fetch_16:
2071 BuiltinIndex = 11;
2072 WarnAboutSemanticsChange = true;
Douglas Gregor73722482011-11-28 16:30:08 +00002073 break;
Mike Stump11289f42009-09-09 15:08:12 +00002074
Chris Lattnerdc046542009-05-08 06:58:22 +00002075 case Builtin::BI__sync_val_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002076 case Builtin::BI__sync_val_compare_and_swap_1:
2077 case Builtin::BI__sync_val_compare_and_swap_2:
2078 case Builtin::BI__sync_val_compare_and_swap_4:
2079 case Builtin::BI__sync_val_compare_and_swap_8:
2080 case Builtin::BI__sync_val_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002081 BuiltinIndex = 12;
Chris Lattnerdc046542009-05-08 06:58:22 +00002082 NumFixed = 2;
2083 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002084
Chris Lattnerdc046542009-05-08 06:58:22 +00002085 case Builtin::BI__sync_bool_compare_and_swap:
Douglas Gregor73722482011-11-28 16:30:08 +00002086 case Builtin::BI__sync_bool_compare_and_swap_1:
2087 case Builtin::BI__sync_bool_compare_and_swap_2:
2088 case Builtin::BI__sync_bool_compare_and_swap_4:
2089 case Builtin::BI__sync_bool_compare_and_swap_8:
2090 case Builtin::BI__sync_bool_compare_and_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002091 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +00002092 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +00002093 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002094 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002095
2096 case Builtin::BI__sync_lock_test_and_set:
2097 case Builtin::BI__sync_lock_test_and_set_1:
2098 case Builtin::BI__sync_lock_test_and_set_2:
2099 case Builtin::BI__sync_lock_test_and_set_4:
2100 case Builtin::BI__sync_lock_test_and_set_8:
2101 case Builtin::BI__sync_lock_test_and_set_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002102 BuiltinIndex = 14;
Douglas Gregor73722482011-11-28 16:30:08 +00002103 break;
2104
Chris Lattnerdc046542009-05-08 06:58:22 +00002105 case Builtin::BI__sync_lock_release:
Douglas Gregor73722482011-11-28 16:30:08 +00002106 case Builtin::BI__sync_lock_release_1:
2107 case Builtin::BI__sync_lock_release_2:
2108 case Builtin::BI__sync_lock_release_4:
2109 case Builtin::BI__sync_lock_release_8:
2110 case Builtin::BI__sync_lock_release_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002111 BuiltinIndex = 15;
Chris Lattnerdc046542009-05-08 06:58:22 +00002112 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +00002113 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +00002114 break;
Douglas Gregor73722482011-11-28 16:30:08 +00002115
2116 case Builtin::BI__sync_swap:
2117 case Builtin::BI__sync_swap_1:
2118 case Builtin::BI__sync_swap_2:
2119 case Builtin::BI__sync_swap_4:
2120 case Builtin::BI__sync_swap_8:
2121 case Builtin::BI__sync_swap_16:
Hal Finkeld2208b52014-10-02 20:53:50 +00002122 BuiltinIndex = 16;
Douglas Gregor73722482011-11-28 16:30:08 +00002123 break;
Chris Lattnerdc046542009-05-08 06:58:22 +00002124 }
Mike Stump11289f42009-09-09 15:08:12 +00002125
Chris Lattnerdc046542009-05-08 06:58:22 +00002126 // Now that we know how many fixed arguments we expect, first check that we
2127 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002128 if (TheCall->getNumArgs() < 1+NumFixed) {
2129 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2130 << 0 << 1+NumFixed << TheCall->getNumArgs()
2131 << TheCall->getCallee()->getSourceRange();
2132 return ExprError();
2133 }
Mike Stump11289f42009-09-09 15:08:12 +00002134
Hal Finkeld2208b52014-10-02 20:53:50 +00002135 if (WarnAboutSemanticsChange) {
2136 Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2137 << TheCall->getCallee()->getSourceRange();
2138 }
2139
Chris Lattner5b9241b2009-05-08 15:36:58 +00002140 // Get the decl for the concrete builtin from this, we can tell what the
2141 // concrete integer type we should convert to is.
2142 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2143 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002144 FunctionDecl *NewBuiltinDecl;
2145 if (NewBuiltinID == BuiltinID)
2146 NewBuiltinDecl = FDecl;
2147 else {
2148 // Perform builtin lookup to avoid redeclaring it.
2149 DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2150 LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2151 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2152 assert(Res.getFoundDecl());
2153 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00002154 if (!NewBuiltinDecl)
Abramo Bagnara6cba23a2012-09-22 09:05:22 +00002155 return ExprError();
2156 }
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002157
John McCallcf142162010-08-07 06:22:56 +00002158 // The first argument --- the pointer --- has a fixed type; we
2159 // deduce the types of the rest of the arguments accordingly. Walk
2160 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +00002161 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +00002162 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +00002163
Chris Lattnerdc046542009-05-08 06:58:22 +00002164 // GCC does an implicit conversion to the pointer or integer ValType. This
2165 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +00002166 // Initialize the argument.
2167 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2168 ValType, /*consume*/ false);
2169 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +00002170 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002171 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002172
Chris Lattnerdc046542009-05-08 06:58:22 +00002173 // Okay, we have something that *can* be converted to the right type. Check
2174 // to see if there is a potentially weird extension going on here. This can
2175 // happen when you do an atomic operation on something like an char* and
2176 // pass in 42. The 42 gets converted to char. This is even more strange
2177 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +00002178 // FIXME: Do this check.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002179 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +00002180 }
Mike Stump11289f42009-09-09 15:08:12 +00002181
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002182 ASTContext& Context = this->getASTContext();
2183
2184 // Create a new DeclRefExpr to refer to the new decl.
2185 DeclRefExpr* NewDRE = DeclRefExpr::Create(
2186 Context,
2187 DRE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00002188 SourceLocation(),
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002189 NewBuiltinDecl,
John McCall113bee02012-03-10 09:33:50 +00002190 /*enclosing*/ false,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002191 DRE->getLocation(),
Eli Friedman34866c72012-08-31 00:14:07 +00002192 Context.BuiltinFnTy,
Douglas Gregor6b3bcf22011-09-09 16:51:10 +00002193 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +00002194
Chris Lattnerdc046542009-05-08 06:58:22 +00002195 // Set the callee in the CallExpr.
Eli Friedman34866c72012-08-31 00:14:07 +00002196 // FIXME: This loses syntactic information.
2197 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2198 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2199 CK_BuiltinFnToFnPtr);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002200 TheCall->setCallee(PromotedCall.get());
Mike Stump11289f42009-09-09 15:08:12 +00002201
Chandler Carruthbc8cab12010-07-18 07:23:17 +00002202 // Change the result type of the call to match the original value type. This
2203 // is arbitrary, but the codegen for these builtins ins design to handle it
2204 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +00002205 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +00002206
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002207 return TheCallResult;
Chris Lattnerdc046542009-05-08 06:58:22 +00002208}
2209
Chris Lattner6436fb62009-02-18 06:01:06 +00002210/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +00002211/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +00002212/// Note: It might also make sense to do the UTF-16 conversion here (would
2213/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +00002214bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +00002215 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +00002216 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2217
Douglas Gregorfb65e592011-07-27 05:40:30 +00002218 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002219 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2220 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +00002221 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +00002222 }
Mike Stump11289f42009-09-09 15:08:12 +00002223
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002224 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002225 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002226 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002227 SmallVector<UTF16, 128> ToBuf(NumBytes);
Roman Divackye6377112012-09-06 15:59:27 +00002228 const UTF8 *FromPtr = (const UTF8 *)String.data();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +00002229 UTF16 *ToPtr = &ToBuf[0];
2230
2231 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2232 &ToPtr, ToPtr + NumBytes,
2233 strictConversion);
2234 // Check for conversion failure.
2235 if (Result != conversionOK)
2236 Diag(Arg->getLocStart(),
2237 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2238 }
Anders Carlssona3a9c432007-08-17 15:44:17 +00002239 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +00002240}
2241
Chris Lattnere202e6a2007-12-20 00:05:45 +00002242/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2243/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +00002244bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2245 Expr *Fn = TheCall->getCallee();
2246 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +00002247 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002248 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002249 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2250 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +00002251 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002252 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +00002253 return true;
2254 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002255
2256 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +00002257 return Diag(TheCall->getLocEnd(),
2258 diag::err_typecheck_call_too_few_args_at_least)
2259 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +00002260 }
2261
John McCall29ad95b2011-08-27 01:09:30 +00002262 // Type-check the first argument normally.
2263 if (checkBuiltinArgument(*this, TheCall, 0))
2264 return true;
2265
Chris Lattnere202e6a2007-12-20 00:05:45 +00002266 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +00002267 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +00002268 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +00002269 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +00002270 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +00002271 else if (FunctionDecl *FD = getCurFunctionDecl())
2272 isVariadic = FD->isVariadic();
2273 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002274 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +00002275
Chris Lattnere202e6a2007-12-20 00:05:45 +00002276 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002277 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2278 return true;
2279 }
Mike Stump11289f42009-09-09 15:08:12 +00002280
Chris Lattner43be2e62007-12-19 23:59:04 +00002281 // Verify that the second argument to the builtin is the last argument of the
2282 // current function or method.
2283 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +00002284 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00002285
Nico Weber9eea7642013-05-24 23:31:57 +00002286 // These are valid if SecondArgIsLastNamedArgument is false after the next
2287 // block.
2288 QualType Type;
2289 SourceLocation ParamLoc;
2290
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002291 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2292 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +00002293 // FIXME: This isn't correct for methods (results in bogus warning).
2294 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +00002295 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +00002296 if (CurBlock)
2297 LastArg = *(CurBlock->TheDecl->param_end()-1);
2298 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +00002299 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002300 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002301 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +00002302 SecondArgIsLastNamedArgument = PV == LastArg;
Nico Weber9eea7642013-05-24 23:31:57 +00002303
2304 Type = PV->getType();
2305 ParamLoc = PV->getLocation();
Chris Lattner43be2e62007-12-19 23:59:04 +00002306 }
2307 }
Mike Stump11289f42009-09-09 15:08:12 +00002308
Chris Lattner43be2e62007-12-19 23:59:04 +00002309 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +00002310 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00002311 diag::warn_second_parameter_of_va_start_not_last_named_argument);
Nico Weber9eea7642013-05-24 23:31:57 +00002312 else if (Type->isReferenceType()) {
2313 Diag(Arg->getLocStart(),
2314 diag::warn_va_start_of_reference_type_is_undefined);
2315 Diag(ParamLoc, diag::note_parameter_type) << Type;
2316 }
2317
Enea Zaffanellab1b1b8a2013-11-07 08:14:26 +00002318 TheCall->setType(Context.VoidTy);
Chris Lattner43be2e62007-12-19 23:59:04 +00002319 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00002320}
Chris Lattner43be2e62007-12-19 23:59:04 +00002321
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002322bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2323 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2324 // const char *named_addr);
2325
2326 Expr *Func = Call->getCallee();
2327
2328 if (Call->getNumArgs() < 3)
2329 return Diag(Call->getLocEnd(),
2330 diag::err_typecheck_call_too_few_args_at_least)
2331 << 0 /*function call*/ << 3 << Call->getNumArgs();
2332
2333 // Determine whether the current function is variadic or not.
2334 bool IsVariadic;
2335 if (BlockScopeInfo *CurBlock = getCurBlock())
2336 IsVariadic = CurBlock->TheDecl->isVariadic();
2337 else if (FunctionDecl *FD = getCurFunctionDecl())
2338 IsVariadic = FD->isVariadic();
2339 else if (ObjCMethodDecl *MD = getCurMethodDecl())
2340 IsVariadic = MD->isVariadic();
2341 else
2342 llvm_unreachable("unexpected statement type");
2343
2344 if (!IsVariadic) {
2345 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2346 return true;
2347 }
2348
2349 // Type-check the first argument normally.
2350 if (checkBuiltinArgument(*this, Call, 0))
2351 return true;
2352
Benjamin Kramere0ca6e12015-03-01 18:09:50 +00002353 const struct {
Saleem Abdulrasool202aac12014-07-22 02:01:04 +00002354 unsigned ArgNo;
2355 QualType Type;
2356 } ArgumentTypes[] = {
2357 { 1, Context.getPointerType(Context.CharTy.withConst()) },
2358 { 2, Context.getSizeType() },
2359 };
2360
2361 for (const auto &AT : ArgumentTypes) {
2362 const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2363 if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2364 continue;
2365 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2366 << Arg->getType() << AT.Type << 1 /* different class */
2367 << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2368 << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2369 }
2370
2371 return false;
2372}
2373
Chris Lattner2da14fb2007-12-20 00:26:33 +00002374/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2375/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00002376bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2377 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00002378 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002379 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00002380 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00002381 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002382 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002383 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00002384 << SourceRange(TheCall->getArg(2)->getLocStart(),
2385 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002386
John Wiegley01296292011-04-08 18:41:53 +00002387 ExprResult OrigArg0 = TheCall->getArg(0);
2388 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002389
Chris Lattner2da14fb2007-12-20 00:26:33 +00002390 // Do standard promotions between the two arguments, returning their common
2391 // type.
Chris Lattner08464942007-12-28 05:29:59 +00002392 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00002393 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2394 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00002395
2396 // Make sure any conversions are pushed back into the call; this is
2397 // type safe since unordered compare builtins are declared as "_Bool
2398 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00002399 TheCall->setArg(0, OrigArg0.get());
2400 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00002401
John Wiegley01296292011-04-08 18:41:53 +00002402 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00002403 return false;
2404
Chris Lattner2da14fb2007-12-20 00:26:33 +00002405 // If the common type isn't a real floating type, then the arguments were
2406 // invalid for this operation.
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002407 if (Res.isNull() || !Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00002408 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00002409 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00002410 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2411 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00002412
Chris Lattner2da14fb2007-12-20 00:26:33 +00002413 return false;
2414}
2415
Benjamin Kramer634fc102010-02-15 22:42:31 +00002416/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2417/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00002418/// to check everything. We expect the last argument to be a floating point
2419/// value.
2420bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2421 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00002422 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00002423 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00002424 if (TheCall->getNumArgs() > NumArgs)
2425 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002426 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002427 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00002428 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002429 (*(TheCall->arg_end()-1))->getLocEnd());
2430
Benjamin Kramer64aae502010-02-16 10:07:31 +00002431 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Eli Friedman7e4faac2009-08-31 20:06:00 +00002433 if (OrigArg->isTypeDependent())
2434 return false;
2435
Chris Lattner68784ef2010-05-06 05:50:07 +00002436 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00002437 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00002438 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00002439 diag::err_typecheck_call_invalid_unary_fp)
2440 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002441
Chris Lattner68784ef2010-05-06 05:50:07 +00002442 // If this is an implicit conversion from float -> double, remove it.
2443 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2444 Expr *CastArg = Cast->getSubExpr();
2445 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2446 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2447 "promotion from float to double is the only expected cast here");
Craig Topperc3ec1492014-05-26 06:22:03 +00002448 Cast->setSubExpr(nullptr);
Chris Lattner68784ef2010-05-06 05:50:07 +00002449 TheCall->setArg(NumArgs-1, CastArg);
Chris Lattner68784ef2010-05-06 05:50:07 +00002450 }
2451 }
2452
Eli Friedman7e4faac2009-08-31 20:06:00 +00002453 return false;
2454}
2455
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002456/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2457// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00002458ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00002459 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002460 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00002461 diag::err_typecheck_call_too_few_args_at_least)
Craig Topper304602a2013-07-28 21:50:10 +00002462 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2463 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002464
Nate Begemana0110022010-06-08 00:16:34 +00002465 // Determine which of the following types of shufflevector we're checking:
2466 // 1) unary, vector mask: (lhs, mask)
2467 // 2) binary, vector mask: (lhs, rhs, mask)
2468 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2469 QualType resType = TheCall->getArg(0)->getType();
2470 unsigned numElements = 0;
Craig Topper61d01cc2013-07-19 04:46:31 +00002471
Douglas Gregorc25f7662009-05-19 22:10:17 +00002472 if (!TheCall->getArg(0)->isTypeDependent() &&
2473 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00002474 QualType LHSType = TheCall->getArg(0)->getType();
2475 QualType RHSType = TheCall->getArg(1)->getType();
Craig Topper61d01cc2013-07-19 04:46:31 +00002476
Craig Topperbaca3892013-07-29 06:47:04 +00002477 if (!LHSType->isVectorType() || !RHSType->isVectorType())
2478 return ExprError(Diag(TheCall->getLocStart(),
2479 diag::err_shufflevector_non_vector)
2480 << SourceRange(TheCall->getArg(0)->getLocStart(),
2481 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002482
Nate Begemana0110022010-06-08 00:16:34 +00002483 numElements = LHSType->getAs<VectorType>()->getNumElements();
2484 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00002485
Nate Begemana0110022010-06-08 00:16:34 +00002486 // Check to see if we have a call with 2 vector arguments, the unary shuffle
2487 // with mask. If so, verify that RHS is an integer vector type with the
2488 // same number of elts as lhs.
2489 if (TheCall->getNumArgs() == 2) {
Sylvestre Ledru8e5d82e2013-07-06 08:00:09 +00002490 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00002491 RHSType->getAs<VectorType>()->getNumElements() != numElements)
Craig Topperbaca3892013-07-29 06:47:04 +00002492 return ExprError(Diag(TheCall->getLocStart(),
2493 diag::err_shufflevector_incompatible_vector)
2494 << SourceRange(TheCall->getArg(1)->getLocStart(),
2495 TheCall->getArg(1)->getLocEnd()));
Craig Topper61d01cc2013-07-19 04:46:31 +00002496 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Craig Topperbaca3892013-07-29 06:47:04 +00002497 return ExprError(Diag(TheCall->getLocStart(),
2498 diag::err_shufflevector_incompatible_vector)
2499 << SourceRange(TheCall->getArg(0)->getLocStart(),
2500 TheCall->getArg(1)->getLocEnd()));
Nate Begemana0110022010-06-08 00:16:34 +00002501 } else if (numElements != numResElements) {
2502 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00002503 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00002504 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00002505 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002506 }
2507
2508 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00002509 if (TheCall->getArg(i)->isTypeDependent() ||
2510 TheCall->getArg(i)->isValueDependent())
2511 continue;
2512
Nate Begemana0110022010-06-08 00:16:34 +00002513 llvm::APSInt Result(32);
2514 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2515 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002516 diag::err_shufflevector_nonconstant_argument)
2517 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002518
Craig Topper50ad5b72013-08-03 17:40:38 +00002519 // Allow -1 which will be translated to undef in the IR.
2520 if (Result.isSigned() && Result.isAllOnesValue())
2521 continue;
2522
Chris Lattner7ab824e2008-08-10 02:05:13 +00002523 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002524 return ExprError(Diag(TheCall->getLocStart(),
Craig Topper304602a2013-07-28 21:50:10 +00002525 diag::err_shufflevector_argument_too_large)
2526 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002527 }
2528
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002529 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002530
Chris Lattner7ab824e2008-08-10 02:05:13 +00002531 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002532 exprs.push_back(TheCall->getArg(i));
Craig Topperc3ec1492014-05-26 06:22:03 +00002533 TheCall->setArg(i, nullptr);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002534 }
2535
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002536 return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2537 TheCall->getCallee()->getLocStart(),
2538 TheCall->getRParenLoc());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00002539}
Chris Lattner43be2e62007-12-19 23:59:04 +00002540
Hal Finkelc4d7c822013-09-18 03:29:45 +00002541/// SemaConvertVectorExpr - Handle __builtin_convertvector
2542ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2543 SourceLocation BuiltinLoc,
2544 SourceLocation RParenLoc) {
2545 ExprValueKind VK = VK_RValue;
2546 ExprObjectKind OK = OK_Ordinary;
2547 QualType DstTy = TInfo->getType();
2548 QualType SrcTy = E->getType();
2549
2550 if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2551 return ExprError(Diag(BuiltinLoc,
2552 diag::err_convertvector_non_vector)
2553 << E->getSourceRange());
2554 if (!DstTy->isVectorType() && !DstTy->isDependentType())
2555 return ExprError(Diag(BuiltinLoc,
2556 diag::err_convertvector_non_vector_type));
2557
2558 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2559 unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2560 unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2561 if (SrcElts != DstElts)
2562 return ExprError(Diag(BuiltinLoc,
2563 diag::err_convertvector_incompatible_vector)
2564 << E->getSourceRange());
2565 }
2566
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002567 return new (Context)
2568 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
Hal Finkelc4d7c822013-09-18 03:29:45 +00002569}
2570
Daniel Dunbarb7257262008-07-21 22:59:13 +00002571/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2572// This is declared to take (const void*, ...) and can take two
2573// optional constant int args.
2574bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00002575 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002576
Chris Lattner3b054132008-11-19 05:08:23 +00002577 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00002578 return Diag(TheCall->getLocEnd(),
2579 diag::err_typecheck_call_too_many_args_at_most)
2580 << 0 /*function call*/ << 3 << NumArgs
2581 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00002582
2583 // Argument 0 is checked for us and the remaining arguments must be
2584 // constant integers.
Richard Sandiford28940af2014-04-16 08:47:51 +00002585 for (unsigned i = 1; i != NumArgs; ++i)
2586 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002587 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002588
Warren Hunt20e4a5d2014-02-21 23:08:53 +00002589 return false;
2590}
2591
Hal Finkelf0417332014-07-17 14:25:55 +00002592/// SemaBuiltinAssume - Handle __assume (MS Extension).
2593// __assume does not evaluate its arguments, and should warn if its argument
2594// has side effects.
2595bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2596 Expr *Arg = TheCall->getArg(0);
2597 if (Arg->isInstantiationDependent()) return false;
2598
2599 if (Arg->HasSideEffects(Context))
David Majnemer51236642015-02-26 00:57:33 +00002600 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
Hal Finkelbcc06082014-09-07 22:58:14 +00002601 << Arg->getSourceRange()
2602 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2603
2604 return false;
2605}
2606
2607/// Handle __builtin_assume_aligned. This is declared
2608/// as (const void*, size_t, ...) and can take one optional constant int arg.
2609bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2610 unsigned NumArgs = TheCall->getNumArgs();
2611
2612 if (NumArgs > 3)
2613 return Diag(TheCall->getLocEnd(),
2614 diag::err_typecheck_call_too_many_args_at_most)
2615 << 0 /*function call*/ << 3 << NumArgs
2616 << TheCall->getSourceRange();
2617
2618 // The alignment must be a constant integer.
2619 Expr *Arg = TheCall->getArg(1);
2620
2621 // We can't check the value of a dependent argument.
2622 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2623 llvm::APSInt Result;
2624 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2625 return true;
2626
2627 if (!Result.isPowerOf2())
2628 return Diag(TheCall->getLocStart(),
2629 diag::err_alignment_not_power_of_two)
2630 << Arg->getSourceRange();
2631 }
2632
2633 if (NumArgs > 2) {
2634 ExprResult Arg(TheCall->getArg(2));
2635 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2636 Context.getSizeType(), false);
2637 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2638 if (Arg.isInvalid()) return true;
2639 TheCall->setArg(2, Arg.get());
2640 }
Hal Finkelf0417332014-07-17 14:25:55 +00002641
2642 return false;
2643}
2644
Eric Christopher8d0c6212010-04-17 02:26:23 +00002645/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2646/// TheCall is a constant expression.
2647bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2648 llvm::APSInt &Result) {
2649 Expr *Arg = TheCall->getArg(ArgNum);
2650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2651 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2652
2653 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2654
2655 if (!Arg->isIntegerConstantExpr(Result, Context))
2656 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00002657 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00002658
Chris Lattnerd545ad12009-09-23 06:06:36 +00002659 return false;
2660}
2661
Richard Sandiford28940af2014-04-16 08:47:51 +00002662/// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2663/// TheCall is a constant expression in the range [Low, High].
2664bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2665 int Low, int High) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00002666 llvm::APSInt Result;
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002667
2668 // We can't check the value of a dependent argument.
Richard Sandiford28940af2014-04-16 08:47:51 +00002669 Expr *Arg = TheCall->getArg(ArgNum);
2670 if (Arg->isTypeDependent() || Arg->isValueDependent())
Douglas Gregor98c3cfc2012-06-29 01:05:22 +00002671 return false;
2672
Eric Christopher8d0c6212010-04-17 02:26:23 +00002673 // Check constant-ness first.
Richard Sandiford28940af2014-04-16 08:47:51 +00002674 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
Eric Christopher8d0c6212010-04-17 02:26:23 +00002675 return true;
2676
Richard Sandiford28940af2014-04-16 08:47:51 +00002677 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
Chris Lattner3b054132008-11-19 05:08:23 +00002678 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Richard Sandiford28940af2014-04-16 08:47:51 +00002679 << Low << High << Arg->getSourceRange();
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00002680
2681 return false;
2682}
2683
Luke Cheeseman59b2d832015-06-15 17:51:01 +00002684/// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
2685/// TheCall is an ARM/AArch64 special register string literal.
2686bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
2687 int ArgNum, unsigned ExpectedFieldNum,
2688 bool AllowName) {
2689 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2690 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2691 BuiltinID == ARM::BI__builtin_arm_rsr ||
2692 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2693 BuiltinID == ARM::BI__builtin_arm_wsr ||
2694 BuiltinID == ARM::BI__builtin_arm_wsrp;
2695 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2696 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2697 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2698 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2699 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2700 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2701 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
2702
2703 // We can't check the value of a dependent argument.
2704 Expr *Arg = TheCall->getArg(ArgNum);
2705 if (Arg->isTypeDependent() || Arg->isValueDependent())
2706 return false;
2707
2708 // Check if the argument is a string literal.
2709 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
2710 return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
2711 << Arg->getSourceRange();
2712
2713 // Check the type of special register given.
2714 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
2715 SmallVector<StringRef, 6> Fields;
2716 Reg.split(Fields, ":");
2717
2718 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2719 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2720 << Arg->getSourceRange();
2721
2722 // If the string is the name of a register then we cannot check that it is
2723 // valid here but if the string is of one the forms described in ACLE then we
2724 // can check that the supplied fields are integers and within the valid
2725 // ranges.
2726 if (Fields.size() > 1) {
2727 bool FiveFields = Fields.size() == 5;
2728
2729 bool ValidString = true;
2730 if (IsARMBuiltin) {
2731 ValidString &= Fields[0].startswith_lower("cp") ||
2732 Fields[0].startswith_lower("p");
2733 if (ValidString)
2734 Fields[0] =
2735 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
2736
2737 ValidString &= Fields[2].startswith_lower("c");
2738 if (ValidString)
2739 Fields[2] = Fields[2].drop_front(1);
2740
2741 if (FiveFields) {
2742 ValidString &= Fields[3].startswith_lower("c");
2743 if (ValidString)
2744 Fields[3] = Fields[3].drop_front(1);
2745 }
2746 }
2747
2748 SmallVector<int, 5> Ranges;
2749 if (FiveFields)
2750 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2751 else
2752 Ranges.append({15, 7, 15});
2753
2754 for (unsigned i=0; i<Fields.size(); ++i) {
2755 int IntField;
2756 ValidString &= !Fields[i].getAsInteger(10, IntField);
2757 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2758 }
2759
2760 if (!ValidString)
2761 return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
2762 << Arg->getSourceRange();
2763
2764 } else if (IsAArch64Builtin && Fields.size() == 1) {
2765 // If the register name is one of those that appear in the condition below
2766 // and the special register builtin being used is one of the write builtins,
2767 // then we require that the argument provided for writing to the register
2768 // is an integer constant expression. This is because it will be lowered to
2769 // an MSR (immediate) instruction, so we need to know the immediate at
2770 // compile time.
2771 if (TheCall->getNumArgs() != 2)
2772 return false;
2773
2774 std::string RegLower = Reg.lower();
2775 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
2776 RegLower != "pan" && RegLower != "uao")
2777 return false;
2778
2779 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2780 }
2781
2782 return false;
2783}
2784
Eli Friedmanc97d0142009-05-03 06:04:26 +00002785/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002786/// This checks that the target supports __builtin_longjmp and
2787/// that val is a constant 1.
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002788bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002789 if (!Context.getTargetInfo().hasSjLjLowering())
2790 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
2791 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2792
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002793 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00002794 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00002795
Eric Christopher8d0c6212010-04-17 02:26:23 +00002796 // TODO: This is less than ideal. Overload this to take a value.
2797 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2798 return true;
2799
2800 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00002801 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2802 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2803
2804 return false;
2805}
2806
Joerg Sonnenberger27173282015-03-11 23:46:32 +00002807
2808/// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
2809/// This checks that the target supports __builtin_setjmp.
2810bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
2811 if (!Context.getTargetInfo().hasSjLjLowering())
2812 return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
2813 << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
2814 return false;
2815}
2816
Richard Smithd7293d72013-08-05 18:49:43 +00002817namespace {
2818enum StringLiteralCheckType {
2819 SLCT_NotALiteral,
2820 SLCT_UncheckedLiteral,
2821 SLCT_CheckedLiteral
2822};
2823}
2824
Richard Smith55ce3522012-06-25 20:30:08 +00002825// Determine if an expression is a string literal or constant string.
2826// If this function returns false on the arguments to a function expecting a
2827// format string, we will usually need to emit a warning.
2828// True string literals are then checked by CheckFormatString.
Richard Smithd7293d72013-08-05 18:49:43 +00002829static StringLiteralCheckType
2830checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2831 bool HasVAListArg, unsigned format_idx,
2832 unsigned firstDataArg, Sema::FormatStringType Type,
2833 Sema::VariadicCallType CallType, bool InFunctionCall,
2834 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek808829352010-09-09 03:51:39 +00002835 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00002836 if (E->isTypeDependent() || E->isValueDependent())
Richard Smith55ce3522012-06-25 20:30:08 +00002837 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002838
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00002839 E = E->IgnoreParenCasts();
Peter Collingbourne91147592011-04-15 00:35:48 +00002840
Richard Smithd7293d72013-08-05 18:49:43 +00002841 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
David Blaikie59fe3f82012-02-10 21:07:25 +00002842 // Technically -Wformat-nonliteral does not warn about this case.
2843 // The behavior of printf and friends in this case is implementation
2844 // dependent. Ideally if the format string cannot be null then
2845 // it should have a 'nonnull' attribute in the function prototype.
Richard Smithd7293d72013-08-05 18:49:43 +00002846 return SLCT_UncheckedLiteral;
David Blaikie59fe3f82012-02-10 21:07:25 +00002847
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002848 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00002849 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002850 case Stmt::ConditionalOperatorClass: {
Richard Smith55ce3522012-06-25 20:30:08 +00002851 // The expression is a literal if both sub-expressions were, and it was
2852 // completely checked only if both sub-expressions were checked.
2853 const AbstractConditionalOperator *C =
2854 cast<AbstractConditionalOperator>(E);
2855 StringLiteralCheckType Left =
Richard Smithd7293d72013-08-05 18:49:43 +00002856 checkFormatStringExpr(S, C->getTrueExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002857 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002858 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002859 if (Left == SLCT_NotALiteral)
2860 return SLCT_NotALiteral;
2861 StringLiteralCheckType Right =
Richard Smithd7293d72013-08-05 18:49:43 +00002862 checkFormatStringExpr(S, C->getFalseExpr(), Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002863 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002864 Type, CallType, InFunctionCall, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002865 return Left < Right ? Left : Right;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002866 }
2867
2868 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00002869 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2870 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002871 }
2872
John McCallc07a0c72011-02-17 10:25:35 +00002873 case Stmt::OpaqueValueExprClass:
2874 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2875 E = src;
2876 goto tryAgain;
2877 }
Richard Smith55ce3522012-06-25 20:30:08 +00002878 return SLCT_NotALiteral;
John McCallc07a0c72011-02-17 10:25:35 +00002879
Ted Kremeneka8890832011-02-24 23:03:04 +00002880 case Stmt::PredefinedExprClass:
2881 // While __func__, etc., are technically not string literals, they
2882 // cannot contain format specifiers and thus are not a security
2883 // liability.
Richard Smith55ce3522012-06-25 20:30:08 +00002884 return SLCT_UncheckedLiteral;
Ted Kremeneka8890832011-02-24 23:03:04 +00002885
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002886 case Stmt::DeclRefExprClass: {
2887 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002888
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002889 // As an exception, do not flag errors for variables binding to
2890 // const string literals.
2891 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2892 bool isConstant = false;
2893 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002894
Richard Smithd7293d72013-08-05 18:49:43 +00002895 if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2896 isConstant = AT->getElementType().isConstant(S.Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00002897 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Richard Smithd7293d72013-08-05 18:49:43 +00002898 isConstant = T.isConstant(S.Context) &&
2899 PT->getPointeeType().isConstant(S.Context);
Jean-Daniel Dupasd5f7ef42012-01-25 10:35:33 +00002900 } else if (T->isObjCObjectPointerType()) {
2901 // In ObjC, there is usually no "const ObjectPointer" type,
2902 // so don't check if the pointee type is constant.
Richard Smithd7293d72013-08-05 18:49:43 +00002903 isConstant = T.isConstant(S.Context);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002904 }
Mike Stump11289f42009-09-09 15:08:12 +00002905
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002906 if (isConstant) {
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002907 if (const Expr *Init = VD->getAnyInitializer()) {
2908 // Look through initializers like const char c[] = { "foo" }
2909 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2910 if (InitList->isStringLiteralInit())
2911 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2912 }
Richard Smithd7293d72013-08-05 18:49:43 +00002913 return checkFormatStringExpr(S, Init, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002914 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002915 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002916 /*InFunctionCall*/false, CheckedVarArgs);
Matt Beaumont-Gayd8735082012-05-11 22:10:59 +00002917 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002918 }
Mike Stump11289f42009-09-09 15:08:12 +00002919
Anders Carlssonb012ca92009-06-28 19:55:58 +00002920 // For vprintf* functions (i.e., HasVAListArg==true), we add a
2921 // special check to see if the format string is a function parameter
2922 // of the function calling the printf function. If the function
2923 // has an attribute indicating it is a printf-like function, then we
2924 // should suppress warnings concerning non-literals being used in a call
2925 // to a vprintf function. For example:
2926 //
2927 // void
2928 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2929 // va_list ap;
2930 // va_start(ap, fmt);
2931 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
2932 // ...
Richard Smithd7293d72013-08-05 18:49:43 +00002933 // }
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002934 if (HasVAListArg) {
2935 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2936 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2937 int PVIndex = PV->getFunctionScopeIndex() + 1;
Aaron Ballmanbe22bcb2014-03-10 17:08:28 +00002938 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002939 // adjust for implicit parameter
2940 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2941 if (MD->isInstance())
2942 ++PVIndex;
2943 // We also check if the formats are compatible.
2944 // We can't pass a 'scanf' string to a 'printf' function.
2945 if (PVIndex == PVFormat->getFormatIdx() &&
Richard Smithd7293d72013-08-05 18:49:43 +00002946 Type == S.GetFormatStringType(PVFormat))
Richard Smith55ce3522012-06-25 20:30:08 +00002947 return SLCT_UncheckedLiteral;
Jean-Daniel Dupas58dab682012-02-21 20:00:53 +00002948 }
2949 }
2950 }
2951 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002952 }
Mike Stump11289f42009-09-09 15:08:12 +00002953
Richard Smith55ce3522012-06-25 20:30:08 +00002954 return SLCT_NotALiteral;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002955 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002956
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002957 case Stmt::CallExprClass:
2958 case Stmt::CXXMemberCallExprClass: {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002959 const CallExpr *CE = cast<CallExpr>(E);
Jean-Daniel Dupas6255bd12012-02-07 19:01:42 +00002960 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2961 if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2962 unsigned ArgIndex = FA->getFormatIdx();
2963 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2964 if (MD->isInstance())
2965 --ArgIndex;
2966 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00002967
Richard Smithd7293d72013-08-05 18:49:43 +00002968 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002969 HasVAListArg, format_idx, firstDataArg,
Richard Smithd7293d72013-08-05 18:49:43 +00002970 Type, CallType, InFunctionCall,
2971 CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002972 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2973 unsigned BuiltinID = FD->getBuiltinID();
2974 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2975 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2976 const Expr *Arg = CE->getArg(0);
Richard Smithd7293d72013-08-05 18:49:43 +00002977 return checkFormatStringExpr(S, Arg, Args,
Richard Smith55ce3522012-06-25 20:30:08 +00002978 HasVAListArg, format_idx,
Jordan Rose3e0ec582012-07-19 18:10:23 +00002979 firstDataArg, Type, CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00002980 InFunctionCall, CheckedVarArgs);
Jordan Rose97c6f2b2012-06-04 23:52:23 +00002981 }
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002982 }
2983 }
Mike Stump11289f42009-09-09 15:08:12 +00002984
Richard Smith55ce3522012-06-25 20:30:08 +00002985 return SLCT_NotALiteral;
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00002986 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002987 case Stmt::ObjCStringLiteralClass:
2988 case Stmt::StringLiteralClass: {
Craig Topperc3ec1492014-05-26 06:22:03 +00002989 const StringLiteral *StrE = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002990
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002991 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002992 StrE = ObjCFExpr->getString();
2993 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00002994 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002995
Ted Kremenek6dfeb552009-01-12 23:09:09 +00002996 if (StrE) {
Richard Smithd7293d72013-08-05 18:49:43 +00002997 S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2998 Type, InFunctionCall, CallType, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00002999 return SLCT_CheckedLiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003000 }
Mike Stump11289f42009-09-09 15:08:12 +00003001
Richard Smith55ce3522012-06-25 20:30:08 +00003002 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003003 }
Mike Stump11289f42009-09-09 15:08:12 +00003004
Ted Kremenekdfd72c22009-03-20 21:35:28 +00003005 default:
Richard Smith55ce3522012-06-25 20:30:08 +00003006 return SLCT_NotALiteral;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003007 }
3008}
3009
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003010Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
Aaron Ballmanf58070b2013-09-03 21:02:22 +00003011 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003012 .Case("scanf", FST_Scanf)
3013 .Cases("printf", "printf0", FST_Printf)
3014 .Cases("NSString", "CFString", FST_NSString)
3015 .Case("strftime", FST_Strftime)
3016 .Case("strfmon", FST_Strfmon)
3017 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003018 .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00003019 .Case("os_trace", FST_OSTrace)
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003020 .Default(FST_Unknown);
3021}
3022
Jordan Rose3e0ec582012-07-19 18:10:23 +00003023/// CheckFormatArguments - Check calls to printf and scanf (and similar
Ted Kremenek02087932010-07-16 02:11:22 +00003024/// functions) for correct use of format strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003025/// Returns true if a format string has been fully checked.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003026bool Sema::CheckFormatArguments(const FormatAttr *Format,
3027 ArrayRef<const Expr *> Args,
3028 bool IsCXXMember,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003029 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003030 SourceLocation Loc, SourceRange Range,
3031 llvm::SmallBitVector &CheckedVarArgs) {
Richard Smith55ce3522012-06-25 20:30:08 +00003032 FormatStringInfo FSI;
3033 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003034 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
Richard Smith55ce3522012-06-25 20:30:08 +00003035 FSI.FirstDataArg, GetFormatStringType(Format),
Richard Smithd7293d72013-08-05 18:49:43 +00003036 CallType, Loc, Range, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003037 return false;
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003038}
Sebastian Redl6eedcc12009-11-17 18:02:24 +00003039
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003040bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00003041 bool HasVAListArg, unsigned format_idx,
3042 unsigned firstDataArg, FormatStringType Type,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003043 VariadicCallType CallType,
Richard Smithd7293d72013-08-05 18:49:43 +00003044 SourceLocation Loc, SourceRange Range,
3045 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00003046 // CHECK: printf/scanf-like function is called with no format string.
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003047 if (format_idx >= Args.size()) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003048 Diag(Loc, diag::warn_missing_format_string) << Range;
Richard Smith55ce3522012-06-25 20:30:08 +00003049 return false;
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003050 }
Mike Stump11289f42009-09-09 15:08:12 +00003051
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003052 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00003053
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003054 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00003055 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003056 // Dynamically generated format strings are difficult to
3057 // automatically vet at compile time. Requiring that format strings
3058 // are string literals: (1) permits the checking of format strings by
3059 // the compiler and thereby (2) can practically remove the source of
3060 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00003061
Mike Stump11289f42009-09-09 15:08:12 +00003062 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00003063 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00003064 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00003065 // the same format string checking logic for both ObjC and C strings.
Richard Smith55ce3522012-06-25 20:30:08 +00003066 StringLiteralCheckType CT =
Richard Smithd7293d72013-08-05 18:49:43 +00003067 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3068 format_idx, firstDataArg, Type, CallType,
3069 /*IsFunctionCall*/true, CheckedVarArgs);
Richard Smith55ce3522012-06-25 20:30:08 +00003070 if (CT != SLCT_NotALiteral)
3071 // Literal format string found, check done!
3072 return CT == SLCT_CheckedLiteral;
Ted Kremenek34f664d2008-06-16 18:00:42 +00003073
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003074 // Strftime is particular as it always uses a single 'time' argument,
3075 // so it is safe to pass a non-literal string.
3076 if (Type == FST_Strftime)
Richard Smith55ce3522012-06-25 20:30:08 +00003077 return false;
Jean-Daniel Dupas6567f482012-02-07 23:10:53 +00003078
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003079 // Do not emit diag when the string param is a macro expansion and the
3080 // format is either NSString or CFString. This is a hack to prevent
3081 // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3082 // which are usually used in place of NS and CF string literals.
Jean-Daniel Dupas2b7da832012-05-04 21:08:08 +00003083 if (Type == FST_NSString &&
3084 SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
Richard Smith55ce3522012-06-25 20:30:08 +00003085 return false;
Jean-Daniel Dupas537aa1a2012-01-30 19:46:17 +00003086
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003087 // If there are no arguments specified, warn with -Wformat-security, otherwise
3088 // warn only with -Wformat-nonliteral.
Eli Friedman0e5d6772013-06-18 18:10:01 +00003089 if (Args.size() == firstDataArg)
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003090 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003091 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003092 << OrigFormatExpr->getSourceRange();
3093 else
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003094 Diag(Args[format_idx]->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00003095 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00003096 << OrigFormatExpr->getSourceRange();
Richard Smith55ce3522012-06-25 20:30:08 +00003097 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00003098}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00003099
Ted Kremenekab278de2010-01-28 23:39:18 +00003100namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00003101class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3102protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00003103 Sema &S;
3104 const StringLiteral *FExpr;
3105 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003106 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00003107 const unsigned NumDataArgs;
Ted Kremenekab278de2010-01-28 23:39:18 +00003108 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00003109 const bool HasVAListArg;
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003110 ArrayRef<const Expr *> Args;
Ted Kremenek5739de72010-01-29 01:06:55 +00003111 unsigned FormatIdx;
Richard Smithd7293d72013-08-05 18:49:43 +00003112 llvm::SmallBitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00003113 bool usesPositionalArgs;
3114 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003115 bool inFunctionCall;
Jordan Rose3e0ec582012-07-19 18:10:23 +00003116 Sema::VariadicCallType CallType;
Richard Smithd7293d72013-08-05 18:49:43 +00003117 llvm::SmallBitVector &CheckedVarArgs;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003118public:
Ted Kremenek02087932010-07-16 02:11:22 +00003119 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00003120 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003121 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003122 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003123 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003124 Sema::VariadicCallType callType,
3125 llvm::SmallBitVector &CheckedVarArgs)
Ted Kremenekab278de2010-01-28 23:39:18 +00003126 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003127 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3128 Beg(beg), HasVAListArg(hasVAListArg),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003129 Args(Args), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00003130 usesPositionalArgs(false), atFirstArg(true),
Richard Smithd7293d72013-08-05 18:49:43 +00003131 inFunctionCall(inFunctionCall), CallType(callType),
3132 CheckedVarArgs(CheckedVarArgs) {
3133 CoveredArgs.resize(numDataArgs);
3134 CoveredArgs.reset();
3135 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003136
Ted Kremenek019d2242010-01-29 01:50:07 +00003137 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003138
Ted Kremenek02087932010-07-16 02:11:22 +00003139 void HandleIncompleteSpecifier(const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003140 unsigned specifierLen) override;
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003141
Jordan Rose92303592012-09-08 04:00:03 +00003142 void HandleInvalidLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003143 const analyze_format_string::FormatSpecifier &FS,
3144 const analyze_format_string::ConversionSpecifier &CS,
3145 const char *startSpecifier, unsigned specifierLen,
3146 unsigned DiagID);
Jordan Rose92303592012-09-08 04:00:03 +00003147
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003148 void HandleNonStandardLengthModifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003149 const analyze_format_string::FormatSpecifier &FS,
3150 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003151
3152 void HandleNonStandardConversionSpecifier(
Craig Toppere14c0f82014-03-12 04:55:44 +00003153 const analyze_format_string::ConversionSpecifier &CS,
3154 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003155
Craig Toppere14c0f82014-03-12 04:55:44 +00003156 void HandlePosition(const char *startPos, unsigned posLen) override;
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003157
Craig Toppere14c0f82014-03-12 04:55:44 +00003158 void HandleInvalidPosition(const char *startSpecifier,
3159 unsigned specifierLen,
3160 analyze_format_string::PositionContext p) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003161
Craig Toppere14c0f82014-03-12 04:55:44 +00003162 void HandleZeroPosition(const char *startPos, unsigned posLen) override;
Ted Kremenekd1668192010-02-27 01:41:03 +00003163
Craig Toppere14c0f82014-03-12 04:55:44 +00003164 void HandleNullChar(const char *nullCharacter) override;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003165
Richard Trieu03cf7b72011-10-28 00:41:25 +00003166 template <typename Range>
3167 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3168 const Expr *ArgumentExpr,
3169 PartialDiagnostic PDiag,
3170 SourceLocation StringLoc,
3171 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003172 ArrayRef<FixItHint> Fixit = None);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003173
Ted Kremenek02087932010-07-16 02:11:22 +00003174protected:
Ted Kremenekce815422010-07-19 21:25:57 +00003175 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3176 const char *startSpec,
3177 unsigned specifierLen,
3178 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003179
3180 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3181 const char *startSpec,
3182 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00003183
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003184 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00003185 CharSourceRange getSpecifierRange(const char *startSpecifier,
3186 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00003187 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003188
Ted Kremenek5739de72010-01-29 01:06:55 +00003189 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003190
3191 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3192 const analyze_format_string::ConversionSpecifier &CS,
3193 const char *startSpecifier, unsigned specifierLen,
3194 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00003195
3196 template <typename Range>
3197 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3198 bool IsStringLocation, Range StringRange,
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00003199 ArrayRef<FixItHint> Fixit = None);
Ted Kremenekab278de2010-01-28 23:39:18 +00003200};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003201}
Ted Kremenekab278de2010-01-28 23:39:18 +00003202
Ted Kremenek02087932010-07-16 02:11:22 +00003203SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00003204 return OrigFormatExpr->getSourceRange();
3205}
3206
Ted Kremenek02087932010-07-16 02:11:22 +00003207CharSourceRange CheckFormatHandler::
3208getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00003209 SourceLocation Start = getLocationOfByte(startSpecifier);
3210 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
3211
3212 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00003213 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00003214
3215 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003216}
3217
Ted Kremenek02087932010-07-16 02:11:22 +00003218SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003219 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00003220}
3221
Ted Kremenek02087932010-07-16 02:11:22 +00003222void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3223 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00003224 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3225 getLocationOfByte(startSpecifier),
3226 /*IsStringLocation*/true,
3227 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00003228}
3229
Jordan Rose92303592012-09-08 04:00:03 +00003230void CheckFormatHandler::HandleInvalidLengthModifier(
3231 const analyze_format_string::FormatSpecifier &FS,
3232 const analyze_format_string::ConversionSpecifier &CS,
Jordan Rose2f9cc042012-09-08 04:00:12 +00003233 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
Jordan Rose92303592012-09-08 04:00:03 +00003234 using namespace analyze_format_string;
3235
3236 const LengthModifier &LM = FS.getLengthModifier();
3237 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3238
3239 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003240 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose92303592012-09-08 04:00:03 +00003241 if (FixedLM) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003242 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003243 getLocationOfByte(LM.getStart()),
3244 /*IsStringLocation*/true,
3245 getSpecifierRange(startSpecifier, specifierLen));
3246
3247 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3248 << FixedLM->toString()
3249 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3250
3251 } else {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003252 FixItHint Hint;
3253 if (DiagID == diag::warn_format_nonsensical_length)
3254 Hint = FixItHint::CreateRemoval(LMRange);
3255
3256 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
Jordan Rose92303592012-09-08 04:00:03 +00003257 getLocationOfByte(LM.getStart()),
3258 /*IsStringLocation*/true,
3259 getSpecifierRange(startSpecifier, specifierLen),
Jordan Rose2f9cc042012-09-08 04:00:12 +00003260 Hint);
Jordan Rose92303592012-09-08 04:00:03 +00003261 }
3262}
3263
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003264void CheckFormatHandler::HandleNonStandardLengthModifier(
Jordan Rose2f9cc042012-09-08 04:00:12 +00003265 const analyze_format_string::FormatSpecifier &FS,
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003266 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose2f9cc042012-09-08 04:00:12 +00003267 using namespace analyze_format_string;
3268
3269 const LengthModifier &LM = FS.getLengthModifier();
3270 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3271
3272 // See if we know how to fix this length modifier.
David Blaikie05785d12013-02-20 22:23:23 +00003273 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
Jordan Rose2f9cc042012-09-08 04:00:12 +00003274 if (FixedLM) {
3275 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3276 << LM.toString() << 0,
3277 getLocationOfByte(LM.getStart()),
3278 /*IsStringLocation*/true,
3279 getSpecifierRange(startSpecifier, specifierLen));
3280
3281 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3282 << FixedLM->toString()
3283 << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3284
3285 } else {
3286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3287 << LM.toString() << 0,
3288 getLocationOfByte(LM.getStart()),
3289 /*IsStringLocation*/true,
3290 getSpecifierRange(startSpecifier, specifierLen));
3291 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003292}
3293
3294void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3295 const analyze_format_string::ConversionSpecifier &CS,
3296 const char *startSpecifier, unsigned specifierLen) {
Jordan Rose4c266aa2012-09-13 02:11:15 +00003297 using namespace analyze_format_string;
3298
3299 // See if we know how to fix this conversion specifier.
David Blaikie05785d12013-02-20 22:23:23 +00003300 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
Jordan Rose4c266aa2012-09-13 02:11:15 +00003301 if (FixedCS) {
3302 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3303 << CS.toString() << /*conversion specifier*/1,
3304 getLocationOfByte(CS.getStart()),
3305 /*IsStringLocation*/true,
3306 getSpecifierRange(startSpecifier, specifierLen));
3307
3308 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3309 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3310 << FixedCS->toString()
3311 << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3312 } else {
3313 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3314 << CS.toString() << /*conversion specifier*/1,
3315 getLocationOfByte(CS.getStart()),
3316 /*IsStringLocation*/true,
3317 getSpecifierRange(startSpecifier, specifierLen));
3318 }
Hans Wennborgc9dd9462012-02-22 10:17:01 +00003319}
3320
Hans Wennborgaa8c61c2012-03-09 10:10:54 +00003321void CheckFormatHandler::HandlePosition(const char *startPos,
3322 unsigned posLen) {
3323 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3324 getLocationOfByte(startPos),
3325 /*IsStringLocation*/true,
3326 getSpecifierRange(startPos, posLen));
3327}
3328
Ted Kremenekd1668192010-02-27 01:41:03 +00003329void
Ted Kremenek02087932010-07-16 02:11:22 +00003330CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3331 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003332 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3333 << (unsigned) p,
3334 getLocationOfByte(startPos), /*IsStringLocation*/true,
3335 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003336}
3337
Ted Kremenek02087932010-07-16 02:11:22 +00003338void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00003339 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003340 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3341 getLocationOfByte(startPos),
3342 /*IsStringLocation*/true,
3343 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00003344}
3345
Ted Kremenek02087932010-07-16 02:11:22 +00003346void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003347 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003348 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003349 EmitFormatDiagnostic(
3350 S.PDiag(diag::warn_printf_format_string_contains_null_char),
3351 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3352 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00003353 }
Ted Kremenek02087932010-07-16 02:11:22 +00003354}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003355
Jordan Rose58bbe422012-07-19 18:10:08 +00003356// Note that this may return NULL if there was an error parsing or building
3357// one of the argument expressions.
Ted Kremenek02087932010-07-16 02:11:22 +00003358const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003359 return Args[FirstDataArg + i];
Ted Kremenek02087932010-07-16 02:11:22 +00003360}
3361
3362void CheckFormatHandler::DoneProcessing() {
3363 // Does the number of data arguments exceed the number of
3364 // format conversions in the format string?
3365 if (!HasVAListArg) {
3366 // Find any arguments that weren't covered.
3367 CoveredArgs.flip();
3368 signed notCoveredArg = CoveredArgs.find_first();
3369 if (notCoveredArg >= 0) {
3370 assert((unsigned)notCoveredArg < NumDataArgs);
Jordan Rose58bbe422012-07-19 18:10:08 +00003371 if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3372 SourceLocation Loc = E->getLocStart();
3373 if (!S.getSourceManager().isInSystemMacro(Loc)) {
3374 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3375 Loc, /*IsStringLocation*/false,
3376 getFormatStringRange());
3377 }
Bob Wilson23cd4342012-05-03 19:47:19 +00003378 }
Ted Kremenek02087932010-07-16 02:11:22 +00003379 }
3380 }
3381}
3382
Ted Kremenekce815422010-07-19 21:25:57 +00003383bool
3384CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3385 SourceLocation Loc,
3386 const char *startSpec,
3387 unsigned specifierLen,
3388 const char *csStart,
3389 unsigned csLen) {
3390
3391 bool keepGoing = true;
3392 if (argIndex < NumDataArgs) {
3393 // Consider the argument coverered, even though the specifier doesn't
3394 // make sense.
3395 CoveredArgs.set(argIndex);
3396 }
3397 else {
3398 // If argIndex exceeds the number of data arguments we
3399 // don't issue a warning because that is just a cascade of warnings (and
3400 // they may have intended '%%' anyway). We don't want to continue processing
3401 // the format string after this point, however, as we will like just get
3402 // gibberish when trying to match arguments.
3403 keepGoing = false;
3404 }
3405
Richard Trieu03cf7b72011-10-28 00:41:25 +00003406 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3407 << StringRef(csStart, csLen),
3408 Loc, /*IsStringLocation*/true,
3409 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00003410
3411 return keepGoing;
3412}
3413
Richard Trieu03cf7b72011-10-28 00:41:25 +00003414void
3415CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3416 const char *startSpec,
3417 unsigned specifierLen) {
3418 EmitFormatDiagnostic(
3419 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3420 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3421}
3422
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003423bool
3424CheckFormatHandler::CheckNumArgs(
3425 const analyze_format_string::FormatSpecifier &FS,
3426 const analyze_format_string::ConversionSpecifier &CS,
3427 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3428
3429 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003430 PartialDiagnostic PDiag = FS.usesPositionalArg()
3431 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3432 << (argIndex+1) << NumDataArgs)
3433 : S.PDiag(diag::warn_printf_insufficient_data_args);
3434 EmitFormatDiagnostic(
3435 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3436 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003437 return false;
3438 }
3439 return true;
3440}
3441
Richard Trieu03cf7b72011-10-28 00:41:25 +00003442template<typename Range>
3443void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3444 SourceLocation Loc,
3445 bool IsStringLocation,
3446 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003447 ArrayRef<FixItHint> FixIt) {
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00003448 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
Richard Trieu03cf7b72011-10-28 00:41:25 +00003449 Loc, IsStringLocation, StringRange, FixIt);
3450}
3451
3452/// \brief If the format string is not within the funcion call, emit a note
3453/// so that the function call and string are in diagnostic messages.
3454///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003455/// \param InFunctionCall if true, the format string is within the function
Richard Trieu03cf7b72011-10-28 00:41:25 +00003456/// call and only one diagnostic message will be produced. Otherwise, an
3457/// extra note will be emitted pointing to location of the format string.
3458///
3459/// \param ArgumentExpr the expression that is passed as the format string
3460/// argument in the function call. Used for getting locations when two
3461/// diagnostics are emitted.
3462///
3463/// \param PDiag the callee should already have provided any strings for the
3464/// diagnostic message. This function only adds locations and fixits
3465/// to diagnostics.
3466///
3467/// \param Loc primary location for diagnostic. If two diagnostics are
3468/// required, one will be at Loc and a new SourceLocation will be created for
3469/// the other one.
3470///
3471/// \param IsStringLocation if true, Loc points to the format string should be
3472/// used for the note. Otherwise, Loc points to the argument list and will
3473/// be used with PDiag.
3474///
3475/// \param StringRange some or all of the string to highlight. This is
3476/// templated so it can accept either a CharSourceRange or a SourceRange.
3477///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00003478/// \param FixIt optional fix it hint for the format string.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003479template<typename Range>
3480void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3481 const Expr *ArgumentExpr,
3482 PartialDiagnostic PDiag,
3483 SourceLocation Loc,
3484 bool IsStringLocation,
3485 Range StringRange,
Jordan Roseaee34382012-09-05 22:56:26 +00003486 ArrayRef<FixItHint> FixIt) {
3487 if (InFunctionCall) {
3488 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3489 D << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003490 D << FixIt;
Jordan Roseaee34382012-09-05 22:56:26 +00003491 } else {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003492 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3493 << ArgumentExpr->getSourceRange();
Jordan Roseaee34382012-09-05 22:56:26 +00003494
3495 const Sema::SemaDiagnosticBuilder &Note =
3496 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3497 diag::note_format_string_defined);
3498
3499 Note << StringRange;
Alexander Kornienkoa9b01eb2015-02-25 14:40:56 +00003500 Note << FixIt;
Richard Trieu03cf7b72011-10-28 00:41:25 +00003501 }
3502}
3503
Ted Kremenek02087932010-07-16 02:11:22 +00003504//===--- CHECK: Printf format string checking ------------------------------===//
3505
3506namespace {
3507class CheckPrintfHandler : public CheckFormatHandler {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003508 bool ObjCContext;
Ted Kremenek02087932010-07-16 02:11:22 +00003509public:
3510 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3511 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003512 unsigned numDataArgs, bool isObjC,
Ted Kremenek02087932010-07-16 02:11:22 +00003513 const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00003514 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00003515 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00003516 Sema::VariadicCallType CallType,
3517 llvm::SmallBitVector &CheckedVarArgs)
3518 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3519 numDataArgs, beg, hasVAListArg, Args,
3520 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3521 ObjCContext(isObjC)
Jordan Rose3e0ec582012-07-19 18:10:23 +00003522 {}
3523
Craig Toppere14c0f82014-03-12 04:55:44 +00003524
Ted Kremenek02087932010-07-16 02:11:22 +00003525 bool HandleInvalidPrintfConversionSpecifier(
3526 const analyze_printf::PrintfSpecifier &FS,
3527 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003528 unsigned specifierLen) override;
3529
Ted Kremenek02087932010-07-16 02:11:22 +00003530 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3531 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00003532 unsigned specifierLen) override;
Richard Smith55ce3522012-06-25 20:30:08 +00003533 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3534 const char *StartSpecifier,
3535 unsigned SpecifierLen,
3536 const Expr *E);
3537
Ted Kremenek02087932010-07-16 02:11:22 +00003538 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3539 const char *startSpecifier, unsigned specifierLen);
3540 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3541 const analyze_printf::OptionalAmount &Amt,
3542 unsigned type,
3543 const char *startSpecifier, unsigned specifierLen);
3544 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3545 const analyze_printf::OptionalFlag &flag,
3546 const char *startSpecifier, unsigned specifierLen);
3547 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3548 const analyze_printf::OptionalFlag &ignoredFlag,
3549 const analyze_printf::OptionalFlag &flag,
3550 const char *startSpecifier, unsigned specifierLen);
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003551 bool checkForCStrMembers(const analyze_printf::ArgType &AT,
Richard Smith2868a732014-02-28 01:36:39 +00003552 const Expr *E);
Richard Smith55ce3522012-06-25 20:30:08 +00003553
Ted Kremenek02087932010-07-16 02:11:22 +00003554};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003555}
Ted Kremenek02087932010-07-16 02:11:22 +00003556
3557bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3558 const analyze_printf::PrintfSpecifier &FS,
3559 const char *startSpecifier,
3560 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003561 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00003562 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00003563
Ted Kremenekce815422010-07-19 21:25:57 +00003564 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3565 getLocationOfByte(CS.getStart()),
3566 startSpecifier, specifierLen,
3567 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00003568}
3569
Ted Kremenek02087932010-07-16 02:11:22 +00003570bool CheckPrintfHandler::HandleAmount(
3571 const analyze_format_string::OptionalAmount &Amt,
3572 unsigned k, const char *startSpecifier,
3573 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003574
3575 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003576 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00003577 unsigned argIndex = Amt.getArgIndex();
3578 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003579 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3580 << k,
3581 getLocationOfByte(Amt.getStart()),
3582 /*IsStringLocation*/true,
3583 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003584 // Don't do any more checking. We will just emit
3585 // spurious errors.
3586 return false;
3587 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003588
Ted Kremenek5739de72010-01-29 01:06:55 +00003589 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00003590 // Although not in conformance with C99, we also allow the argument to be
3591 // an 'unsigned int' as that is a reasonably safe case. GCC also
3592 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00003593 CoveredArgs.set(argIndex);
3594 const Expr *Arg = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00003595 if (!Arg)
3596 return false;
3597
Ted Kremenek5739de72010-01-29 01:06:55 +00003598 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003599
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003600 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3601 assert(AT.isValid());
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003602
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003603 if (!AT.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003604 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003605 << k << AT.getRepresentativeTypeName(S.Context)
Richard Trieu03cf7b72011-10-28 00:41:25 +00003606 << T << Arg->getSourceRange(),
3607 getLocationOfByte(Amt.getStart()),
3608 /*IsStringLocation*/true,
3609 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00003610 // Don't do any more checking. We will just emit
3611 // spurious errors.
3612 return false;
3613 }
3614 }
3615 }
3616 return true;
3617}
Ted Kremenek5739de72010-01-29 01:06:55 +00003618
Tom Careb49ec692010-06-17 19:00:27 +00003619void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00003620 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003621 const analyze_printf::OptionalAmount &Amt,
3622 unsigned type,
3623 const char *startSpecifier,
3624 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003625 const analyze_printf::PrintfConversionSpecifier &CS =
3626 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00003627
Richard Trieu03cf7b72011-10-28 00:41:25 +00003628 FixItHint fixit =
3629 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3630 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3631 Amt.getConstantLength()))
3632 : FixItHint();
3633
3634 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3635 << type << CS.toString(),
3636 getLocationOfByte(Amt.getStart()),
3637 /*IsStringLocation*/true,
3638 getSpecifierRange(startSpecifier, specifierLen),
3639 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00003640}
3641
Ted Kremenek02087932010-07-16 02:11:22 +00003642void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003643 const analyze_printf::OptionalFlag &flag,
3644 const char *startSpecifier,
3645 unsigned specifierLen) {
3646 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003647 const analyze_printf::PrintfConversionSpecifier &CS =
3648 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00003649 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3650 << flag.toString() << CS.toString(),
3651 getLocationOfByte(flag.getPosition()),
3652 /*IsStringLocation*/true,
3653 getSpecifierRange(startSpecifier, specifierLen),
3654 FixItHint::CreateRemoval(
3655 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003656}
3657
3658void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00003659 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00003660 const analyze_printf::OptionalFlag &ignoredFlag,
3661 const analyze_printf::OptionalFlag &flag,
3662 const char *startSpecifier,
3663 unsigned specifierLen) {
3664 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00003665 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3666 << ignoredFlag.toString() << flag.toString(),
3667 getLocationOfByte(ignoredFlag.getPosition()),
3668 /*IsStringLocation*/true,
3669 getSpecifierRange(startSpecifier, specifierLen),
3670 FixItHint::CreateRemoval(
3671 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00003672}
3673
Richard Smith55ce3522012-06-25 20:30:08 +00003674// Determines if the specified is a C++ class or struct containing
3675// a member with the specified name and kind (e.g. a CXXMethodDecl named
3676// "c_str()").
3677template<typename MemberKind>
3678static llvm::SmallPtrSet<MemberKind*, 1>
3679CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3680 const RecordType *RT = Ty->getAs<RecordType>();
3681 llvm::SmallPtrSet<MemberKind*, 1> Results;
3682
3683 if (!RT)
3684 return Results;
3685 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
Richard Smith2868a732014-02-28 01:36:39 +00003686 if (!RD || !RD->getDefinition())
Richard Smith55ce3522012-06-25 20:30:08 +00003687 return Results;
3688
Alp Tokerb6cc5922014-05-03 03:45:55 +00003689 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
Richard Smith55ce3522012-06-25 20:30:08 +00003690 Sema::LookupMemberName);
Richard Smith2868a732014-02-28 01:36:39 +00003691 R.suppressDiagnostics();
Richard Smith55ce3522012-06-25 20:30:08 +00003692
3693 // We just need to include all members of the right kind turned up by the
3694 // filter, at this point.
3695 if (S.LookupQualifiedName(R, RT->getDecl()))
3696 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3697 NamedDecl *decl = (*I)->getUnderlyingDecl();
3698 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3699 Results.insert(FK);
3700 }
3701 return Results;
3702}
3703
Richard Smith2868a732014-02-28 01:36:39 +00003704/// Check if we could call '.c_str()' on an object.
3705///
3706/// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3707/// allow the call, or if it would be ambiguous).
3708bool Sema::hasCStrMethod(const Expr *E) {
3709 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3710 MethodSet Results =
3711 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3712 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3713 MI != ME; ++MI)
3714 if ((*MI)->getMinRequiredArguments() == 0)
3715 return true;
3716 return false;
3717}
3718
Richard Smith55ce3522012-06-25 20:30:08 +00003719// Check if a (w)string was passed when a (w)char* was needed, and offer a
Hans Wennborgc3b3da02012-08-07 08:11:26 +00003720// better diagnostic if so. AT is assumed to be valid.
Richard Smith55ce3522012-06-25 20:30:08 +00003721// Returns true when a c_str() conversion method is found.
3722bool CheckPrintfHandler::checkForCStrMembers(
Richard Smith2868a732014-02-28 01:36:39 +00003723 const analyze_printf::ArgType &AT, const Expr *E) {
Richard Smith55ce3522012-06-25 20:30:08 +00003724 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3725
3726 MethodSet Results =
3727 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3728
3729 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3730 MI != ME; ++MI) {
3731 const CXXMethodDecl *Method = *MI;
Richard Smith2868a732014-02-28 01:36:39 +00003732 if (Method->getMinRequiredArguments() == 0 &&
Alp Toker314cc812014-01-25 16:55:45 +00003733 AT.matchesType(S.Context, Method->getReturnType())) {
Richard Smith55ce3522012-06-25 20:30:08 +00003734 // FIXME: Suggest parens if the expression needs them.
Alp Tokerb6cc5922014-05-03 03:45:55 +00003735 SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
Richard Smith55ce3522012-06-25 20:30:08 +00003736 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3737 << "c_str()"
3738 << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3739 return true;
3740 }
3741 }
3742
3743 return false;
3744}
3745
Ted Kremenekab278de2010-01-28 23:39:18 +00003746bool
Ted Kremenek02087932010-07-16 02:11:22 +00003747CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00003748 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00003749 const char *startSpecifier,
3750 unsigned specifierLen) {
3751
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003752 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00003753 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00003754 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00003755
Ted Kremenek6cd69422010-07-19 22:01:06 +00003756 if (FS.consumesDataArgument()) {
3757 if (atFirstArg) {
3758 atFirstArg = false;
3759 usesPositionalArgs = FS.usesPositionalArg();
3760 }
3761 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00003762 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3763 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00003764 return false;
3765 }
Ted Kremenek5739de72010-01-29 01:06:55 +00003766 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003767
Ted Kremenekd1668192010-02-27 01:41:03 +00003768 // First check if the field width, precision, and conversion specifier
3769 // have matching data arguments.
3770 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3771 startSpecifier, specifierLen)) {
3772 return false;
3773 }
3774
3775 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3776 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00003777 return false;
3778 }
3779
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003780 if (!CS.consumesDataArgument()) {
3781 // FIXME: Technically specifying a precision or field width here
3782 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00003783 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00003784 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003785
Ted Kremenek4a49d982010-02-26 19:18:41 +00003786 // Consume the argument.
3787 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00003788 if (argIndex < NumDataArgs) {
3789 // The check to see if the argIndex is valid will come later.
3790 // We set the bit here because we may exit early from this
3791 // function if we encounter some other error.
3792 CoveredArgs.set(argIndex);
3793 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00003794
Dimitry Andric6b5ed342015-02-19 22:32:33 +00003795 // FreeBSD kernel extensions.
3796 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3797 CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3798 // We need at least two arguments.
3799 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3800 return false;
3801
3802 // Claim the second argument.
3803 CoveredArgs.set(argIndex + 1);
3804
3805 // Type check the first argument (int for %b, pointer for %D)
3806 const Expr *Ex = getDataArg(argIndex);
3807 const analyze_printf::ArgType &AT =
3808 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3809 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3810 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3811 EmitFormatDiagnostic(
3812 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3813 << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3814 << false << Ex->getSourceRange(),
3815 Ex->getLocStart(), /*IsStringLocation*/false,
3816 getSpecifierRange(startSpecifier, specifierLen));
3817
3818 // Type check the second argument (char * for both %b and %D)
3819 Ex = getDataArg(argIndex + 1);
3820 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3821 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3822 EmitFormatDiagnostic(
3823 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3824 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3825 << false << Ex->getSourceRange(),
3826 Ex->getLocStart(), /*IsStringLocation*/false,
3827 getSpecifierRange(startSpecifier, specifierLen));
3828
3829 return true;
3830 }
3831
Ted Kremenek4a49d982010-02-26 19:18:41 +00003832 // Check for using an Objective-C specific conversion specifier
3833 // in a non-ObjC literal.
Jordan Rose97c6f2b2012-06-04 23:52:23 +00003834 if (!ObjCContext && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00003835 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3836 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00003837 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003838
Tom Careb49ec692010-06-17 19:00:27 +00003839 // Check for invalid use of field width
3840 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00003841 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00003842 startSpecifier, specifierLen);
3843 }
3844
3845 // Check for invalid use of precision
3846 if (!FS.hasValidPrecision()) {
3847 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3848 startSpecifier, specifierLen);
3849 }
3850
3851 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00003852 if (!FS.hasValidThousandsGroupingPrefix())
3853 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003854 if (!FS.hasValidLeadingZeros())
3855 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3856 if (!FS.hasValidPlusPrefix())
3857 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00003858 if (!FS.hasValidSpacePrefix())
3859 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003860 if (!FS.hasValidAlternativeForm())
3861 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3862 if (!FS.hasValidLeftJustified())
3863 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3864
3865 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00003866 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3867 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3868 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00003869 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3870 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3871 startSpecifier, specifierLen);
3872
3873 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00003874 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00003875 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3876 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00003877 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003878 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00003879 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00003880 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3881 diag::warn_format_non_standard_conversion_spec);
Tom Careb49ec692010-06-17 19:00:27 +00003882
Jordan Rose92303592012-09-08 04:00:03 +00003883 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3884 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3885
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003886 // The remaining checks depend on the data arguments.
3887 if (HasVAListArg)
3888 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003889
Ted Kremenek6adb7e32010-07-26 19:45:42 +00003890 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00003891 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003892
Jordan Rose58bbe422012-07-19 18:10:08 +00003893 const Expr *Arg = getDataArg(argIndex);
3894 if (!Arg)
3895 return true;
3896
3897 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
Richard Smith55ce3522012-06-25 20:30:08 +00003898}
3899
Jordan Roseaee34382012-09-05 22:56:26 +00003900static bool requiresParensToAddCast(const Expr *E) {
3901 // FIXME: We should have a general way to reason about operator
3902 // precedence and whether parens are actually needed here.
3903 // Take care of a few common cases where they aren't.
3904 const Expr *Inside = E->IgnoreImpCasts();
3905 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3906 Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3907
3908 switch (Inside->getStmtClass()) {
3909 case Stmt::ArraySubscriptExprClass:
3910 case Stmt::CallExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003911 case Stmt::CharacterLiteralClass:
3912 case Stmt::CXXBoolLiteralExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003913 case Stmt::DeclRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003914 case Stmt::FloatingLiteralClass:
3915 case Stmt::IntegerLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003916 case Stmt::MemberExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003917 case Stmt::ObjCArrayLiteralClass:
3918 case Stmt::ObjCBoolLiteralExprClass:
3919 case Stmt::ObjCBoxedExprClass:
3920 case Stmt::ObjCDictionaryLiteralClass:
3921 case Stmt::ObjCEncodeExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003922 case Stmt::ObjCIvarRefExprClass:
3923 case Stmt::ObjCMessageExprClass:
3924 case Stmt::ObjCPropertyRefExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003925 case Stmt::ObjCStringLiteralClass:
3926 case Stmt::ObjCSubscriptRefExprClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003927 case Stmt::ParenExprClass:
Jordan Roseea0fdfe2012-12-05 18:44:44 +00003928 case Stmt::StringLiteralClass:
Jordan Roseaee34382012-09-05 22:56:26 +00003929 case Stmt::UnaryOperatorClass:
3930 return false;
3931 default:
3932 return true;
3933 }
3934}
3935
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00003936static std::pair<QualType, StringRef>
3937shouldNotPrintDirectly(const ASTContext &Context,
3938 QualType IntendedTy,
3939 const Expr *E) {
3940 // Use a 'while' to peel off layers of typedefs.
3941 QualType TyTy = IntendedTy;
3942 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3943 StringRef Name = UserTy->getDecl()->getName();
3944 QualType CastTy = llvm::StringSwitch<QualType>(Name)
3945 .Case("NSInteger", Context.LongTy)
3946 .Case("NSUInteger", Context.UnsignedLongTy)
3947 .Case("SInt32", Context.IntTy)
3948 .Case("UInt32", Context.UnsignedIntTy)
3949 .Default(QualType());
3950
3951 if (!CastTy.isNull())
3952 return std::make_pair(CastTy, Name);
3953
3954 TyTy = UserTy->desugar();
3955 }
3956
3957 // Strip parens if necessary.
3958 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3959 return shouldNotPrintDirectly(Context,
3960 PE->getSubExpr()->getType(),
3961 PE->getSubExpr());
3962
3963 // If this is a conditional expression, then its result type is constructed
3964 // via usual arithmetic conversions and thus there might be no necessary
3965 // typedef sugar there. Recurse to operands to check for NSInteger &
3966 // Co. usage condition.
3967 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3968 QualType TrueTy, FalseTy;
3969 StringRef TrueName, FalseName;
3970
3971 std::tie(TrueTy, TrueName) =
3972 shouldNotPrintDirectly(Context,
3973 CO->getTrueExpr()->getType(),
3974 CO->getTrueExpr());
3975 std::tie(FalseTy, FalseName) =
3976 shouldNotPrintDirectly(Context,
3977 CO->getFalseExpr()->getType(),
3978 CO->getFalseExpr());
3979
3980 if (TrueTy == FalseTy)
3981 return std::make_pair(TrueTy, TrueName);
3982 else if (TrueTy.isNull())
3983 return std::make_pair(FalseTy, FalseName);
3984 else if (FalseTy.isNull())
3985 return std::make_pair(TrueTy, TrueName);
3986 }
3987
3988 return std::make_pair(QualType(), StringRef());
3989}
3990
Richard Smith55ce3522012-06-25 20:30:08 +00003991bool
3992CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3993 const char *StartSpecifier,
3994 unsigned SpecifierLen,
3995 const Expr *E) {
3996 using namespace analyze_format_string;
3997 using namespace analyze_printf;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00003998 // Now type check the data expression that matches the
3999 // format specifier.
Hans Wennborgc3b3da02012-08-07 08:11:26 +00004000 const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4001 ObjCContext);
Jordan Rose22b74712012-09-05 22:56:19 +00004002 if (!AT.isValid())
4003 return true;
Jordan Roseaee34382012-09-05 22:56:26 +00004004
Jordan Rose598ec092012-12-05 18:44:40 +00004005 QualType ExprTy = E->getType();
Ted Kremenek3365e522013-04-10 06:26:26 +00004006 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4007 ExprTy = TET->getUnderlyingExpr()->getType();
4008 }
4009
Seth Cantrellb4802962015-03-04 03:12:10 +00004010 analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4011
4012 if (match == analyze_printf::ArgType::Match) {
Jordan Rose22b74712012-09-05 22:56:19 +00004013 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004014 }
Jordan Rose98709982012-06-04 22:48:57 +00004015
Jordan Rose22b74712012-09-05 22:56:19 +00004016 // Look through argument promotions for our error message's reported type.
4017 // This includes the integral and floating promotions, but excludes array
4018 // and function pointer decay; seeing that an argument intended to be a
4019 // string has type 'char [6]' is probably more confusing than 'char *'.
4020 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4021 if (ICE->getCastKind() == CK_IntegralCast ||
4022 ICE->getCastKind() == CK_FloatingCast) {
4023 E = ICE->getSubExpr();
Jordan Rose598ec092012-12-05 18:44:40 +00004024 ExprTy = E->getType();
Jordan Rose22b74712012-09-05 22:56:19 +00004025
4026 // Check if we didn't match because of an implicit cast from a 'char'
4027 // or 'short' to an 'int'. This is done because printf is a varargs
4028 // function.
4029 if (ICE->getType() == S.Context.IntTy ||
4030 ICE->getType() == S.Context.UnsignedIntTy) {
4031 // All further checking is done on the subexpression.
Jordan Rose598ec092012-12-05 18:44:40 +00004032 if (AT.matchesType(S.Context, ExprTy))
Jordan Rose22b74712012-09-05 22:56:19 +00004033 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00004034 }
Jordan Rose98709982012-06-04 22:48:57 +00004035 }
Jordan Rose598ec092012-12-05 18:44:40 +00004036 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4037 // Special case for 'a', which has type 'int' in C.
4038 // Note, however, that we do /not/ want to treat multibyte constants like
4039 // 'MooV' as characters! This form is deprecated but still exists.
4040 if (ExprTy == S.Context.IntTy)
4041 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4042 ExprTy = S.Context.CharTy;
Jordan Rose22b74712012-09-05 22:56:19 +00004043 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004044
Jordan Rosebc53ed12014-05-31 04:12:14 +00004045 // Look through enums to their underlying type.
4046 bool IsEnum = false;
4047 if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4048 ExprTy = EnumTy->getDecl()->getIntegerType();
4049 IsEnum = true;
4050 }
4051
Jordan Rose0e5badd2012-12-05 18:44:49 +00004052 // %C in an Objective-C context prints a unichar, not a wchar_t.
4053 // If the argument is an integer of some kind, believe the %C and suggest
4054 // a cast instead of changing the conversion specifier.
Jordan Rose598ec092012-12-05 18:44:40 +00004055 QualType IntendedTy = ExprTy;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004056 if (ObjCContext &&
4057 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4058 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4059 !ExprTy->isCharType()) {
4060 // 'unichar' is defined as a typedef of unsigned short, but we should
4061 // prefer using the typedef if it is visible.
4062 IntendedTy = S.Context.UnsignedShortTy;
Ted Kremenekda2f4052013-10-15 05:25:17 +00004063
4064 // While we are here, check if the value is an IntegerLiteral that happens
4065 // to be within the valid range.
4066 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4067 const llvm::APInt &V = IL->getValue();
4068 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4069 return true;
4070 }
4071
Jordan Rose0e5badd2012-12-05 18:44:49 +00004072 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4073 Sema::LookupOrdinaryName);
4074 if (S.LookupName(Result, S.getCurScope())) {
4075 NamedDecl *ND = Result.getFoundDecl();
4076 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4077 if (TD->getUnderlyingType() == IntendedTy)
4078 IntendedTy = S.Context.getTypedefType(TD);
4079 }
4080 }
4081 }
4082
4083 // Special-case some of Darwin's platform-independence types by suggesting
4084 // casts to primitive types that are known to be large enough.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004085 bool ShouldNotPrintDirectly = false; StringRef CastTyName;
Jordan Roseaee34382012-09-05 22:56:26 +00004086 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004087 QualType CastTy;
4088 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4089 if (!CastTy.isNull()) {
4090 IntendedTy = CastTy;
4091 ShouldNotPrintDirectly = true;
Jordan Roseaee34382012-09-05 22:56:26 +00004092 }
4093 }
4094
Jordan Rose22b74712012-09-05 22:56:19 +00004095 // We may be able to offer a FixItHint if it is a supported type.
4096 PrintfSpecifier fixedFS = FS;
Jordan Roseaee34382012-09-05 22:56:26 +00004097 bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
Jordan Rose22b74712012-09-05 22:56:19 +00004098 S.Context, ObjCContext);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004099
Jordan Rose22b74712012-09-05 22:56:19 +00004100 if (success) {
4101 // Get the fix string from the fixed format specifier
4102 SmallString<16> buf;
4103 llvm::raw_svector_ostream os(buf);
4104 fixedFS.toString(os);
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004105
Jordan Roseaee34382012-09-05 22:56:26 +00004106 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4107
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004108 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
Daniel Jasperad8d8492015-03-04 14:18:20 +00004109 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4110 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4111 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4112 }
Jordan Rose0e5badd2012-12-05 18:44:49 +00004113 // In this case, the specifier is wrong and should be changed to match
4114 // the argument.
Daniel Jasperad8d8492015-03-04 14:18:20 +00004115 EmitFormatDiagnostic(S.PDiag(diag)
4116 << AT.getRepresentativeTypeName(S.Context)
4117 << IntendedTy << IsEnum << E->getSourceRange(),
4118 E->getLocStart(),
4119 /*IsStringLocation*/ false, SpecRange,
4120 FixItHint::CreateReplacement(SpecRange, os.str()));
Jordan Rose0e5badd2012-12-05 18:44:49 +00004121
4122 } else {
Jordan Roseaee34382012-09-05 22:56:26 +00004123 // The canonical type for formatting this value is different from the
4124 // actual type of the expression. (This occurs, for example, with Darwin's
4125 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4126 // should be printed as 'long' for 64-bit compatibility.)
4127 // Rather than emitting a normal format/argument mismatch, we want to
4128 // add a cast to the recommended type (and correct the format string
4129 // if necessary).
4130 SmallString<16> CastBuf;
4131 llvm::raw_svector_ostream CastFix(CastBuf);
4132 CastFix << "(";
4133 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4134 CastFix << ")";
4135
4136 SmallVector<FixItHint,4> Hints;
4137 if (!AT.matchesType(S.Context, IntendedTy))
4138 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4139
4140 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4141 // If there's already a cast present, just replace it.
4142 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4143 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4144
4145 } else if (!requiresParensToAddCast(E)) {
4146 // If the expression has high enough precedence,
4147 // just write the C-style cast.
4148 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4149 CastFix.str()));
4150 } else {
4151 // Otherwise, add parens around the expression as well as the cast.
4152 CastFix << "(";
4153 Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4154 CastFix.str()));
4155
Alp Tokerb6cc5922014-05-03 03:45:55 +00004156 SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
Jordan Roseaee34382012-09-05 22:56:26 +00004157 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4158 }
4159
Jordan Rose0e5badd2012-12-05 18:44:49 +00004160 if (ShouldNotPrintDirectly) {
4161 // The expression has a type that should not be printed directly.
4162 // We extract the name from the typedef because we don't want to show
4163 // the underlying type in the diagnostic.
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00004164 StringRef Name;
4165 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4166 Name = TypedefTy->getDecl()->getName();
4167 else
4168 Name = CastTyName;
Jordan Rose0e5badd2012-12-05 18:44:49 +00004169 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
Jordan Rosebc53ed12014-05-31 04:12:14 +00004170 << Name << IntendedTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004171 << E->getSourceRange(),
4172 E->getLocStart(), /*IsStringLocation=*/false,
4173 SpecRange, Hints);
4174 } else {
4175 // In this case, the expression could be printed using a different
4176 // specifier, but we've decided that the specifier is probably correct
4177 // and we should cast instead. Just use the normal warning message.
4178 EmitFormatDiagnostic(
Jordan Rosebc53ed12014-05-31 04:12:14 +00004179 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4180 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
Jordan Rose0e5badd2012-12-05 18:44:49 +00004181 << E->getSourceRange(),
4182 E->getLocStart(), /*IsStringLocation*/false,
4183 SpecRange, Hints);
4184 }
Jordan Roseaee34382012-09-05 22:56:26 +00004185 }
Jordan Rose22b74712012-09-05 22:56:19 +00004186 } else {
4187 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4188 SpecifierLen);
4189 // Since the warning for passing non-POD types to variadic functions
4190 // was deferred until now, we emit a warning for non-POD
4191 // arguments here.
Richard Smithd7293d72013-08-05 18:49:43 +00004192 switch (S.isValidVarArgType(ExprTy)) {
4193 case Sema::VAK_Valid:
Seth Cantrellb4802962015-03-04 03:12:10 +00004194 case Sema::VAK_ValidInCXX11: {
4195 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4196 if (match == analyze_printf::ArgType::NoMatchPedantic) {
4197 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4198 }
Richard Smithd7293d72013-08-05 18:49:43 +00004199
Seth Cantrellb4802962015-03-04 03:12:10 +00004200 EmitFormatDiagnostic(
4201 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4202 << IsEnum << CSR << E->getSourceRange(),
4203 E->getLocStart(), /*IsStringLocation*/ false, CSR);
4204 break;
4205 }
Richard Smithd7293d72013-08-05 18:49:43 +00004206 case Sema::VAK_Undefined:
Hans Wennborgd9dd4d22014-09-29 23:06:57 +00004207 case Sema::VAK_MSVCUndefined:
Richard Smithd7293d72013-08-05 18:49:43 +00004208 EmitFormatDiagnostic(
4209 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004210 << S.getLangOpts().CPlusPlus11
Jordan Rose598ec092012-12-05 18:44:40 +00004211 << ExprTy
Jordan Rose22b74712012-09-05 22:56:19 +00004212 << CallType
4213 << AT.getRepresentativeTypeName(S.Context)
4214 << CSR
4215 << E->getSourceRange(),
4216 E->getLocStart(), /*IsStringLocation*/false, CSR);
Richard Smith2868a732014-02-28 01:36:39 +00004217 checkForCStrMembers(AT, E);
Richard Smithd7293d72013-08-05 18:49:43 +00004218 break;
4219
4220 case Sema::VAK_Invalid:
4221 if (ExprTy->isObjCObjectType())
4222 EmitFormatDiagnostic(
4223 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4224 << S.getLangOpts().CPlusPlus11
4225 << ExprTy
4226 << CallType
4227 << AT.getRepresentativeTypeName(S.Context)
4228 << CSR
4229 << E->getSourceRange(),
4230 E->getLocStart(), /*IsStringLocation*/false, CSR);
4231 else
4232 // FIXME: If this is an initializer list, suggest removing the braces
4233 // or inserting a cast to the target type.
4234 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4235 << isa<InitListExpr>(E) << ExprTy << CallType
4236 << AT.getRepresentativeTypeName(S.Context)
4237 << E->getSourceRange();
4238 break;
4239 }
4240
4241 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4242 "format string specifier index out of range");
4243 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00004244 }
4245
Ted Kremenekab278de2010-01-28 23:39:18 +00004246 return true;
4247}
4248
Ted Kremenek02087932010-07-16 02:11:22 +00004249//===--- CHECK: Scanf format string checking ------------------------------===//
4250
4251namespace {
4252class CheckScanfHandler : public CheckFormatHandler {
4253public:
4254 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4255 const Expr *origFormatExpr, unsigned firstDataArg,
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004256 unsigned numDataArgs, const char *beg, bool hasVAListArg,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004257 ArrayRef<const Expr *> Args,
Jordan Rose3e0ec582012-07-19 18:10:23 +00004258 unsigned formatIdx, bool inFunctionCall,
Richard Smithd7293d72013-08-05 18:49:43 +00004259 Sema::VariadicCallType CallType,
4260 llvm::SmallBitVector &CheckedVarArgs)
4261 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4262 numDataArgs, beg, hasVAListArg,
4263 Args, formatIdx, inFunctionCall, CallType,
4264 CheckedVarArgs)
Jordan Rose3e0ec582012-07-19 18:10:23 +00004265 {}
Ted Kremenek02087932010-07-16 02:11:22 +00004266
4267 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4268 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004269 unsigned specifierLen) override;
Ted Kremenekce815422010-07-19 21:25:57 +00004270
4271 bool HandleInvalidScanfConversionSpecifier(
4272 const analyze_scanf::ScanfSpecifier &FS,
4273 const char *startSpecifier,
Craig Toppere14c0f82014-03-12 04:55:44 +00004274 unsigned specifierLen) override;
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004275
Craig Toppere14c0f82014-03-12 04:55:44 +00004276 void HandleIncompleteScanList(const char *start, const char *end) override;
Ted Kremenek02087932010-07-16 02:11:22 +00004277};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004278}
Ted Kremenekab278de2010-01-28 23:39:18 +00004279
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004280void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4281 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004282 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4283 getLocationOfByte(end), /*IsStringLocation*/true,
4284 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00004285}
4286
Ted Kremenekce815422010-07-19 21:25:57 +00004287bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4288 const analyze_scanf::ScanfSpecifier &FS,
4289 const char *startSpecifier,
4290 unsigned specifierLen) {
4291
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004292 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00004293 FS.getConversionSpecifier();
4294
4295 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4296 getLocationOfByte(CS.getStart()),
4297 startSpecifier, specifierLen,
4298 CS.getStart(), CS.getLength());
4299}
4300
Ted Kremenek02087932010-07-16 02:11:22 +00004301bool CheckScanfHandler::HandleScanfSpecifier(
4302 const analyze_scanf::ScanfSpecifier &FS,
4303 const char *startSpecifier,
4304 unsigned specifierLen) {
4305
4306 using namespace analyze_scanf;
4307 using namespace analyze_format_string;
4308
Ted Kremenekf03e6d852010-07-20 20:04:27 +00004309 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00004310
Ted Kremenek6cd69422010-07-19 22:01:06 +00004311 // Handle case where '%' and '*' don't consume an argument. These shouldn't
4312 // be used to decide if we are using positional arguments consistently.
4313 if (FS.consumesDataArgument()) {
4314 if (atFirstArg) {
4315 atFirstArg = false;
4316 usesPositionalArgs = FS.usesPositionalArg();
4317 }
4318 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004319 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4320 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00004321 return false;
4322 }
Ted Kremenek02087932010-07-16 02:11:22 +00004323 }
4324
4325 // Check if the field with is non-zero.
4326 const OptionalAmount &Amt = FS.getFieldWidth();
4327 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4328 if (Amt.getConstantAmount() == 0) {
4329 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4330 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00004331 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4332 getLocationOfByte(Amt.getStart()),
4333 /*IsStringLocation*/true, R,
4334 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00004335 }
4336 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004337
Ted Kremenek02087932010-07-16 02:11:22 +00004338 if (!FS.consumesDataArgument()) {
4339 // FIXME: Technically specifying a precision or field width here
4340 // makes no sense. Worth issuing a warning at some point.
4341 return true;
4342 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004343
Ted Kremenek02087932010-07-16 02:11:22 +00004344 // Consume the argument.
4345 unsigned argIndex = FS.getArgIndex();
4346 if (argIndex < NumDataArgs) {
4347 // The check to see if the argIndex is valid will come later.
4348 // We set the bit here because we may exit early from this
4349 // function if we encounter some other error.
4350 CoveredArgs.set(argIndex);
4351 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004352
Ted Kremenek4407ea42010-07-20 20:04:47 +00004353 // Check the length modifier is valid with the given conversion specifier.
Jordan Rose92303592012-09-08 04:00:03 +00004354 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
Jordan Rose2f9cc042012-09-08 04:00:12 +00004355 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4356 diag::warn_format_nonsensical_length);
Jordan Rose92303592012-09-08 04:00:03 +00004357 else if (!FS.hasStandardLengthModifier())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004358 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
Jordan Rose92303592012-09-08 04:00:03 +00004359 else if (!FS.hasStandardLengthConversionCombination())
Jordan Rose2f9cc042012-09-08 04:00:12 +00004360 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4361 diag::warn_format_non_standard_conversion_spec);
Hans Wennborgc9dd9462012-02-22 10:17:01 +00004362
Jordan Rose92303592012-09-08 04:00:03 +00004363 if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4364 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4365
Ted Kremenek02087932010-07-16 02:11:22 +00004366 // The remaining checks depend on the data arguments.
4367 if (HasVAListArg)
4368 return true;
Seth Cantrellb4802962015-03-04 03:12:10 +00004369
Ted Kremenek6adb7e32010-07-26 19:45:42 +00004370 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00004371 return false;
Seth Cantrellb4802962015-03-04 03:12:10 +00004372
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004373 // Check that the argument type matches the format specifier.
4374 const Expr *Ex = getDataArg(argIndex);
Jordan Rose58bbe422012-07-19 18:10:08 +00004375 if (!Ex)
4376 return true;
4377
Hans Wennborgb1ab2a82012-08-07 08:59:46 +00004378 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
Seth Cantrell79340072015-03-04 05:58:08 +00004379
4380 if (!AT.isValid()) {
4381 return true;
4382 }
4383
Seth Cantrellb4802962015-03-04 03:12:10 +00004384 analyze_format_string::ArgType::MatchKind match =
4385 AT.matchesType(S.Context, Ex->getType());
Seth Cantrell79340072015-03-04 05:58:08 +00004386 if (match == analyze_format_string::ArgType::Match) {
4387 return true;
4388 }
Seth Cantrellb4802962015-03-04 03:12:10 +00004389
Seth Cantrell79340072015-03-04 05:58:08 +00004390 ScanfSpecifier fixedFS = FS;
4391 bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4392 S.getLangOpts(), S.Context);
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004393
Seth Cantrell79340072015-03-04 05:58:08 +00004394 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4395 if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4396 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4397 }
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004398
Seth Cantrell79340072015-03-04 05:58:08 +00004399 if (success) {
4400 // Get the fix string from the fixed format specifier.
4401 SmallString<128> buf;
4402 llvm::raw_svector_ostream os(buf);
4403 fixedFS.toString(os);
4404
4405 EmitFormatDiagnostic(
4406 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4407 << Ex->getType() << false << Ex->getSourceRange(),
4408 Ex->getLocStart(),
4409 /*IsStringLocation*/ false,
4410 getSpecifierRange(startSpecifier, specifierLen),
4411 FixItHint::CreateReplacement(
4412 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4413 } else {
4414 EmitFormatDiagnostic(S.PDiag(diag)
4415 << AT.getRepresentativeTypeName(S.Context)
4416 << Ex->getType() << false << Ex->getSourceRange(),
4417 Ex->getLocStart(),
4418 /*IsStringLocation*/ false,
4419 getSpecifierRange(startSpecifier, specifierLen));
Hans Wennborgb1a5e092011-12-10 13:20:11 +00004420 }
4421
Ted Kremenek02087932010-07-16 02:11:22 +00004422 return true;
4423}
4424
4425void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00004426 const Expr *OrigFormatExpr,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004427 ArrayRef<const Expr *> Args,
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004428 bool HasVAListArg, unsigned format_idx,
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004429 unsigned firstDataArg, FormatStringType Type,
Richard Smithd7293d72013-08-05 18:49:43 +00004430 bool inFunctionCall, VariadicCallType CallType,
4431 llvm::SmallBitVector &CheckedVarArgs) {
Ted Kremenek02087932010-07-16 02:11:22 +00004432
Ted Kremenekab278de2010-01-28 23:39:18 +00004433 // CHECK: is the format string a wide literal?
Richard Smith4060f772012-06-13 05:37:23 +00004434 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004435 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004436 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004437 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4438 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004439 return;
4440 }
Ted Kremenek02087932010-07-16 02:11:22 +00004441
Ted Kremenekab278de2010-01-28 23:39:18 +00004442 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004443 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00004444 const char *Str = StrRef.data();
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004445 // Account for cases where the string literal is truncated in a declaration.
4446 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4447 assert(T && "String literal not of constant array type!");
4448 size_t TypeSize = T->getSize().getZExtValue();
4449 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004450 const unsigned numDataArgs = Args.size() - firstDataArg;
Benjamin Kramer6c6a4f42014-02-20 17:05:38 +00004451
4452 // Emit a warning if the string literal is truncated and does not contain an
4453 // embedded null character.
4454 if (TypeSize <= StrRef.size() &&
4455 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4456 CheckFormatHandler::EmitFormatDiagnostic(
4457 *this, inFunctionCall, Args[format_idx],
4458 PDiag(diag::warn_printf_format_string_not_null_terminated),
4459 FExpr->getLocStart(),
4460 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4461 return;
4462 }
4463
Ted Kremenekab278de2010-01-28 23:39:18 +00004464 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00004465 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00004466 CheckFormatHandler::EmitFormatDiagnostic(
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00004467 *this, inFunctionCall, Args[format_idx],
Richard Trieu03cf7b72011-10-28 00:41:25 +00004468 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4469 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00004470 return;
4471 }
Ted Kremenek02087932010-07-16 02:11:22 +00004472
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004473 if (Type == FST_Printf || Type == FST_NSString ||
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004474 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
Ted Kremenek02087932010-07-16 02:11:22 +00004475 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Fariborz Jahanianf8dce0f2015-02-21 00:45:58 +00004476 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004477 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004478 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004479
Hans Wennborg23926bd2011-12-15 10:25:47 +00004480 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004481 getLangOpts(),
Dimitry Andric6b5ed342015-02-19 22:32:33 +00004482 Context.getTargetInfo(),
4483 Type == FST_FreeBSDKPrintf))
Ted Kremenek02087932010-07-16 02:11:22 +00004484 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004485 } else if (Type == FST_Scanf) {
Jordan Rose97c6f2b2012-06-04 23:52:23 +00004486 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
Dmitri Gribenko765396f2013-01-13 20:46:02 +00004487 Str, HasVAListArg, Args, format_idx,
Richard Smithd7293d72013-08-05 18:49:43 +00004488 inFunctionCall, CallType, CheckedVarArgs);
Ted Kremenek02087932010-07-16 02:11:22 +00004489
Hans Wennborg23926bd2011-12-15 10:25:47 +00004490 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
Jordan Rose510260c2012-09-13 02:11:03 +00004491 getLangOpts(),
4492 Context.getTargetInfo()))
Ted Kremenek02087932010-07-16 02:11:22 +00004493 H.DoneProcessing();
Jean-Daniel Dupas028573e72012-01-30 08:46:47 +00004494 } // TODO: handle other formats
Ted Kremenekc70ee862010-01-28 01:18:22 +00004495}
4496
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00004497bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4498 // Str - The format string. NOTE: this is NOT null-terminated!
4499 StringRef StrRef = FExpr->getString();
4500 const char *Str = StrRef.data();
4501 // Account for cases where the string literal is truncated in a declaration.
4502 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4503 assert(T && "String literal not of constant array type!");
4504 size_t TypeSize = T->getSize().getZExtValue();
4505 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4506 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4507 getLangOpts(),
4508 Context.getTargetInfo());
4509}
4510
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004511//===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4512
4513// Returns the related absolute value function that is larger, of 0 if one
4514// does not exist.
4515static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4516 switch (AbsFunction) {
4517 default:
4518 return 0;
4519
4520 case Builtin::BI__builtin_abs:
4521 return Builtin::BI__builtin_labs;
4522 case Builtin::BI__builtin_labs:
4523 return Builtin::BI__builtin_llabs;
4524 case Builtin::BI__builtin_llabs:
4525 return 0;
4526
4527 case Builtin::BI__builtin_fabsf:
4528 return Builtin::BI__builtin_fabs;
4529 case Builtin::BI__builtin_fabs:
4530 return Builtin::BI__builtin_fabsl;
4531 case Builtin::BI__builtin_fabsl:
4532 return 0;
4533
4534 case Builtin::BI__builtin_cabsf:
4535 return Builtin::BI__builtin_cabs;
4536 case Builtin::BI__builtin_cabs:
4537 return Builtin::BI__builtin_cabsl;
4538 case Builtin::BI__builtin_cabsl:
4539 return 0;
4540
4541 case Builtin::BIabs:
4542 return Builtin::BIlabs;
4543 case Builtin::BIlabs:
4544 return Builtin::BIllabs;
4545 case Builtin::BIllabs:
4546 return 0;
4547
4548 case Builtin::BIfabsf:
4549 return Builtin::BIfabs;
4550 case Builtin::BIfabs:
4551 return Builtin::BIfabsl;
4552 case Builtin::BIfabsl:
4553 return 0;
4554
4555 case Builtin::BIcabsf:
4556 return Builtin::BIcabs;
4557 case Builtin::BIcabs:
4558 return Builtin::BIcabsl;
4559 case Builtin::BIcabsl:
4560 return 0;
4561 }
4562}
4563
4564// Returns the argument type of the absolute value function.
4565static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4566 unsigned AbsType) {
4567 if (AbsType == 0)
4568 return QualType();
4569
4570 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4571 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4572 if (Error != ASTContext::GE_None)
4573 return QualType();
4574
4575 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4576 if (!FT)
4577 return QualType();
4578
4579 if (FT->getNumParams() != 1)
4580 return QualType();
4581
4582 return FT->getParamType(0);
4583}
4584
4585// Returns the best absolute value function, or zero, based on type and
4586// current absolute value function.
4587static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4588 unsigned AbsFunctionKind) {
4589 unsigned BestKind = 0;
4590 uint64_t ArgSize = Context.getTypeSize(ArgType);
4591 for (unsigned Kind = AbsFunctionKind; Kind != 0;
4592 Kind = getLargerAbsoluteValueFunction(Kind)) {
4593 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4594 if (Context.getTypeSize(ParamType) >= ArgSize) {
4595 if (BestKind == 0)
4596 BestKind = Kind;
4597 else if (Context.hasSameType(ParamType, ArgType)) {
4598 BestKind = Kind;
4599 break;
4600 }
4601 }
4602 }
4603 return BestKind;
4604}
4605
4606enum AbsoluteValueKind {
4607 AVK_Integer,
4608 AVK_Floating,
4609 AVK_Complex
4610};
4611
4612static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4613 if (T->isIntegralOrEnumerationType())
4614 return AVK_Integer;
4615 if (T->isRealFloatingType())
4616 return AVK_Floating;
4617 if (T->isAnyComplexType())
4618 return AVK_Complex;
4619
4620 llvm_unreachable("Type not integer, floating, or complex");
4621}
4622
4623// Changes the absolute value function to a different type. Preserves whether
4624// the function is a builtin.
4625static unsigned changeAbsFunction(unsigned AbsKind,
4626 AbsoluteValueKind ValueKind) {
4627 switch (ValueKind) {
4628 case AVK_Integer:
4629 switch (AbsKind) {
4630 default:
4631 return 0;
4632 case Builtin::BI__builtin_fabsf:
4633 case Builtin::BI__builtin_fabs:
4634 case Builtin::BI__builtin_fabsl:
4635 case Builtin::BI__builtin_cabsf:
4636 case Builtin::BI__builtin_cabs:
4637 case Builtin::BI__builtin_cabsl:
4638 return Builtin::BI__builtin_abs;
4639 case Builtin::BIfabsf:
4640 case Builtin::BIfabs:
4641 case Builtin::BIfabsl:
4642 case Builtin::BIcabsf:
4643 case Builtin::BIcabs:
4644 case Builtin::BIcabsl:
4645 return Builtin::BIabs;
4646 }
4647 case AVK_Floating:
4648 switch (AbsKind) {
4649 default:
4650 return 0;
4651 case Builtin::BI__builtin_abs:
4652 case Builtin::BI__builtin_labs:
4653 case Builtin::BI__builtin_llabs:
4654 case Builtin::BI__builtin_cabsf:
4655 case Builtin::BI__builtin_cabs:
4656 case Builtin::BI__builtin_cabsl:
4657 return Builtin::BI__builtin_fabsf;
4658 case Builtin::BIabs:
4659 case Builtin::BIlabs:
4660 case Builtin::BIllabs:
4661 case Builtin::BIcabsf:
4662 case Builtin::BIcabs:
4663 case Builtin::BIcabsl:
4664 return Builtin::BIfabsf;
4665 }
4666 case AVK_Complex:
4667 switch (AbsKind) {
4668 default:
4669 return 0;
4670 case Builtin::BI__builtin_abs:
4671 case Builtin::BI__builtin_labs:
4672 case Builtin::BI__builtin_llabs:
4673 case Builtin::BI__builtin_fabsf:
4674 case Builtin::BI__builtin_fabs:
4675 case Builtin::BI__builtin_fabsl:
4676 return Builtin::BI__builtin_cabsf;
4677 case Builtin::BIabs:
4678 case Builtin::BIlabs:
4679 case Builtin::BIllabs:
4680 case Builtin::BIfabsf:
4681 case Builtin::BIfabs:
4682 case Builtin::BIfabsl:
4683 return Builtin::BIcabsf;
4684 }
4685 }
4686 llvm_unreachable("Unable to convert function");
4687}
4688
Benjamin Kramer3d6220d2014-03-01 17:21:22 +00004689static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004690 const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4691 if (!FnInfo)
4692 return 0;
4693
4694 switch (FDecl->getBuiltinID()) {
4695 default:
4696 return 0;
4697 case Builtin::BI__builtin_abs:
4698 case Builtin::BI__builtin_fabs:
4699 case Builtin::BI__builtin_fabsf:
4700 case Builtin::BI__builtin_fabsl:
4701 case Builtin::BI__builtin_labs:
4702 case Builtin::BI__builtin_llabs:
4703 case Builtin::BI__builtin_cabs:
4704 case Builtin::BI__builtin_cabsf:
4705 case Builtin::BI__builtin_cabsl:
4706 case Builtin::BIabs:
4707 case Builtin::BIlabs:
4708 case Builtin::BIllabs:
4709 case Builtin::BIfabs:
4710 case Builtin::BIfabsf:
4711 case Builtin::BIfabsl:
4712 case Builtin::BIcabs:
4713 case Builtin::BIcabsf:
4714 case Builtin::BIcabsl:
4715 return FDecl->getBuiltinID();
4716 }
4717 llvm_unreachable("Unknown Builtin type");
4718}
4719
4720// If the replacement is valid, emit a note with replacement function.
4721// Additionally, suggest including the proper header if not already included.
4722static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
Richard Trieubeffb832014-04-15 23:47:53 +00004723 unsigned AbsKind, QualType ArgType) {
4724 bool EmitHeaderHint = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00004725 const char *HeaderName = nullptr;
4726 const char *FunctionName = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004727 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4728 FunctionName = "std::abs";
4729 if (ArgType->isIntegralOrEnumerationType()) {
4730 HeaderName = "cstdlib";
4731 } else if (ArgType->isRealFloatingType()) {
4732 HeaderName = "cmath";
4733 } else {
4734 llvm_unreachable("Invalid Type");
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004735 }
Richard Trieubeffb832014-04-15 23:47:53 +00004736
4737 // Lookup all std::abs
4738 if (NamespaceDecl *Std = S.getStdNamespace()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +00004739 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
Richard Trieubeffb832014-04-15 23:47:53 +00004740 R.suppressDiagnostics();
4741 S.LookupQualifiedName(R, Std);
4742
4743 for (const auto *I : R) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004744 const FunctionDecl *FDecl = nullptr;
Richard Trieubeffb832014-04-15 23:47:53 +00004745 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4746 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4747 } else {
4748 FDecl = dyn_cast<FunctionDecl>(I);
4749 }
4750 if (!FDecl)
4751 continue;
4752
4753 // Found std::abs(), check that they are the right ones.
4754 if (FDecl->getNumParams() != 1)
4755 continue;
4756
4757 // Check that the parameter type can handle the argument.
4758 QualType ParamType = FDecl->getParamDecl(0)->getType();
4759 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4760 S.Context.getTypeSize(ArgType) <=
4761 S.Context.getTypeSize(ParamType)) {
4762 // Found a function, don't need the header hint.
4763 EmitHeaderHint = false;
4764 break;
4765 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004766 }
Richard Trieubeffb832014-04-15 23:47:53 +00004767 }
4768 } else {
4769 FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4770 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4771
4772 if (HeaderName) {
4773 DeclarationName DN(&S.Context.Idents.get(FunctionName));
4774 LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4775 R.suppressDiagnostics();
4776 S.LookupName(R, S.getCurScope());
4777
4778 if (R.isSingleResult()) {
4779 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4780 if (FD && FD->getBuiltinID() == AbsKind) {
4781 EmitHeaderHint = false;
4782 } else {
4783 return;
4784 }
4785 } else if (!R.empty()) {
4786 return;
4787 }
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004788 }
4789 }
4790
4791 S.Diag(Loc, diag::note_replace_abs_function)
Richard Trieubeffb832014-04-15 23:47:53 +00004792 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004793
Richard Trieubeffb832014-04-15 23:47:53 +00004794 if (!HeaderName)
4795 return;
4796
4797 if (!EmitHeaderHint)
4798 return;
4799
Alp Toker5d96e0a2014-07-11 20:53:51 +00004800 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4801 << FunctionName;
Richard Trieubeffb832014-04-15 23:47:53 +00004802}
4803
4804static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4805 if (!FDecl)
4806 return false;
4807
4808 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4809 return false;
4810
4811 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4812
4813 while (ND && ND->isInlineNamespace()) {
4814 ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004815 }
Richard Trieubeffb832014-04-15 23:47:53 +00004816
4817 if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4818 return false;
4819
4820 if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4821 return false;
4822
4823 return true;
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004824}
4825
4826// Warn when using the wrong abs() function.
4827void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4828 const FunctionDecl *FDecl,
4829 IdentifierInfo *FnInfo) {
4830 if (Call->getNumArgs() != 1)
4831 return;
4832
4833 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
Richard Trieubeffb832014-04-15 23:47:53 +00004834 bool IsStdAbs = IsFunctionStdAbs(FDecl);
4835 if (AbsKind == 0 && !IsStdAbs)
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004836 return;
4837
4838 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4839 QualType ParamType = Call->getArg(0)->getType();
4840
Alp Toker5d96e0a2014-07-11 20:53:51 +00004841 // Unsigned types cannot be negative. Suggest removing the absolute value
4842 // function call.
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004843 if (ArgType->isUnsignedIntegerType()) {
Richard Trieubeffb832014-04-15 23:47:53 +00004844 const char *FunctionName =
4845 IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004846 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4847 Diag(Call->getExprLoc(), diag::note_remove_abs)
Richard Trieubeffb832014-04-15 23:47:53 +00004848 << FunctionName
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004849 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4850 return;
4851 }
4852
Richard Trieubeffb832014-04-15 23:47:53 +00004853 // std::abs has overloads which prevent most of the absolute value problems
4854 // from occurring.
4855 if (IsStdAbs)
4856 return;
4857
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004858 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4859 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4860
4861 // The argument and parameter are the same kind. Check if they are the right
4862 // size.
4863 if (ArgValueKind == ParamValueKind) {
4864 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4865 return;
4866
4867 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4868 Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4869 << FDecl << ArgType << ParamType;
4870
4871 if (NewAbsKind == 0)
4872 return;
4873
4874 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004875 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004876 return;
4877 }
4878
4879 // ArgValueKind != ParamValueKind
4880 // The wrong type of absolute value function was used. Attempt to find the
4881 // proper one.
4882 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4883 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4884 if (NewAbsKind == 0)
4885 return;
4886
4887 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4888 << FDecl << ParamValueKind << ArgValueKind;
4889
4890 emitReplacement(*this, Call->getExprLoc(),
Richard Trieubeffb832014-04-15 23:47:53 +00004891 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00004892 return;
4893}
4894
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004895//===--- CHECK: Standard memory functions ---------------------------------===//
4896
Nico Weber0e6daef2013-12-26 23:38:39 +00004897/// \brief Takes the expression passed to the size_t parameter of functions
4898/// such as memcmp, strncat, etc and warns if it's a comparison.
4899///
4900/// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4901static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4902 IdentifierInfo *FnName,
4903 SourceLocation FnLoc,
4904 SourceLocation RParenLoc) {
4905 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4906 if (!Size)
4907 return false;
4908
4909 // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4910 if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4911 return false;
4912
Nico Weber0e6daef2013-12-26 23:38:39 +00004913 SourceRange SizeRange = Size->getSourceRange();
4914 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4915 << SizeRange << FnName;
Alp Tokerb0869032014-05-17 01:13:18 +00004916 S.Diag(FnLoc, diag::note_memsize_comparison_paren)
Alp Tokerb6cc5922014-05-03 03:45:55 +00004917 << FnName << FixItHint::CreateInsertion(
4918 S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
Nico Weber0e6daef2013-12-26 23:38:39 +00004919 << FixItHint::CreateRemoval(RParenLoc);
Alp Tokerb0869032014-05-17 01:13:18 +00004920 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
Nico Weber0e6daef2013-12-26 23:38:39 +00004921 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
Alp Tokerb6cc5922014-05-03 03:45:55 +00004922 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4923 ")");
Nico Weber0e6daef2013-12-26 23:38:39 +00004924
4925 return true;
4926}
4927
Reid Kleckner5fb5b122014-06-27 23:58:21 +00004928/// \brief Determine whether the given type is or contains a dynamic class type
4929/// (e.g., whether it has a vtable).
4930static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4931 bool &IsContained) {
4932 // Look through array types while ignoring qualifiers.
4933 const Type *Ty = T->getBaseElementTypeUnsafe();
4934 IsContained = false;
4935
4936 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4937 RD = RD ? RD->getDefinition() : nullptr;
4938 if (!RD)
4939 return nullptr;
4940
4941 if (RD->isDynamicClass())
4942 return RD;
4943
4944 // Check all the fields. If any bases were dynamic, the class is dynamic.
4945 // It's impossible for a class to transitively contain itself by value, so
4946 // infinite recursion is impossible.
4947 for (auto *FD : RD->fields()) {
4948 bool SubContained;
4949 if (const CXXRecordDecl *ContainedRD =
4950 getContainedDynamicClass(FD->getType(), SubContained)) {
4951 IsContained = true;
4952 return ContainedRD;
4953 }
4954 }
4955
4956 return nullptr;
Douglas Gregora74926b2011-05-03 20:05:22 +00004957}
4958
Chandler Carruth889ed862011-06-21 23:04:20 +00004959/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004960/// otherwise returns NULL.
Nico Weberc44b35e2015-03-21 17:37:46 +00004961static const Expr *getSizeOfExprArg(const Expr *E) {
Nico Weberc5e73862011-06-14 16:14:58 +00004962 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004963 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4964 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4965 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00004966
Craig Topperc3ec1492014-05-26 06:22:03 +00004967 return nullptr;
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004968}
4969
Chandler Carruth889ed862011-06-21 23:04:20 +00004970/// \brief If E is a sizeof expression, returns its argument type.
Nico Weberc44b35e2015-03-21 17:37:46 +00004971static QualType getSizeOfArgType(const Expr *E) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00004972 if (const UnaryExprOrTypeTraitExpr *SizeOf =
4973 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4974 if (SizeOf->getKind() == clang::UETT_SizeOf)
4975 return SizeOf->getTypeOfArgument();
4976
4977 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00004978}
4979
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004980/// \brief Check for dangerous or invalid arguments to memset().
4981///
Chandler Carruthac687262011-06-03 06:23:57 +00004982/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004983/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4984/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00004985///
4986/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004987void Sema::CheckMemaccessArguments(const CallExpr *Call,
Anna Zaks22122702012-01-17 00:37:07 +00004988 unsigned BId,
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00004989 IdentifierInfo *FnName) {
Anna Zaks22122702012-01-17 00:37:07 +00004990 assert(BId != 0);
4991
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004992 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00004993 // we have enough arguments, and if not, abort further checking.
Anna Zaks22122702012-01-17 00:37:07 +00004994 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
Nico Weber39bfed82011-10-13 22:30:23 +00004995 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00004996 return;
4997
Anna Zaks22122702012-01-17 00:37:07 +00004998 unsigned LastArg = (BId == Builtin::BImemset ||
4999 BId == Builtin::BIstrndup ? 1 : 2);
5000 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
Nico Weber39bfed82011-10-13 22:30:23 +00005001 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005002
Nico Weber0e6daef2013-12-26 23:38:39 +00005003 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5004 Call->getLocStart(), Call->getRParenLoc()))
5005 return;
5006
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005007 // We have special checking when the length is a sizeof expression.
5008 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5009 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5010 llvm::FoldingSetNodeID SizeOfArgID;
5011
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005012 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5013 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00005014 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005015
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005016 QualType DestTy = Dest->getType();
Nico Weberc44b35e2015-03-21 17:37:46 +00005017 QualType PointeeTy;
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005018 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
Nico Weberc44b35e2015-03-21 17:37:46 +00005019 PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00005020
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005021 // Never warn about void type pointers. This can be used to suppress
5022 // false positives.
5023 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00005024 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005025
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005026 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5027 // actually comparing the expressions for equality. Because computing the
5028 // expression IDs can be expensive, we only do this if the diagnostic is
5029 // enabled.
5030 if (SizeOfArg &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005031 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5032 SizeOfArg->getExprLoc())) {
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005033 // We only compute IDs for expressions if the warning is enabled, and
5034 // cache the sizeof arg's ID.
5035 if (SizeOfArgID == llvm::FoldingSetNodeID())
5036 SizeOfArg->Profile(SizeOfArgID, Context, true);
5037 llvm::FoldingSetNodeID DestID;
5038 Dest->Profile(DestID, Context, true);
5039 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00005040 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5041 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005042 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
Anna Zaks869aecc2012-05-30 00:34:21 +00005043 StringRef ReadableName = FnName->getName();
5044
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005045 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
Anna Zaksd08d9152012-05-30 23:14:52 +00005046 if (UnaryOp->getOpcode() == UO_AddrOf)
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005047 ActionIdx = 1; // If its an address-of operator, just remove it.
Fariborz Jahanian4d365ba2013-01-30 01:12:44 +00005048 if (!PointeeTy->isIncompleteType() &&
5049 (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005050 ActionIdx = 2; // If the pointee's size is sizeof(char),
5051 // suggest an explicit length.
Anna Zaks869aecc2012-05-30 00:34:21 +00005052
5053 // If the function is defined as a builtin macro, do not show macro
5054 // expansion.
5055 SourceLocation SL = SizeOfArg->getExprLoc();
5056 SourceRange DSR = Dest->getSourceRange();
5057 SourceRange SSR = SizeOfArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005058 SourceManager &SM = getSourceManager();
Anna Zaks869aecc2012-05-30 00:34:21 +00005059
5060 if (SM.isMacroArgExpansion(SL)) {
5061 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5062 SL = SM.getSpellingLoc(SL);
5063 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5064 SM.getSpellingLoc(DSR.getEnd()));
5065 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5066 SM.getSpellingLoc(SSR.getEnd()));
5067 }
5068
Anna Zaksd08d9152012-05-30 23:14:52 +00005069 DiagRuntimeBehavior(SL, SizeOfArg,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005070 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Anna Zaks869aecc2012-05-30 00:34:21 +00005071 << ReadableName
Anna Zaksd08d9152012-05-30 23:14:52 +00005072 << PointeeTy
5073 << DestTy
Anna Zaks869aecc2012-05-30 00:34:21 +00005074 << DSR
Anna Zaksd08d9152012-05-30 23:14:52 +00005075 << SSR);
5076 DiagRuntimeBehavior(SL, SizeOfArg,
5077 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5078 << ActionIdx
5079 << SSR);
5080
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00005081 break;
5082 }
5083 }
5084
5085 // Also check for cases where the sizeof argument is the exact same
5086 // type as the memory argument, and where it points to a user-defined
5087 // record type.
5088 if (SizeOfArgTy != QualType()) {
5089 if (PointeeTy->isRecordType() &&
5090 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5091 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5092 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5093 << FnName << SizeOfArgTy << ArgIdx
5094 << PointeeTy << Dest->getSourceRange()
5095 << LenExpr->getSourceRange());
5096 break;
5097 }
Nico Weberc5e73862011-06-14 16:14:58 +00005098 }
Nico Weberbac8b6b2015-03-21 17:56:44 +00005099 } else if (DestTy->isArrayType()) {
5100 PointeeTy = DestTy;
Nico Weberc44b35e2015-03-21 17:37:46 +00005101 }
Nico Weberc5e73862011-06-14 16:14:58 +00005102
Nico Weberc44b35e2015-03-21 17:37:46 +00005103 if (PointeeTy == QualType())
5104 continue;
Anna Zaks22122702012-01-17 00:37:07 +00005105
Nico Weberc44b35e2015-03-21 17:37:46 +00005106 // Always complain about dynamic classes.
5107 bool IsContained;
5108 if (const CXXRecordDecl *ContainedRD =
5109 getContainedDynamicClass(PointeeTy, IsContained)) {
John McCall31168b02011-06-15 23:02:42 +00005110
Nico Weberc44b35e2015-03-21 17:37:46 +00005111 unsigned OperationType = 0;
5112 // "overwritten" if we're warning about the destination for any call
5113 // but memcmp; otherwise a verb appropriate to the call.
5114 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5115 if (BId == Builtin::BImemcpy)
5116 OperationType = 1;
5117 else if(BId == Builtin::BImemmove)
5118 OperationType = 2;
5119 else if (BId == Builtin::BImemcmp)
5120 OperationType = 3;
5121 }
5122
John McCall31168b02011-06-15 23:02:42 +00005123 DiagRuntimeBehavior(
5124 Dest->getExprLoc(), Dest,
Nico Weberc44b35e2015-03-21 17:37:46 +00005125 PDiag(diag::warn_dyn_class_memaccess)
5126 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5127 << FnName << IsContained << ContainedRD << OperationType
5128 << Call->getCallee()->getSourceRange());
5129 } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5130 BId != Builtin::BImemset)
5131 DiagRuntimeBehavior(
5132 Dest->getExprLoc(), Dest,
5133 PDiag(diag::warn_arc_object_memaccess)
5134 << ArgIdx << FnName << PointeeTy
5135 << Call->getCallee()->getSourceRange());
5136 else
5137 continue;
5138
5139 DiagRuntimeBehavior(
5140 Dest->getExprLoc(), Dest,
5141 PDiag(diag::note_bad_memaccess_silence)
5142 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5143 break;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005144 }
Nico Weberc44b35e2015-03-21 17:37:46 +00005145
Chandler Carruth53caa4d2011-04-27 07:05:31 +00005146}
5147
Ted Kremenek6865f772011-08-18 20:55:45 +00005148// A little helper routine: ignore addition and subtraction of integer literals.
5149// This intentionally does not ignore all integer constant expressions because
5150// we don't want to remove sizeof().
5151static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5152 Ex = Ex->IgnoreParenCasts();
5153
5154 for (;;) {
5155 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5156 if (!BO || !BO->isAdditiveOp())
5157 break;
5158
5159 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5160 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5161
5162 if (isa<IntegerLiteral>(RHS))
5163 Ex = LHS;
5164 else if (isa<IntegerLiteral>(LHS))
5165 Ex = RHS;
5166 else
5167 break;
5168 }
5169
5170 return Ex;
5171}
5172
Anna Zaks13b08572012-08-08 21:42:23 +00005173static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5174 ASTContext &Context) {
5175 // Only handle constant-sized or VLAs, but not flexible members.
5176 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5177 // Only issue the FIXIT for arrays of size > 1.
5178 if (CAT->getSize().getSExtValue() <= 1)
5179 return false;
5180 } else if (!Ty->isVariableArrayType()) {
5181 return false;
5182 }
5183 return true;
5184}
5185
Ted Kremenek6865f772011-08-18 20:55:45 +00005186// Warn if the user has made the 'size' argument to strlcpy or strlcat
5187// be the size of the source, instead of the destination.
5188void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5189 IdentifierInfo *FnName) {
5190
5191 // Don't crash if the user has the wrong number of arguments
Fariborz Jahanianab4fe982014-09-12 18:44:36 +00005192 unsigned NumArgs = Call->getNumArgs();
5193 if ((NumArgs != 3) && (NumArgs != 4))
Ted Kremenek6865f772011-08-18 20:55:45 +00005194 return;
5195
5196 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5197 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
Craig Topperc3ec1492014-05-26 06:22:03 +00005198 const Expr *CompareWithSrc = nullptr;
Nico Weber0e6daef2013-12-26 23:38:39 +00005199
5200 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5201 Call->getLocStart(), Call->getRParenLoc()))
5202 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00005203
5204 // Look for 'strlcpy(dst, x, sizeof(x))'
5205 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5206 CompareWithSrc = Ex;
5207 else {
5208 // Look for 'strlcpy(dst, x, strlen(x))'
5209 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
Alp Tokera724cff2013-12-28 21:59:02 +00005210 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5211 SizeCall->getNumArgs() == 1)
Ted Kremenek6865f772011-08-18 20:55:45 +00005212 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5213 }
5214 }
5215
5216 if (!CompareWithSrc)
5217 return;
5218
5219 // Determine if the argument to sizeof/strlen is equal to the source
5220 // argument. In principle there's all kinds of things you could do
5221 // here, for instance creating an == expression and evaluating it with
5222 // EvaluateAsBooleanCondition, but this uses a more direct technique:
5223 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5224 if (!SrcArgDRE)
5225 return;
5226
5227 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5228 if (!CompareWithSrcDRE ||
5229 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5230 return;
5231
5232 const Expr *OriginalSizeArg = Call->getArg(2);
5233 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5234 << OriginalSizeArg->getSourceRange() << FnName;
5235
5236 // Output a FIXIT hint if the destination is an array (rather than a
5237 // pointer to an array). This could be enhanced to handle some
5238 // pointers if we know the actual size, like if DstArg is 'array+2'
5239 // we could say 'sizeof(array)-2'.
5240 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Anna Zaks13b08572012-08-08 21:42:23 +00005241 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
Ted Kremenek18db5d42011-08-18 22:48:41 +00005242 return;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005243
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005244 SmallString<128> sizeString;
Ted Kremenek18db5d42011-08-18 22:48:41 +00005245 llvm::raw_svector_ostream OS(sizeString);
5246 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005247 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00005248 OS << ")";
5249
5250 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5251 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5252 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00005253}
5254
Anna Zaks314cd092012-02-01 19:08:57 +00005255/// Check if two expressions refer to the same declaration.
5256static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5257 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5258 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5259 return D1->getDecl() == D2->getDecl();
5260 return false;
5261}
5262
5263static const Expr *getStrlenExprArg(const Expr *E) {
5264 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5265 const FunctionDecl *FD = CE->getDirectCallee();
5266 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
Craig Topperc3ec1492014-05-26 06:22:03 +00005267 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005268 return CE->getArg(0)->IgnoreParenCasts();
5269 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005270 return nullptr;
Anna Zaks314cd092012-02-01 19:08:57 +00005271}
5272
5273// Warn on anti-patterns as the 'size' argument to strncat.
5274// The correct size argument should look like following:
5275// strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5276void Sema::CheckStrncatArguments(const CallExpr *CE,
5277 IdentifierInfo *FnName) {
5278 // Don't crash if the user has the wrong number of arguments.
5279 if (CE->getNumArgs() < 3)
5280 return;
5281 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5282 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5283 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5284
Nico Weber0e6daef2013-12-26 23:38:39 +00005285 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5286 CE->getRParenLoc()))
5287 return;
5288
Anna Zaks314cd092012-02-01 19:08:57 +00005289 // Identify common expressions, which are wrongly used as the size argument
5290 // to strncat and may lead to buffer overflows.
5291 unsigned PatternType = 0;
5292 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5293 // - sizeof(dst)
5294 if (referToTheSameDecl(SizeOfArg, DstArg))
5295 PatternType = 1;
5296 // - sizeof(src)
5297 else if (referToTheSameDecl(SizeOfArg, SrcArg))
5298 PatternType = 2;
5299 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5300 if (BE->getOpcode() == BO_Sub) {
5301 const Expr *L = BE->getLHS()->IgnoreParenCasts();
5302 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5303 // - sizeof(dst) - strlen(dst)
5304 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5305 referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5306 PatternType = 1;
5307 // - sizeof(src) - (anything)
5308 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5309 PatternType = 2;
5310 }
5311 }
5312
5313 if (PatternType == 0)
5314 return;
5315
Anna Zaks5069aa32012-02-03 01:27:37 +00005316 // Generate the diagnostic.
5317 SourceLocation SL = LenArg->getLocStart();
5318 SourceRange SR = LenArg->getSourceRange();
Alp Tokerb6cc5922014-05-03 03:45:55 +00005319 SourceManager &SM = getSourceManager();
Anna Zaks5069aa32012-02-03 01:27:37 +00005320
5321 // If the function is defined as a builtin macro, do not show macro expansion.
5322 if (SM.isMacroArgExpansion(SL)) {
5323 SL = SM.getSpellingLoc(SL);
5324 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
5325 SM.getSpellingLoc(SR.getEnd()));
5326 }
5327
Anna Zaks13b08572012-08-08 21:42:23 +00005328 // Check if the destination is an array (rather than a pointer to an array).
5329 QualType DstTy = DstArg->getType();
5330 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
5331 Context);
5332 if (!isKnownSizeArray) {
5333 if (PatternType == 1)
5334 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5335 else
5336 Diag(SL, diag::warn_strncat_src_size) << SR;
5337 return;
5338 }
5339
Anna Zaks314cd092012-02-01 19:08:57 +00005340 if (PatternType == 1)
Anna Zaks5069aa32012-02-03 01:27:37 +00005341 Diag(SL, diag::warn_strncat_large_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005342 else
Anna Zaks5069aa32012-02-03 01:27:37 +00005343 Diag(SL, diag::warn_strncat_src_size) << SR;
Anna Zaks314cd092012-02-01 19:08:57 +00005344
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00005345 SmallString<128> sizeString;
Anna Zaks314cd092012-02-01 19:08:57 +00005346 llvm::raw_svector_ostream OS(sizeString);
5347 OS << "sizeof(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005348 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005349 OS << ") - ";
5350 OS << "strlen(";
Craig Topperc3ec1492014-05-26 06:22:03 +00005351 DstArg->printPretty(OS, nullptr, getPrintingPolicy());
Anna Zaks314cd092012-02-01 19:08:57 +00005352 OS << ") - 1";
5353
Anna Zaks5069aa32012-02-03 01:27:37 +00005354 Diag(SL, diag::note_strncat_wrong_size)
5355 << FixItHint::CreateReplacement(SR, OS.str());
Anna Zaks314cd092012-02-01 19:08:57 +00005356}
5357
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005358//===--- CHECK: Return Address of Stack Variable --------------------------===//
5359
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005360static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5361 Decl *ParentDecl);
5362static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5363 Decl *ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005364
5365/// CheckReturnStackAddr - Check if a return statement returns the address
5366/// of a stack variable.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005367static void
5368CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5369 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00005370
Craig Topperc3ec1492014-05-26 06:22:03 +00005371 Expr *stackE = nullptr;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005372 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005373
5374 // Perform checking for returned stack addresses, local blocks,
5375 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00005376 if (lhsType->isPointerType() ||
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005377 (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005378 stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
Mike Stump12b8ce12009-08-04 21:02:39 +00005379 } else if (lhsType->isReferenceType()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00005380 stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005381 }
5382
Craig Topperc3ec1492014-05-26 06:22:03 +00005383 if (!stackE)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005384 return; // Nothing suspicious was found.
5385
5386 SourceLocation diagLoc;
5387 SourceRange diagRange;
5388 if (refVars.empty()) {
5389 diagLoc = stackE->getLocStart();
5390 diagRange = stackE->getSourceRange();
5391 } else {
5392 // We followed through a reference variable. 'stackE' contains the
5393 // problematic expression but we will warn at the return statement pointing
5394 // at the reference variable. We will later display the "trail" of
5395 // reference variables using notes.
5396 diagLoc = refVars[0]->getLocStart();
5397 diagRange = refVars[0]->getSourceRange();
5398 }
5399
5400 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005401 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005402 : diag::warn_ret_stack_addr)
5403 << DR->getDecl()->getDeclName() << diagRange;
5404 } else if (isa<BlockExpr>(stackE)) { // local block.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005405 S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005406 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005407 S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005408 } else { // local temporary.
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005409 S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5410 : diag::warn_ret_local_temp_addr)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005411 << diagRange;
5412 }
5413
5414 // Display the "trail" of reference variables that we followed until we
5415 // found the problematic expression using notes.
5416 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5417 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5418 // If this var binds to another reference var, show the range of the next
5419 // var, otherwise the var binds to the problematic expression, in which case
5420 // show the range of the expression.
5421 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5422 : stackE->getSourceRange();
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005423 S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5424 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005425 }
5426}
5427
5428/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5429/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005430/// to a location on the stack, a local block, an address of a label, or a
5431/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005432/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005433/// encounter a subexpression that (1) clearly does not lead to one of the
5434/// above problematic expressions (2) is something we cannot determine leads to
5435/// a problematic expression based on such local checking.
5436///
5437/// Both EvalAddr and EvalVal follow through reference variables to evaluate
5438/// the expression that they point to. Such variables are added to the
5439/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005440///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005441/// EvalAddr processes expressions that are pointers that are used as
5442/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005443/// At the base case of the recursion is a check for the above problematic
5444/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005445///
5446/// This implementation handles:
5447///
5448/// * pointer-to-pointer casts
5449/// * implicit conversions from array references to pointers
5450/// * taking the address of fields
5451/// * arbitrary interplay between "&" and "*" operators
5452/// * pointer arithmetic from an address of a stack variable
5453/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005454static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5455 Decl *ParentDecl) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005456 if (E->isTypeDependent())
Craig Topperc3ec1492014-05-26 06:22:03 +00005457 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005458
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005459 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00005460 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00005461 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00005462 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00005463 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00005464
Peter Collingbourne91147592011-04-15 00:35:48 +00005465 E = E->IgnoreParens();
5466
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005467 // Our "symbolic interpreter" is just a dispatch off the currently
5468 // viewed AST node. We then recursively traverse the AST by calling
5469 // EvalAddr and EvalVal appropriately.
5470 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005471 case Stmt::DeclRefExprClass: {
5472 DeclRefExpr *DR = cast<DeclRefExpr>(E);
5473
Richard Smith40f08eb2014-01-30 22:05:38 +00005474 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005475 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005476 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005477
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005478 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5479 // If this is a reference variable, follow through to the expression that
5480 // it points to.
5481 if (V->hasLocalStorage() &&
5482 V->getType()->isReferenceType() && V->hasInit()) {
5483 // Add the reference variable to the "trail".
5484 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005485 return EvalAddr(V->getInit(), refVars, ParentDecl);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005486 }
5487
Craig Topperc3ec1492014-05-26 06:22:03 +00005488 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005489 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005490
Chris Lattner934edb22007-12-28 05:31:15 +00005491 case Stmt::UnaryOperatorClass: {
5492 // The only unary operator that make sense to handle here
5493 // is AddrOf. All others don't make sense as pointers.
5494 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005495
John McCalle3027922010-08-25 11:45:40 +00005496 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005497 return EvalVal(U->getSubExpr(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005498 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005499 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005500 }
Mike Stump11289f42009-09-09 15:08:12 +00005501
Chris Lattner934edb22007-12-28 05:31:15 +00005502 case Stmt::BinaryOperatorClass: {
5503 // Handle pointer arithmetic. All other binary operators are not valid
5504 // in this context.
5505 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00005506 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00005507
John McCalle3027922010-08-25 11:45:40 +00005508 if (op != BO_Add && op != BO_Sub)
Craig Topperc3ec1492014-05-26 06:22:03 +00005509 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00005510
Chris Lattner934edb22007-12-28 05:31:15 +00005511 Expr *Base = B->getLHS();
5512
5513 // Determine which argument is the real pointer base. It could be
5514 // the RHS argument instead of the LHS.
5515 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00005516
Chris Lattner934edb22007-12-28 05:31:15 +00005517 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005518 return EvalAddr(Base, refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005519 }
Steve Naroff2752a172008-09-10 19:17:48 +00005520
Chris Lattner934edb22007-12-28 05:31:15 +00005521 // For conditional operators we need to see if either the LHS or RHS are
5522 // valid DeclRefExpr*s. If one of them is valid, we return it.
5523 case Stmt::ConditionalOperatorClass: {
5524 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005525
Chris Lattner934edb22007-12-28 05:31:15 +00005526 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005527 // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5528 if (Expr *LHSExpr = C->getLHS()) {
5529 // In C++, we can have a throw-expression, which has 'void' type.
5530 if (!LHSExpr->getType()->isVoidType())
5531 if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005532 return LHS;
5533 }
Chris Lattner934edb22007-12-28 05:31:15 +00005534
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005535 // In C++, we can have a throw-expression, which has 'void' type.
5536 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005537 return nullptr;
Douglas Gregor270b2ef2010-10-21 16:21:08 +00005538
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005539 return EvalAddr(C->getRHS(), refVars, ParentDecl);
Chris Lattner934edb22007-12-28 05:31:15 +00005540 }
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005541
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005542 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00005543 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005544 return E; // local block.
Craig Topperc3ec1492014-05-26 06:22:03 +00005545 return nullptr;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005546
5547 case Stmt::AddrLabelExprClass:
5548 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00005549
John McCall28fc7092011-11-10 05:35:25 +00005550 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005551 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5552 ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005553
Ted Kremenekc3b4c522008-08-07 00:49:01 +00005554 // For casts, we need to handle conversions from arrays to
5555 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00005556 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00005557 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00005558 case Stmt::CXXFunctionalCastExprClass:
Eli Friedman8195ad72012-02-23 23:04:32 +00005559 case Stmt::ObjCBridgedCastExprClass:
Mike Stump11289f42009-09-09 15:08:12 +00005560 case Stmt::CXXStaticCastExprClass:
5561 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00005562 case Stmt::CXXConstCastExprClass:
5563 case Stmt::CXXReinterpretCastExprClass: {
Eli Friedman8195ad72012-02-23 23:04:32 +00005564 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5565 switch (cast<CastExpr>(E)->getCastKind()) {
Eli Friedman8195ad72012-02-23 23:04:32 +00005566 case CK_LValueToRValue:
5567 case CK_NoOp:
5568 case CK_BaseToDerived:
5569 case CK_DerivedToBase:
5570 case CK_UncheckedDerivedToBase:
5571 case CK_Dynamic:
5572 case CK_CPointerToObjCPointerCast:
5573 case CK_BlockPointerToObjCPointerCast:
5574 case CK_AnyPointerToBlockPointerCast:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005575 return EvalAddr(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005576
5577 case CK_ArrayToPointerDecay:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005578 return EvalVal(SubExpr, refVars, ParentDecl);
Eli Friedman8195ad72012-02-23 23:04:32 +00005579
Richard Trieudadefde2014-07-02 04:39:38 +00005580 case CK_BitCast:
5581 if (SubExpr->getType()->isAnyPointerType() ||
5582 SubExpr->getType()->isBlockPointerType() ||
5583 SubExpr->getType()->isObjCQualifiedIdType())
5584 return EvalAddr(SubExpr, refVars, ParentDecl);
5585 else
5586 return nullptr;
5587
Eli Friedman8195ad72012-02-23 23:04:32 +00005588 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005589 return nullptr;
Eli Friedman8195ad72012-02-23 23:04:32 +00005590 }
Chris Lattner934edb22007-12-28 05:31:15 +00005591 }
Mike Stump11289f42009-09-09 15:08:12 +00005592
Douglas Gregorfe314812011-06-21 17:03:29 +00005593 case Stmt::MaterializeTemporaryExprClass:
5594 if (Expr *Result = EvalAddr(
5595 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005596 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005597 return Result;
5598
5599 return E;
5600
Chris Lattner934edb22007-12-28 05:31:15 +00005601 // Everything else: we simply don't reason about them.
5602 default:
Craig Topperc3ec1492014-05-26 06:22:03 +00005603 return nullptr;
Chris Lattner934edb22007-12-28 05:31:15 +00005604 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005605}
Mike Stump11289f42009-09-09 15:08:12 +00005606
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005607
5608/// EvalVal - This function is complements EvalAddr in the mutual recursion.
5609/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005610static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5611 Decl *ParentDecl) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005612do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00005613 // We should only be called for evaluating non-pointer expressions, or
5614 // expressions with a pointer type that are not used as references but instead
5615 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00005616
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005617 // Our "symbolic interpreter" is just a dispatch off the currently
5618 // viewed AST node. We then recursively traverse the AST by calling
5619 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00005620
5621 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005622 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005623 case Stmt::ImplicitCastExprClass: {
5624 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00005625 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00005626 E = IE->getSubExpr();
5627 continue;
5628 }
Craig Topperc3ec1492014-05-26 06:22:03 +00005629 return nullptr;
Ted Kremenekb7861562010-08-04 20:01:07 +00005630 }
5631
John McCall28fc7092011-11-10 05:35:25 +00005632 case Stmt::ExprWithCleanupsClass:
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005633 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
John McCall28fc7092011-11-10 05:35:25 +00005634
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005635 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005636 // When we hit a DeclRefExpr we are looking at code that refers to a
5637 // variable's name. If it's not a reference variable we check if it has
5638 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005639 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005640
Richard Smith40f08eb2014-01-30 22:05:38 +00005641 // If we leave the immediate function, the lifetime isn't about to end.
Alexey Bataev19acc3d2015-01-12 10:17:46 +00005642 if (DR->refersToEnclosingVariableOrCapture())
Craig Topperc3ec1492014-05-26 06:22:03 +00005643 return nullptr;
Richard Smith40f08eb2014-01-30 22:05:38 +00005644
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005645 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5646 // Check if it refers to itself, e.g. "int& i = i;".
5647 if (V == ParentDecl)
5648 return DR;
5649
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005650 if (V->hasLocalStorage()) {
5651 if (!V->getType()->isReferenceType())
5652 return DR;
5653
5654 // Reference variable, follow through to the expression that
5655 // it points to.
5656 if (V->hasInit()) {
5657 // Add the reference variable to the "trail".
5658 refVars.push_back(DR);
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005659 return EvalVal(V->getInit(), refVars, V);
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005660 }
5661 }
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005662 }
Mike Stump11289f42009-09-09 15:08:12 +00005663
Craig Topperc3ec1492014-05-26 06:22:03 +00005664 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005665 }
Mike Stump11289f42009-09-09 15:08:12 +00005666
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005667 case Stmt::UnaryOperatorClass: {
5668 // The only unary operator that make sense to handle here
5669 // is Deref. All others don't resolve to a "name." This includes
5670 // handling all sorts of rvalues passed to a unary operator.
5671 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005672
John McCalle3027922010-08-25 11:45:40 +00005673 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005674 return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005675
Craig Topperc3ec1492014-05-26 06:22:03 +00005676 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005677 }
Mike Stump11289f42009-09-09 15:08:12 +00005678
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005679 case Stmt::ArraySubscriptExprClass: {
5680 // Array subscripts are potential references to data on the stack. We
5681 // retrieve the DeclRefExpr* for the array variable if it indeed
5682 // has local storage.
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005683 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005684 }
Mike Stump11289f42009-09-09 15:08:12 +00005685
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005686 case Stmt::ConditionalOperatorClass: {
5687 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005688 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005689 ConditionalOperator *C = cast<ConditionalOperator>(E);
5690
Anders Carlsson801c5c72007-11-30 19:04:31 +00005691 // Handle the GNU extension for missing LHS.
Richard Smith6a6a4bb2014-01-27 04:19:56 +00005692 if (Expr *LHSExpr = C->getLHS()) {
5693 // In C++, we can have a throw-expression, which has 'void' type.
5694 if (!LHSExpr->getType()->isVoidType())
5695 if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5696 return LHS;
5697 }
5698
5699 // In C++, we can have a throw-expression, which has 'void' type.
5700 if (C->getRHS()->getType()->isVoidType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005701 return nullptr;
Anders Carlsson801c5c72007-11-30 19:04:31 +00005702
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005703 return EvalVal(C->getRHS(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005704 }
Mike Stump11289f42009-09-09 15:08:12 +00005705
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005706 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00005707 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005708 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00005709
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005710 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005711 if (M->isArrow())
Craig Topperc3ec1492014-05-26 06:22:03 +00005712 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005713
5714 // Check whether the member type is itself a reference, in which case
5715 // we're not going to refer to the member, but to what the member refers to.
5716 if (M->getMemberDecl()->getType()->isReferenceType())
Craig Topperc3ec1492014-05-26 06:22:03 +00005717 return nullptr;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00005718
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005719 return EvalVal(M->getBase(), refVars, ParentDecl);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005720 }
Mike Stump11289f42009-09-09 15:08:12 +00005721
Douglas Gregorfe314812011-06-21 17:03:29 +00005722 case Stmt::MaterializeTemporaryExprClass:
5723 if (Expr *Result = EvalVal(
5724 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
Argyrios Kyrtzidisb4015e12012-04-30 23:23:55 +00005725 refVars, ParentDecl))
Douglas Gregorfe314812011-06-21 17:03:29 +00005726 return Result;
5727
5728 return E;
5729
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005730 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00005731 // Check that we don't return or take the address of a reference to a
5732 // temporary. This is only useful in C++.
5733 if (!E->isTypeDependent() && E->isRValue())
5734 return E;
5735
5736 // Everything else: we simply don't reason about them.
Craig Topperc3ec1492014-05-26 06:22:03 +00005737 return nullptr;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005738 }
Ted Kremenekb7861562010-08-04 20:01:07 +00005739} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00005740}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005741
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005742void
5743Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5744 SourceLocation ReturnLoc,
5745 bool isObjCMethod,
Artyom Skrobov9f213442014-01-24 11:10:39 +00005746 const AttrVec *Attrs,
5747 const FunctionDecl *FD) {
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005748 CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5749
5750 // Check if the return value is null but should not be.
Douglas Gregorb4866e82015-06-19 18:13:19 +00005751 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5752 (!isObjCMethod && isNonNullType(Context, lhsType))) &&
Benjamin Kramerae852a62014-02-23 14:34:50 +00005753 CheckNonNullExpr(*this, RetValExp))
5754 Diag(ReturnLoc, diag::warn_null_ret)
5755 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
Artyom Skrobov9f213442014-01-24 11:10:39 +00005756
5757 // C++11 [basic.stc.dynamic.allocation]p4:
5758 // If an allocation function declared with a non-throwing
5759 // exception-specification fails to allocate storage, it shall return
5760 // a null pointer. Any other allocation function that fails to allocate
5761 // storage shall indicate failure only by throwing an exception [...]
5762 if (FD) {
5763 OverloadedOperatorKind Op = FD->getOverloadedOperator();
5764 if (Op == OO_New || Op == OO_Array_New) {
5765 const FunctionProtoType *Proto
5766 = FD->getType()->castAs<FunctionProtoType>();
5767 if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5768 CheckNonNullExpr(*this, RetValExp))
5769 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5770 << FD << getLangOpts().CPlusPlus11;
5771 }
5772 }
Ted Kremenekef9e7f82014-01-22 06:10:28 +00005773}
5774
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005775//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5776
5777/// Check for comparisons of floating point operands using != and ==.
5778/// Issue a warning if these are no self-comparisons, as they are not likely
5779/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00005780void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Richard Trieu82402a02011-09-15 21:56:47 +00005781 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5782 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005783
5784 // Special case: check for x == x (which is OK).
5785 // Do not emit warnings for such cases.
5786 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5787 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5788 if (DRL->getDecl() == DRR->getDecl())
David Blaikie1f4ff152012-07-16 20:47:22 +00005789 return;
Mike Stump11289f42009-09-09 15:08:12 +00005790
5791
Ted Kremenekeda40e22007-11-29 00:59:04 +00005792 // Special case: check for comparisons against literals that can be exactly
5793 // represented by APFloat. In such cases, do not emit a warning. This
5794 // is a heuristic: often comparison against such literals are used to
5795 // detect if a value in a variable has not changed. This clearly can
5796 // lead to false negatives.
David Blaikie1f4ff152012-07-16 20:47:22 +00005797 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5798 if (FLL->isExact())
5799 return;
5800 } else
5801 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5802 if (FLR->isExact())
5803 return;
Mike Stump11289f42009-09-09 15:08:12 +00005804
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005805 // Check for comparisons with builtin types.
David Blaikie1f4ff152012-07-16 20:47:22 +00005806 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005807 if (CL->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005808 return;
Mike Stump11289f42009-09-09 15:08:12 +00005809
David Blaikie1f4ff152012-07-16 20:47:22 +00005810 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Alp Tokera724cff2013-12-28 21:59:02 +00005811 if (CR->getBuiltinCallee())
David Blaikie1f4ff152012-07-16 20:47:22 +00005812 return;
Mike Stump11289f42009-09-09 15:08:12 +00005813
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005814 // Emit the diagnostic.
David Blaikie1f4ff152012-07-16 20:47:22 +00005815 Diag(Loc, diag::warn_floatingpoint_eq)
5816 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00005817}
John McCallca01b222010-01-04 23:21:16 +00005818
John McCall70aa5392010-01-06 05:24:50 +00005819//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5820//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00005821
John McCall70aa5392010-01-06 05:24:50 +00005822namespace {
John McCallca01b222010-01-04 23:21:16 +00005823
John McCall70aa5392010-01-06 05:24:50 +00005824/// Structure recording the 'active' range of an integer-valued
5825/// expression.
5826struct IntRange {
5827 /// The number of bits active in the int.
5828 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00005829
John McCall70aa5392010-01-06 05:24:50 +00005830 /// True if the int is known not to have negative values.
5831 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00005832
John McCall70aa5392010-01-06 05:24:50 +00005833 IntRange(unsigned Width, bool NonNegative)
5834 : Width(Width), NonNegative(NonNegative)
5835 {}
John McCallca01b222010-01-04 23:21:16 +00005836
John McCall817d4af2010-11-10 23:38:19 +00005837 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00005838 static IntRange forBoolType() {
5839 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00005840 }
5841
John McCall817d4af2010-11-10 23:38:19 +00005842 /// Returns the range of an opaque value of the given integral type.
5843 static IntRange forValueOfType(ASTContext &C, QualType T) {
5844 return forValueOfCanonicalType(C,
5845 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00005846 }
5847
John McCall817d4af2010-11-10 23:38:19 +00005848 /// Returns the range of an opaque value of a canonical integral type.
5849 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00005850 assert(T->isCanonicalUnqualified());
5851
5852 if (const VectorType *VT = dyn_cast<VectorType>(T))
5853 T = VT->getElementType().getTypePtr();
5854 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5855 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005856 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5857 T = AT->getValueType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00005858
David Majnemer6a426652013-06-07 22:07:20 +00005859 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00005860 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
David Majnemer6a426652013-06-07 22:07:20 +00005861 EnumDecl *Enum = ET->getDecl();
5862 if (!Enum->isCompleteDefinition())
5863 return IntRange(C.getIntWidth(QualType(T, 0)), false);
John McCall18a2c2c2010-11-09 22:22:12 +00005864
David Majnemer6a426652013-06-07 22:07:20 +00005865 unsigned NumPositive = Enum->getNumPositiveBits();
5866 unsigned NumNegative = Enum->getNumNegativeBits();
John McCallcc7e5bf2010-05-06 08:58:33 +00005867
David Majnemer6a426652013-06-07 22:07:20 +00005868 if (NumNegative == 0)
5869 return IntRange(NumPositive, true/*NonNegative*/);
5870 else
5871 return IntRange(std::max(NumPositive + 1, NumNegative),
5872 false/*NonNegative*/);
John McCallcc7e5bf2010-05-06 08:58:33 +00005873 }
John McCall70aa5392010-01-06 05:24:50 +00005874
5875 const BuiltinType *BT = cast<BuiltinType>(T);
5876 assert(BT->isInteger());
5877
5878 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5879 }
5880
John McCall817d4af2010-11-10 23:38:19 +00005881 /// Returns the "target" range of a canonical integral type, i.e.
5882 /// the range of values expressible in the type.
5883 ///
5884 /// This matches forValueOfCanonicalType except that enums have the
5885 /// full range of their type, not the range of their enumerators.
5886 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5887 assert(T->isCanonicalUnqualified());
5888
5889 if (const VectorType *VT = dyn_cast<VectorType>(T))
5890 T = VT->getElementType().getTypePtr();
5891 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5892 T = CT->getElementType().getTypePtr();
Justin Bogner4f42fc42014-07-21 18:01:53 +00005893 if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5894 T = AT->getValueType().getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005895 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00005896 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00005897
5898 const BuiltinType *BT = cast<BuiltinType>(T);
5899 assert(BT->isInteger());
5900
5901 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5902 }
5903
5904 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00005905 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00005906 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00005907 L.NonNegative && R.NonNegative);
5908 }
5909
John McCall817d4af2010-11-10 23:38:19 +00005910 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00005911 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00005912 return IntRange(std::min(L.Width, R.Width),
5913 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00005914 }
5915};
5916
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005917static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5918 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005919 if (value.isSigned() && value.isNegative())
5920 return IntRange(value.getMinSignedBits(), false);
5921
5922 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00005923 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005924
5925 // isNonNegative() just checks the sign bit without considering
5926 // signedness.
5927 return IntRange(value.getActiveBits(), true);
5928}
5929
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005930static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5931 unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005932 if (result.isInt())
5933 return GetValueRange(C, result.getInt(), MaxWidth);
5934
5935 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00005936 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5937 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5938 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5939 R = IntRange::join(R, El);
5940 }
John McCall70aa5392010-01-06 05:24:50 +00005941 return R;
5942 }
5943
5944 if (result.isComplexInt()) {
5945 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5946 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5947 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00005948 }
5949
5950 // This can happen with lossless casts to intptr_t of "based" lvalues.
5951 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00005952 // FIXME: The only reason we need to pass the type in here is to get
5953 // the sign right on this one case. It would be nice if APValue
5954 // preserved this.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005955 assert(result.isLValue() || result.isAddrLabelDiff());
Douglas Gregor61b6e492011-05-21 16:28:01 +00005956 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00005957}
John McCall70aa5392010-01-06 05:24:50 +00005958
Eli Friedmane6d33952013-07-08 20:20:06 +00005959static QualType GetExprType(Expr *E) {
5960 QualType Ty = E->getType();
5961 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5962 Ty = AtomicRHS->getValueType();
5963 return Ty;
5964}
5965
John McCall70aa5392010-01-06 05:24:50 +00005966/// Pseudo-evaluate the given integer expression, estimating the
5967/// range of values it might take.
5968///
5969/// \param MaxWidth - the width to which the value will be truncated
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00005970static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
John McCall70aa5392010-01-06 05:24:50 +00005971 E = E->IgnoreParens();
5972
5973 // Try a full evaluation first.
5974 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00005975 if (E->EvaluateAsRValue(result, C))
Eli Friedmane6d33952013-07-08 20:20:06 +00005976 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00005977
5978 // I think we only want to look through implicit casts here; if the
5979 // user has an explicit widening cast, we should treat the value as
5980 // being of the new, wider type.
5981 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
Eli Friedman8349dc12011-12-15 02:41:52 +00005982 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
John McCall70aa5392010-01-06 05:24:50 +00005983 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5984
Eli Friedmane6d33952013-07-08 20:20:06 +00005985 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
John McCall70aa5392010-01-06 05:24:50 +00005986
John McCalle3027922010-08-25 11:45:40 +00005987 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00005988
John McCall70aa5392010-01-06 05:24:50 +00005989 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00005990 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00005991 return OutputTypeRange;
5992
5993 IntRange SubRange
5994 = GetExprRange(C, CE->getSubExpr(),
5995 std::min(MaxWidth, OutputTypeRange.Width));
5996
5997 // Bail out if the subexpr's range is as wide as the cast type.
5998 if (SubRange.Width >= OutputTypeRange.Width)
5999 return OutputTypeRange;
6000
6001 // Otherwise, we take the smaller width, and we're non-negative if
6002 // either the output type or the subexpr is.
6003 return IntRange(SubRange.Width,
6004 SubRange.NonNegative || OutputTypeRange.NonNegative);
6005 }
6006
6007 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6008 // If we can fold the condition, just take that operand.
6009 bool CondResult;
6010 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6011 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6012 : CO->getFalseExpr(),
6013 MaxWidth);
6014
6015 // Otherwise, conservatively merge.
6016 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6017 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6018 return IntRange::join(L, R);
6019 }
6020
6021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6022 switch (BO->getOpcode()) {
6023
6024 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00006025 case BO_LAnd:
6026 case BO_LOr:
6027 case BO_LT:
6028 case BO_GT:
6029 case BO_LE:
6030 case BO_GE:
6031 case BO_EQ:
6032 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00006033 return IntRange::forBoolType();
6034
John McCallc3688382011-07-13 06:35:24 +00006035 // The type of the assignments is the type of the LHS, so the RHS
6036 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00006037 case BO_MulAssign:
6038 case BO_DivAssign:
6039 case BO_RemAssign:
6040 case BO_AddAssign:
6041 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00006042 case BO_XorAssign:
6043 case BO_OrAssign:
6044 // TODO: bitfields?
Eli Friedmane6d33952013-07-08 20:20:06 +00006045 return IntRange::forValueOfType(C, GetExprType(E));
John McCallff96ccd2010-02-23 19:22:29 +00006046
John McCallc3688382011-07-13 06:35:24 +00006047 // Simple assignments just pass through the RHS, which will have
6048 // been coerced to the LHS type.
6049 case BO_Assign:
6050 // TODO: bitfields?
6051 return GetExprRange(C, BO->getRHS(), MaxWidth);
6052
John McCall70aa5392010-01-06 05:24:50 +00006053 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006054 case BO_PtrMemD:
6055 case BO_PtrMemI:
Eli Friedmane6d33952013-07-08 20:20:06 +00006056 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006057
John McCall2ce81ad2010-01-06 22:07:33 +00006058 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00006059 case BO_And:
6060 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00006061 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6062 GetExprRange(C, BO->getRHS(), MaxWidth));
6063
John McCall70aa5392010-01-06 05:24:50 +00006064 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00006065 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00006066 // ...except that we want to treat '1 << (blah)' as logically
6067 // positive. It's an important idiom.
6068 if (IntegerLiteral *I
6069 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6070 if (I->getValue() == 1) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006071 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
John McCall1bff9932010-04-07 01:14:35 +00006072 return IntRange(R.Width, /*NonNegative*/ true);
6073 }
6074 }
6075 // fallthrough
6076
John McCalle3027922010-08-25 11:45:40 +00006077 case BO_ShlAssign:
Eli Friedmane6d33952013-07-08 20:20:06 +00006078 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006079
John McCall2ce81ad2010-01-06 22:07:33 +00006080 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00006081 case BO_Shr:
6082 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00006083 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6084
6085 // If the shift amount is a positive constant, drop the width by
6086 // that much.
6087 llvm::APSInt shift;
6088 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6089 shift.isNonNegative()) {
6090 unsigned zext = shift.getZExtValue();
6091 if (zext >= L.Width)
6092 L.Width = (L.NonNegative ? 0 : 1);
6093 else
6094 L.Width -= zext;
6095 }
6096
6097 return L;
6098 }
6099
6100 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00006101 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00006102 return GetExprRange(C, BO->getRHS(), MaxWidth);
6103
John McCall2ce81ad2010-01-06 22:07:33 +00006104 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00006105 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00006106 if (BO->getLHS()->getType()->isPointerType())
Eli Friedmane6d33952013-07-08 20:20:06 +00006107 return IntRange::forValueOfType(C, GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006108 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00006109
John McCall51431812011-07-14 22:39:48 +00006110 // The width of a division result is mostly determined by the size
6111 // of the LHS.
6112 case BO_Div: {
6113 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006114 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006115 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6116
6117 // If the divisor is constant, use that.
6118 llvm::APSInt divisor;
6119 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6120 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6121 if (log2 >= L.Width)
6122 L.Width = (L.NonNegative ? 0 : 1);
6123 else
6124 L.Width = std::min(L.Width - log2, MaxWidth);
6125 return L;
6126 }
6127
6128 // Otherwise, just use the LHS's width.
6129 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6130 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6131 }
6132
6133 // The result of a remainder can't be larger than the result of
6134 // either side.
6135 case BO_Rem: {
6136 // Don't 'pre-truncate' the operands.
Eli Friedmane6d33952013-07-08 20:20:06 +00006137 unsigned opWidth = C.getIntWidth(GetExprType(E));
John McCall51431812011-07-14 22:39:48 +00006138 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6139 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6140
6141 IntRange meet = IntRange::meet(L, R);
6142 meet.Width = std::min(meet.Width, MaxWidth);
6143 return meet;
6144 }
6145
6146 // The default behavior is okay for these.
6147 case BO_Mul:
6148 case BO_Add:
6149 case BO_Xor:
6150 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00006151 break;
6152 }
6153
John McCall51431812011-07-14 22:39:48 +00006154 // The default case is to treat the operation as if it were closed
6155 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00006156 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6157 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6158 return IntRange::join(L, R);
6159 }
6160
6161 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6162 switch (UO->getOpcode()) {
6163 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00006164 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00006165 return IntRange::forBoolType();
6166
6167 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00006168 case UO_Deref:
6169 case UO_AddrOf: // should be impossible
Eli Friedmane6d33952013-07-08 20:20:06 +00006170 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006171
6172 default:
6173 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6174 }
6175 }
6176
Ted Kremeneka553fbf2013-10-14 18:55:27 +00006177 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6178 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6179
John McCalld25db7e2013-05-06 21:39:12 +00006180 if (FieldDecl *BitField = E->getSourceBitField())
Richard Smithcaf33902011-10-10 18:28:20 +00006181 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00006182 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00006183
Eli Friedmane6d33952013-07-08 20:20:06 +00006184 return IntRange::forValueOfType(C, GetExprType(E));
John McCall70aa5392010-01-06 05:24:50 +00006185}
John McCall263a48b2010-01-04 23:31:57 +00006186
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006187static IntRange GetExprRange(ASTContext &C, Expr *E) {
Eli Friedmane6d33952013-07-08 20:20:06 +00006188 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
John McCallcc7e5bf2010-05-06 08:58:33 +00006189}
6190
John McCall263a48b2010-01-04 23:31:57 +00006191/// Checks whether the given value, which currently has the given
6192/// source semantics, has the same value when coerced through the
6193/// target semantics.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006194static bool IsSameFloatAfterCast(const llvm::APFloat &value,
6195 const llvm::fltSemantics &Src,
6196 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006197 llvm::APFloat truncated = value;
6198
6199 bool ignored;
6200 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6201 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6202
6203 return truncated.bitwiseIsEqual(value);
6204}
6205
6206/// Checks whether the given value, which currently has the given
6207/// source semantics, has the same value when coerced through the
6208/// target semantics.
6209///
6210/// The value might be a vector of floats (or a complex number).
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006211static bool IsSameFloatAfterCast(const APValue &value,
6212 const llvm::fltSemantics &Src,
6213 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00006214 if (value.isFloat())
6215 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6216
6217 if (value.isVector()) {
6218 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6219 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6220 return false;
6221 return true;
6222 }
6223
6224 assert(value.isComplexFloat());
6225 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6226 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6227}
6228
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006229static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00006230
Ted Kremenek6274be42010-09-23 21:43:44 +00006231static bool IsZero(Sema &S, Expr *E) {
6232 // Suppress cases where we are comparing against an enum constant.
6233 if (const DeclRefExpr *DR =
6234 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6235 if (isa<EnumConstantDecl>(DR->getDecl()))
6236 return false;
6237
6238 // Suppress cases where the '0' value is expanded from a macro.
6239 if (E->getLocStart().isMacroID())
6240 return false;
6241
John McCallcc7e5bf2010-05-06 08:58:33 +00006242 llvm::APSInt Value;
6243 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6244}
6245
John McCall2551c1b2010-10-06 00:25:24 +00006246static bool HasEnumType(Expr *E) {
6247 // Strip off implicit integral promotions.
6248 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006249 if (ICE->getCastKind() != CK_IntegralCast &&
6250 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00006251 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00006252 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00006253 }
6254
6255 return E->getType()->isEnumeralType();
6256}
6257
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006258static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
Richard Trieu36594562013-11-01 21:47:19 +00006259 // Disable warning in template instantiations.
6260 if (!S.ActiveTemplateInstantiations.empty())
6261 return;
6262
John McCalle3027922010-08-25 11:45:40 +00006263 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00006264 if (E->isValueDependent())
6265 return;
6266
John McCalle3027922010-08-25 11:45:40 +00006267 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006268 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006269 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006270 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006271 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006272 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006273 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006274 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006275 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006276 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006277 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006278 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00006279 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006280 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00006281 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00006282 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6283 }
6284}
6285
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006286static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006287 Expr *Constant, Expr *Other,
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006288 llvm::APSInt Value,
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006289 bool RhsConstant) {
Richard Trieudd51d742013-11-01 21:19:43 +00006290 // Disable warning in template instantiations.
6291 if (!S.ActiveTemplateInstantiations.empty())
6292 return;
6293
Richard Trieu0f097742014-04-04 04:13:47 +00006294 // TODO: Investigate using GetExprRange() to get tighter bounds
6295 // on the bit ranges.
6296 QualType OtherT = Other->getType();
David Majnemer7800f1f2015-05-23 01:32:17 +00006297 if (const auto *AT = OtherT->getAs<AtomicType>())
Justin Bogner4f42fc42014-07-21 18:01:53 +00006298 OtherT = AT->getValueType();
Richard Trieu0f097742014-04-04 04:13:47 +00006299 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6300 unsigned OtherWidth = OtherRange.Width;
6301
6302 bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6303
Richard Trieu560910c2012-11-14 22:50:24 +00006304 // 0 values are handled later by CheckTrivialUnsignedComparison().
Richard Trieu0f097742014-04-04 04:13:47 +00006305 if ((Value == 0) && (!OtherIsBooleanType))
Richard Trieu560910c2012-11-14 22:50:24 +00006306 return;
6307
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006308 BinaryOperatorKind op = E->getOpcode();
Richard Trieu0f097742014-04-04 04:13:47 +00006309 bool IsTrue = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006310
Richard Trieu0f097742014-04-04 04:13:47 +00006311 // Used for diagnostic printout.
6312 enum {
6313 LiteralConstant = 0,
6314 CXXBoolLiteralTrue,
6315 CXXBoolLiteralFalse
6316 } LiteralOrBoolConstant = LiteralConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006317
Richard Trieu0f097742014-04-04 04:13:47 +00006318 if (!OtherIsBooleanType) {
6319 QualType ConstantT = Constant->getType();
6320 QualType CommonT = E->getLHS()->getType();
Richard Trieu560910c2012-11-14 22:50:24 +00006321
Richard Trieu0f097742014-04-04 04:13:47 +00006322 if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
6323 return;
6324 assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
6325 "comparison with non-integer type");
6326
6327 bool ConstantSigned = ConstantT->isSignedIntegerType();
6328 bool CommonSigned = CommonT->isSignedIntegerType();
6329
6330 bool EqualityOnly = false;
6331
6332 if (CommonSigned) {
6333 // The common type is signed, therefore no signed to unsigned conversion.
6334 if (!OtherRange.NonNegative) {
6335 // Check that the constant is representable in type OtherT.
6336 if (ConstantSigned) {
6337 if (OtherWidth >= Value.getMinSignedBits())
6338 return;
6339 } else { // !ConstantSigned
6340 if (OtherWidth >= Value.getActiveBits() + 1)
6341 return;
6342 }
6343 } else { // !OtherSigned
6344 // Check that the constant is representable in type OtherT.
6345 // Negative values are out of range.
6346 if (ConstantSigned) {
6347 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6348 return;
6349 } else { // !ConstantSigned
6350 if (OtherWidth >= Value.getActiveBits())
6351 return;
6352 }
Richard Trieu560910c2012-11-14 22:50:24 +00006353 }
Richard Trieu0f097742014-04-04 04:13:47 +00006354 } else { // !CommonSigned
6355 if (OtherRange.NonNegative) {
Richard Trieu560910c2012-11-14 22:50:24 +00006356 if (OtherWidth >= Value.getActiveBits())
6357 return;
Craig Toppercf360162014-06-18 05:13:11 +00006358 } else { // OtherSigned
6359 assert(!ConstantSigned &&
6360 "Two signed types converted to unsigned types.");
Richard Trieu0f097742014-04-04 04:13:47 +00006361 // Check to see if the constant is representable in OtherT.
6362 if (OtherWidth > Value.getActiveBits())
6363 return;
6364 // Check to see if the constant is equivalent to a negative value
6365 // cast to CommonT.
6366 if (S.Context.getIntWidth(ConstantT) ==
6367 S.Context.getIntWidth(CommonT) &&
6368 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6369 return;
6370 // The constant value rests between values that OtherT can represent
6371 // after conversion. Relational comparison still works, but equality
6372 // comparisons will be tautological.
6373 EqualityOnly = true;
Richard Trieu560910c2012-11-14 22:50:24 +00006374 }
6375 }
Richard Trieu0f097742014-04-04 04:13:47 +00006376
6377 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6378
6379 if (op == BO_EQ || op == BO_NE) {
6380 IsTrue = op == BO_NE;
6381 } else if (EqualityOnly) {
6382 return;
6383 } else if (RhsConstant) {
6384 if (op == BO_GT || op == BO_GE)
6385 IsTrue = !PositiveConstant;
6386 else // op == BO_LT || op == BO_LE
6387 IsTrue = PositiveConstant;
6388 } else {
6389 if (op == BO_LT || op == BO_LE)
6390 IsTrue = !PositiveConstant;
6391 else // op == BO_GT || op == BO_GE
6392 IsTrue = PositiveConstant;
Richard Trieu560910c2012-11-14 22:50:24 +00006393 }
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006394 } else {
Richard Trieu0f097742014-04-04 04:13:47 +00006395 // Other isKnownToHaveBooleanValue
6396 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6397 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6398 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6399
6400 static const struct LinkedConditions {
6401 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6402 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6403 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6404 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6405 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6406 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6407
6408 } TruthTable = {
6409 // Constant on LHS. | Constant on RHS. |
6410 // LT_Zero| Zero | One |GT_One| LT_Zero| Zero | One |GT_One|
6411 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6412 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6413 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6414 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6415 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6416 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6417 };
6418
6419 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6420
6421 enum ConstantValue ConstVal = Zero;
6422 if (Value.isUnsigned() || Value.isNonNegative()) {
6423 if (Value == 0) {
6424 LiteralOrBoolConstant =
6425 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6426 ConstVal = Zero;
6427 } else if (Value == 1) {
6428 LiteralOrBoolConstant =
6429 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6430 ConstVal = One;
6431 } else {
6432 LiteralOrBoolConstant = LiteralConstant;
6433 ConstVal = GT_One;
6434 }
6435 } else {
6436 ConstVal = LT_Zero;
6437 }
6438
6439 CompareBoolWithConstantResult CmpRes;
6440
6441 switch (op) {
6442 case BO_LT:
6443 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6444 break;
6445 case BO_GT:
6446 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6447 break;
6448 case BO_LE:
6449 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6450 break;
6451 case BO_GE:
6452 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6453 break;
6454 case BO_EQ:
6455 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6456 break;
6457 case BO_NE:
6458 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6459 break;
6460 default:
6461 CmpRes = Unkwn;
6462 break;
6463 }
6464
6465 if (CmpRes == AFals) {
6466 IsTrue = false;
6467 } else if (CmpRes == ATrue) {
6468 IsTrue = true;
6469 } else {
6470 return;
6471 }
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006472 }
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006473
6474 // If this is a comparison to an enum constant, include that
6475 // constant in the diagnostic.
Craig Topperc3ec1492014-05-26 06:22:03 +00006476 const EnumConstantDecl *ED = nullptr;
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006477 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6478 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6479
6480 SmallString<64> PrettySourceValue;
6481 llvm::raw_svector_ostream OS(PrettySourceValue);
6482 if (ED)
Ted Kremeneke943ce12013-03-15 22:02:46 +00006483 OS << '\'' << *ED << "' (" << Value << ")";
Ted Kremenekb7d7dd42013-03-15 21:50:10 +00006484 else
6485 OS << Value;
6486
Richard Trieu0f097742014-04-04 04:13:47 +00006487 S.DiagRuntimeBehavior(
6488 E->getOperatorLoc(), E,
6489 S.PDiag(diag::warn_out_of_range_compare)
6490 << OS.str() << LiteralOrBoolConstant
6491 << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6492 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006493}
6494
John McCallcc7e5bf2010-05-06 08:58:33 +00006495/// Analyze the operands of the given comparison. Implements the
6496/// fallback case from AnalyzeComparison.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006497static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00006498 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6499 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00006500}
John McCall263a48b2010-01-04 23:31:57 +00006501
John McCallca01b222010-01-04 23:21:16 +00006502/// \brief Implements -Wsign-compare.
6503///
Richard Trieu82402a02011-09-15 21:56:47 +00006504/// \param E the binary operator to check for warnings
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006505static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006506 // The type the comparison is being performed in.
6507 QualType T = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00006508
6509 // Only analyze comparison operators where both sides have been converted to
6510 // the same type.
6511 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6512 return AnalyzeImpConvsInComparison(S, E);
6513
6514 // Don't analyze value-dependent comparisons directly.
Fariborz Jahanian282071e2012-09-18 17:46:26 +00006515 if (E->isValueDependent())
6516 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006517
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006518 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6519 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006520
6521 bool IsComparisonConstant = false;
6522
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006523 // Check whether an integer constant comparison results in a value
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006524 // of 'true' or 'false'.
6525 if (T->isIntegralType(S.Context)) {
6526 llvm::APSInt RHSValue;
6527 bool IsRHSIntegralLiteral =
6528 RHS->isIntegerConstantExpr(RHSValue, S.Context);
6529 llvm::APSInt LHSValue;
6530 bool IsLHSIntegralLiteral =
6531 LHS->isIntegerConstantExpr(LHSValue, S.Context);
6532 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6533 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6534 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6535 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6536 else
6537 IsComparisonConstant =
6538 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
Fariborz Jahanian2f4e33a2012-09-20 19:36:41 +00006539 } else if (!T->hasUnsignedIntegerRepresentation())
6540 IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006541
John McCallcc7e5bf2010-05-06 08:58:33 +00006542 // We don't do anything special if this isn't an unsigned integral
6543 // comparison: we're only interested in integral comparisons, and
6544 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00006545 //
6546 // We also don't care about value-dependent expressions or expressions
6547 // whose result is a constant.
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006548 if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
John McCallcc7e5bf2010-05-06 08:58:33 +00006549 return AnalyzeImpConvsInComparison(S, E);
Fariborz Jahanianb1885422012-09-18 17:37:21 +00006550
John McCallcc7e5bf2010-05-06 08:58:33 +00006551 // Check to see if one of the (unmodified) operands is of different
6552 // signedness.
6553 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00006554 if (LHS->getType()->hasSignedIntegerRepresentation()) {
6555 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00006556 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00006557 signedOperand = LHS;
6558 unsignedOperand = RHS;
6559 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6560 signedOperand = RHS;
6561 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00006562 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00006563 CheckTrivialUnsignedComparison(S, E);
6564 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006565 }
6566
John McCallcc7e5bf2010-05-06 08:58:33 +00006567 // Otherwise, calculate the effective range of the signed operand.
6568 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00006569
John McCallcc7e5bf2010-05-06 08:58:33 +00006570 // Go ahead and analyze implicit conversions in the operands. Note
6571 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00006572 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6573 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00006574
John McCallcc7e5bf2010-05-06 08:58:33 +00006575 // If the signed range is non-negative, -Wsign-compare won't fire,
6576 // but we should still check for comparisons which are always true
6577 // or false.
6578 if (signedRange.NonNegative)
6579 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00006580
6581 // For (in)equality comparisons, if the unsigned operand is a
6582 // constant which cannot collide with a overflowed signed operand,
6583 // then reinterpreting the signed operand as unsigned will not
6584 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00006585 if (E->isEqualityOp()) {
6586 unsigned comparisonWidth = S.Context.getIntWidth(T);
6587 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00006588
John McCallcc7e5bf2010-05-06 08:58:33 +00006589 // We should never be unable to prove that the unsigned operand is
6590 // non-negative.
6591 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6592
6593 if (unsignedRange.Width < comparisonWidth)
6594 return;
6595 }
6596
Douglas Gregorbfb4a212012-05-01 01:53:49 +00006597 S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6598 S.PDiag(diag::warn_mixed_sign_comparison)
6599 << LHS->getType() << RHS->getType()
6600 << LHS->getSourceRange() << RHS->getSourceRange());
John McCallca01b222010-01-04 23:21:16 +00006601}
6602
John McCall1f425642010-11-11 03:21:53 +00006603/// Analyzes an attempt to assign the given value to a bitfield.
6604///
6605/// Returns true if there was something fishy about the attempt.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006606static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6607 SourceLocation InitLoc) {
John McCall1f425642010-11-11 03:21:53 +00006608 assert(Bitfield->isBitField());
6609 if (Bitfield->isInvalidDecl())
6610 return false;
6611
John McCalldeebbcf2010-11-11 05:33:51 +00006612 // White-list bool bitfields.
6613 if (Bitfield->getType()->isBooleanType())
6614 return false;
6615
Douglas Gregor789adec2011-02-04 13:09:01 +00006616 // Ignore value- or type-dependent expressions.
6617 if (Bitfield->getBitWidth()->isValueDependent() ||
6618 Bitfield->getBitWidth()->isTypeDependent() ||
6619 Init->isValueDependent() ||
6620 Init->isTypeDependent())
6621 return false;
6622
John McCall1f425642010-11-11 03:21:53 +00006623 Expr *OriginalInit = Init->IgnoreParenImpCasts();
6624
Richard Smith5fab0c92011-12-28 19:48:30 +00006625 llvm::APSInt Value;
6626 if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
John McCall1f425642010-11-11 03:21:53 +00006627 return false;
6628
John McCall1f425642010-11-11 03:21:53 +00006629 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00006630 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00006631
6632 if (OriginalWidth <= FieldWidth)
6633 return false;
6634
Eli Friedmanc267a322012-01-26 23:11:39 +00006635 // Compute the value which the bitfield will contain.
Jay Foad6d4db0c2010-12-07 08:25:34 +00006636 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
Eli Friedmanc267a322012-01-26 23:11:39 +00006637 TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
John McCall1f425642010-11-11 03:21:53 +00006638
Eli Friedmanc267a322012-01-26 23:11:39 +00006639 // Check whether the stored value is equal to the original value.
6640 TruncatedValue = TruncatedValue.extend(OriginalWidth);
Richard Trieuc320c742012-07-23 20:21:35 +00006641 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
John McCall1f425642010-11-11 03:21:53 +00006642 return false;
6643
Eli Friedmanc267a322012-01-26 23:11:39 +00006644 // Special-case bitfields of width 1: booleans are naturally 0/1, and
Eli Friedmane1ffd492012-02-02 00:40:20 +00006645 // therefore don't strictly fit into a signed bitfield of width 1.
6646 if (FieldWidth == 1 && Value == 1)
Eli Friedmanc267a322012-01-26 23:11:39 +00006647 return false;
6648
John McCall1f425642010-11-11 03:21:53 +00006649 std::string PrettyValue = Value.toString(10);
6650 std::string PrettyTrunc = TruncatedValue.toString(10);
6651
6652 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6653 << PrettyValue << PrettyTrunc << OriginalInit->getType()
6654 << Init->getSourceRange();
6655
6656 return true;
6657}
6658
John McCalld2a53122010-11-09 23:24:47 +00006659/// Analyze the given simple or compound assignment for warning-worthy
6660/// operations.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006661static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
John McCalld2a53122010-11-09 23:24:47 +00006662 // Just recurse on the LHS.
6663 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6664
6665 // We want to recurse on the RHS as normal unless we're assigning to
6666 // a bitfield.
John McCalld25db7e2013-05-06 21:39:12 +00006667 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006668 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
John McCall1f425642010-11-11 03:21:53 +00006669 E->getOperatorLoc())) {
6670 // Recurse, ignoring any implicit conversions on the RHS.
6671 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6672 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00006673 }
6674 }
6675
6676 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6677}
6678
John McCall263a48b2010-01-04 23:31:57 +00006679/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006680static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006681 SourceLocation CContext, unsigned diag,
6682 bool pruneControlFlow = false) {
6683 if (pruneControlFlow) {
6684 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6685 S.PDiag(diag)
6686 << SourceType << T << E->getSourceRange()
6687 << SourceRange(CContext));
6688 return;
6689 }
Douglas Gregor364f7db2011-03-12 00:14:31 +00006690 S.Diag(E->getExprLoc(), diag)
6691 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6692}
6693
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006694/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Ted Kremenek8a92c8b2012-01-31 05:37:37 +00006695static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
Anna Zaks314cd092012-02-01 19:08:57 +00006696 SourceLocation CContext, unsigned diag,
6697 bool pruneControlFlow = false) {
6698 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
Chandler Carruth7f3654f2011-04-05 06:47:57 +00006699}
6700
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006701/// Diagnose an implicit cast from a literal expression. Does not warn when the
6702/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00006703void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6704 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006705 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00006706 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006707 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00006708 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6709 T->hasUnsignedIntegerRepresentation());
6710 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00006711 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006712 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00006713 return;
6714
Eli Friedman07185912013-08-29 23:44:43 +00006715 // FIXME: Force the precision of the source value down so we don't print
6716 // digits which are usually useless (we don't really care here if we
6717 // truncate a digit by accident in edge cases). Ideally, APFloat::toString
6718 // would automatically print the shortest representation, but it's a bit
6719 // tricky to implement.
David Blaikie7555b6a2012-05-15 16:56:36 +00006720 SmallString<16> PrettySourceValue;
Eli Friedman07185912013-08-29 23:44:43 +00006721 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6722 precision = (precision * 59 + 195) / 196;
6723 Value.toString(PrettySourceValue, precision);
6724
David Blaikie9b88cc02012-05-15 17:18:27 +00006725 SmallString<16> PrettyTargetValue;
David Blaikie7555b6a2012-05-15 16:56:36 +00006726 if (T->isSpecificBuiltinType(BuiltinType::Bool))
6727 PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6728 else
David Blaikie9b88cc02012-05-15 17:18:27 +00006729 IntegerValue.toString(PrettyTargetValue);
David Blaikie7555b6a2012-05-15 16:56:36 +00006730
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00006731 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
David Blaikie7555b6a2012-05-15 16:56:36 +00006732 << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6733 << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00006734}
6735
John McCall18a2c2c2010-11-09 22:22:12 +00006736std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6737 if (!Range.Width) return "0";
6738
6739 llvm::APSInt ValueInRange = Value;
6740 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00006741 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00006742 return ValueInRange.toString(10);
6743}
6744
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006745static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6746 if (!isa<ImplicitCastExpr>(Ex))
6747 return false;
6748
6749 Expr *InnerE = Ex->IgnoreParenImpCasts();
6750 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6751 const Type *Source =
6752 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6753 if (Target->isDependentType())
6754 return false;
6755
6756 const BuiltinType *FloatCandidateBT =
6757 dyn_cast<BuiltinType>(ToBool ? Source : Target);
6758 const Type *BoolCandidateType = ToBool ? Target : Source;
6759
6760 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6761 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6762}
6763
6764void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6765 SourceLocation CC) {
6766 unsigned NumArgs = TheCall->getNumArgs();
6767 for (unsigned i = 0; i < NumArgs; ++i) {
6768 Expr *CurrA = TheCall->getArg(i);
6769 if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6770 continue;
6771
6772 bool IsSwapped = ((i > 0) &&
6773 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6774 IsSwapped |= ((i < (NumArgs - 1)) &&
6775 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6776 if (IsSwapped) {
6777 // Warn on this floating-point to bool conversion.
6778 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6779 CurrA->getType(), CC,
6780 diag::warn_impcast_floating_point_to_bool);
6781 }
6782 }
6783}
6784
Richard Trieu5b993502014-10-15 03:42:06 +00006785static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6786 SourceLocation CC) {
6787 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6788 E->getExprLoc()))
6789 return;
6790
6791 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6792 const Expr::NullPointerConstantKind NullKind =
6793 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6794 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6795 return;
6796
6797 // Return if target type is a safe conversion.
6798 if (T->isAnyPointerType() || T->isBlockPointerType() ||
6799 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6800 return;
6801
6802 SourceLocation Loc = E->getSourceRange().getBegin();
6803
6804 // __null is usually wrapped in a macro. Go up a macro if that is the case.
6805 if (NullKind == Expr::NPCK_GNUNull) {
6806 if (Loc.isMacroID())
6807 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6808 }
6809
6810 // Only warn if the null and context location are in the same macro expansion.
6811 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6812 return;
6813
6814 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6815 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6816 << FixItHint::CreateReplacement(Loc,
6817 S.getFixItZeroLiteralForType(T, Loc));
6818}
6819
John McCallcc7e5bf2010-05-06 08:58:33 +00006820void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
Craig Topperc3ec1492014-05-26 06:22:03 +00006821 SourceLocation CC, bool *ICContext = nullptr) {
John McCallcc7e5bf2010-05-06 08:58:33 +00006822 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00006823
John McCallcc7e5bf2010-05-06 08:58:33 +00006824 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6825 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6826 if (Source == Target) return;
6827 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00006828
Chandler Carruthc22845a2011-07-26 05:40:03 +00006829 // If the conversion context location is invalid don't complain. We also
6830 // don't want to emit a warning if the issue occurs from the expansion of
6831 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6832 // delay this check as long as possible. Once we detect we are in that
6833 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006834 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00006835 return;
6836
Richard Trieu021baa32011-09-23 20:10:00 +00006837 // Diagnose implicit casts to bool.
6838 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6839 if (isa<StringLiteral>(E))
6840 // Warn on string literal to bool. Checks for string literals in logical
Richard Trieu955231d2014-01-25 01:10:35 +00006841 // and expressions, for instance, assert(0 && "error here"), are
6842 // prevented by a check in AnalyzeImplicitConversions().
Richard Trieu021baa32011-09-23 20:10:00 +00006843 return DiagnoseImpCast(S, E, T, CC,
6844 diag::warn_impcast_string_literal_to_bool);
Richard Trieu1e632af2014-01-28 23:40:26 +00006845 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6846 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6847 // This covers the literal expressions that evaluate to Objective-C
6848 // objects.
6849 return DiagnoseImpCast(S, E, T, CC,
6850 diag::warn_impcast_objective_c_literal_to_bool);
6851 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00006852 if (Source->isPointerType() || Source->canDecayToPointerType()) {
6853 // Warn on pointer to bool conversion that is always true.
6854 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6855 SourceRange(CC));
Lang Hamesdf5c1212011-12-05 20:49:50 +00006856 }
Richard Trieu021baa32011-09-23 20:10:00 +00006857 }
John McCall263a48b2010-01-04 23:31:57 +00006858
6859 // Strip vector types.
6860 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006861 if (!isa<VectorType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006862 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006863 return;
John McCallacf0ee52010-10-08 02:01:28 +00006864 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006865 }
Chris Lattneree7286f2011-06-14 04:51:15 +00006866
6867 // If the vector cast is cast between two vectors of the same size, it is
6868 // a bitcast, not a conversion.
6869 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6870 return;
John McCall263a48b2010-01-04 23:31:57 +00006871
6872 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6873 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6874 }
Stephen Canon3ba640d2014-04-03 10:33:25 +00006875 if (auto VecTy = dyn_cast<VectorType>(Target))
6876 Target = VecTy->getElementType().getTypePtr();
John McCall263a48b2010-01-04 23:31:57 +00006877
6878 // Strip complex types.
6879 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006880 if (!isa<ComplexType>(Target)) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006881 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006882 return;
6883
John McCallacf0ee52010-10-08 02:01:28 +00006884 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006885 }
John McCall263a48b2010-01-04 23:31:57 +00006886
6887 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6888 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6889 }
6890
6891 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6892 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6893
6894 // If the source is floating point...
6895 if (SourceBT && SourceBT->isFloatingPoint()) {
6896 // ...and the target is floating point...
6897 if (TargetBT && TargetBT->isFloatingPoint()) {
6898 // ...then warn if we're dropping FP rank.
6899
6900 // Builtin FP kinds are ordered by increasing FP rank.
6901 if (SourceBT->getKind() > TargetBT->getKind()) {
6902 // Don't warn about float constants that are precisely
6903 // representable in the target type.
6904 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00006905 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00006906 // Value might be a float, a float vector, or a float complex.
6907 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00006908 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6909 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00006910 return;
6911 }
6912
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006913 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006914 return;
6915
John McCallacf0ee52010-10-08 02:01:28 +00006916 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00006917 }
6918 return;
6919 }
6920
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006921 // If the target is integral, always warn.
David Blaikie7555b6a2012-05-15 16:56:36 +00006922 if (TargetBT && TargetBT->isInteger()) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00006923 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00006924 return;
6925
Chandler Carruth22c7a792011-02-17 11:05:49 +00006926 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00006927 // We also want to warn on, e.g., "int i = -1.234"
6928 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6929 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6930 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6931
Chandler Carruth016ef402011-04-10 08:36:24 +00006932 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6933 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00006934 } else {
6935 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6936 }
6937 }
John McCall263a48b2010-01-04 23:31:57 +00006938
Hans Wennborgf4ad2322012-08-28 15:44:30 +00006939 // If the target is bool, warn if expr is a function or method call.
6940 if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6941 isa<CallExpr>(E)) {
6942 // Check last argument of function call to see if it is an
6943 // implicit cast from a type matching the type the result
6944 // is being cast to.
6945 CallExpr *CEx = cast<CallExpr>(E);
6946 unsigned NumArgs = CEx->getNumArgs();
6947 if (NumArgs > 0) {
6948 Expr *LastA = CEx->getArg(NumArgs - 1);
6949 Expr *InnerE = LastA->IgnoreParenImpCasts();
6950 const Type *InnerType =
6951 S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6952 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6953 // Warn on this floating-point to bool conversion
6954 DiagnoseImpCast(S, E, T, CC,
6955 diag::warn_impcast_floating_point_to_bool);
6956 }
6957 }
6958 }
John McCall263a48b2010-01-04 23:31:57 +00006959 return;
6960 }
6961
Richard Trieu5b993502014-10-15 03:42:06 +00006962 DiagnoseNullConversion(S, E, T, CC);
Richard Trieubeaf3452011-05-29 19:59:02 +00006963
David Blaikie9366d2b2012-06-19 21:19:06 +00006964 if (!Source->isIntegerType() || !Target->isIntegerType())
6965 return;
6966
David Blaikie7555b6a2012-05-15 16:56:36 +00006967 // TODO: remove this early return once the false positives for constant->bool
6968 // in templates, macros, etc, are reduced or removed.
6969 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6970 return;
6971
John McCallcc7e5bf2010-05-06 08:58:33 +00006972 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00006973 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00006974
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006975 if (SourceRange.Width > TargetRange.Width) {
Sam Panzer6fffec62013-03-28 19:07:11 +00006976 // If the source is a constant, use a default-on diagnostic.
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006977 // TODO: this should happen for bitfield stores, too.
6978 llvm::APSInt Value(32);
6979 if (E->isIntegerConstantExpr(Value, S.Context)) {
6980 if (S.SourceMgr.isInSystemMacro(CC))
6981 return;
6982
John McCall18a2c2c2010-11-09 22:22:12 +00006983 std::string PrettySourceValue = Value.toString(10);
6984 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006985
Ted Kremenek33ba9952011-10-22 02:37:33 +00006986 S.DiagRuntimeBehavior(E->getExprLoc(), E,
6987 S.PDiag(diag::warn_impcast_integer_precision_constant)
6988 << PrettySourceValue << PrettyTargetValue
6989 << E->getType() << T << E->getSourceRange()
6990 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00006991 return;
6992 }
6993
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00006994 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6995 if (S.SourceMgr.isInSystemMacro(CC))
6996 return;
6997
David Blaikie9455da02012-04-12 22:40:54 +00006998 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
Anna Zaks314cd092012-02-01 19:08:57 +00006999 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7000 /* pruneControlFlow */ true);
John McCallacf0ee52010-10-08 02:01:28 +00007001 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00007002 }
7003
7004 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7005 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7006 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007007
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007008 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007009 return;
7010
John McCallcc7e5bf2010-05-06 08:58:33 +00007011 unsigned DiagID = diag::warn_impcast_integer_sign;
7012
7013 // Traditionally, gcc has warned about this under -Wsign-compare.
7014 // We also want to warn about it in -Wconversion.
7015 // So if -Wconversion is off, use a completely identical diagnostic
7016 // in the sign-compare group.
7017 // The conditional-checking code will
7018 if (ICContext) {
7019 DiagID = diag::warn_impcast_integer_sign_conditional;
7020 *ICContext = true;
7021 }
7022
John McCallacf0ee52010-10-08 02:01:28 +00007023 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00007024 }
7025
Douglas Gregora78f1932011-02-22 02:45:07 +00007026 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00007027 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7028 // type, to give us better diagnostics.
7029 QualType SourceType = E->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00007030 if (!S.getLangOpts().CPlusPlus) {
Douglas Gregor364f7db2011-03-12 00:14:31 +00007031 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7032 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7033 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7034 SourceType = S.Context.getTypeDeclType(Enum);
7035 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7036 }
7037 }
7038
Douglas Gregora78f1932011-02-22 02:45:07 +00007039 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7040 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
John McCall5ea95772013-03-09 00:54:27 +00007041 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7042 TargetEnum->getDecl()->hasNameForLinkage() &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007043 SourceEnum != TargetEnum) {
Matt Beaumont-Gay7a57ada2012-01-06 22:43:58 +00007044 if (S.SourceMgr.isInSystemMacro(CC))
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007045 return;
7046
Douglas Gregor364f7db2011-03-12 00:14:31 +00007047 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00007048 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00007049 }
Douglas Gregora78f1932011-02-22 02:45:07 +00007050
John McCall263a48b2010-01-04 23:31:57 +00007051 return;
7052}
7053
David Blaikie18e9ac72012-05-15 21:57:38 +00007054void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7055 SourceLocation CC, QualType T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007056
7057void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00007058 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007059 E = E->IgnoreParenImpCasts();
7060
7061 if (isa<ConditionalOperator>(E))
David Blaikie18e9ac72012-05-15 21:57:38 +00007062 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007063
John McCallacf0ee52010-10-08 02:01:28 +00007064 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007065 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007066 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00007067 return;
7068}
7069
David Blaikie18e9ac72012-05-15 21:57:38 +00007070void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7071 SourceLocation CC, QualType T) {
Richard Trieubd3305b2014-08-07 02:09:05 +00007072 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00007073
7074 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00007075 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7076 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007077
7078 // If -Wconversion would have warned about either of the candidates
7079 // for a signedness conversion to the context type...
7080 if (!Suspicious) return;
7081
7082 // ...but it's currently ignored...
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00007083 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00007084 return;
7085
John McCallcc7e5bf2010-05-06 08:58:33 +00007086 // ...then check whether it would have warned about either of the
7087 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00007088 if (E->getType() == T) return;
7089
7090 Suspicious = false;
7091 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
7092 E->getType(), CC, &Suspicious);
7093 if (!Suspicious)
7094 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00007095 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00007096}
7097
Richard Trieu65724892014-11-15 06:37:39 +00007098/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7099/// Input argument E is a logical expression.
7100static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
7101 if (S.getLangOpts().Bool)
7102 return;
7103 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
7104}
7105
John McCallcc7e5bf2010-05-06 08:58:33 +00007106/// AnalyzeImplicitConversions - Find and report any interesting
7107/// implicit conversions in the given expression. There are a couple
7108/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007109void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
Fariborz Jahanian148c8c82014-04-07 16:32:54 +00007110 QualType T = OrigE->getType();
John McCallcc7e5bf2010-05-06 08:58:33 +00007111 Expr *E = OrigE->IgnoreParenImpCasts();
7112
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00007113 if (E->isTypeDependent() || E->isValueDependent())
7114 return;
Fariborz Jahanianad95da72014-04-04 19:33:39 +00007115
John McCallcc7e5bf2010-05-06 08:58:33 +00007116 // For conditional operators, we analyze the arguments as if they
7117 // were being fed directly into the output.
7118 if (isa<ConditionalOperator>(E)) {
7119 ConditionalOperator *CO = cast<ConditionalOperator>(E);
David Blaikie18e9ac72012-05-15 21:57:38 +00007120 CheckConditionalOperator(S, CO, CC, T);
John McCallcc7e5bf2010-05-06 08:58:33 +00007121 return;
7122 }
7123
Hans Wennborgf4ad2322012-08-28 15:44:30 +00007124 // Check implicit argument conversions for function calls.
7125 if (CallExpr *Call = dyn_cast<CallExpr>(E))
7126 CheckImplicitArgumentConversions(S, Call, CC);
7127
John McCallcc7e5bf2010-05-06 08:58:33 +00007128 // Go ahead and check any implicit conversions we might have skipped.
7129 // The non-canonical typecheck is just an optimization;
7130 // CheckImplicitConversion will filter out dead implicit conversions.
7131 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00007132 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007133
7134 // Now continue drilling into this expression.
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007135
7136 if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007137 if (POE->getResultExpr())
7138 E = POE->getResultExpr();
Fariborz Jahanian2cb4a952013-05-15 19:03:04 +00007139 }
7140
Fariborz Jahanian947efbc2015-02-26 17:59:54 +00007141 if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
7142 if (OVE->getSourceExpr())
7143 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7144 return;
7145 }
Fariborz Jahanian0b11ef22013-05-15 22:25:03 +00007146
John McCallcc7e5bf2010-05-06 08:58:33 +00007147 // Skip past explicit casts.
7148 if (isa<ExplicitCastExpr>(E)) {
7149 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00007150 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007151 }
7152
John McCalld2a53122010-11-09 23:24:47 +00007153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7154 // Do a somewhat different check with comparison operators.
7155 if (BO->isComparisonOp())
7156 return AnalyzeComparison(S, BO);
7157
Timur Iskhodzhanov554bdc62013-03-29 00:22:03 +00007158 // And with simple assignments.
7159 if (BO->getOpcode() == BO_Assign)
John McCalld2a53122010-11-09 23:24:47 +00007160 return AnalyzeAssignment(S, BO);
7161 }
John McCallcc7e5bf2010-05-06 08:58:33 +00007162
7163 // These break the otherwise-useful invariant below. Fortunately,
7164 // we don't really need to recurse into them, because any internal
7165 // expressions should have been analyzed already when they were
7166 // built into statements.
7167 if (isa<StmtExpr>(E)) return;
7168
7169 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00007170 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00007171
7172 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00007173 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00007174 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
Richard Trieu955231d2014-01-25 01:10:35 +00007175 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
Richard Trieu021baa32011-09-23 20:10:00 +00007176 for (Stmt::child_range I = E->children(); I; ++I) {
Douglas Gregor73456262012-02-09 10:18:50 +00007177 Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00007178 if (!ChildExpr)
7179 continue;
7180
Richard Trieu955231d2014-01-25 01:10:35 +00007181 if (IsLogicalAndOperator &&
Richard Trieu021baa32011-09-23 20:10:00 +00007182 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
Richard Trieu955231d2014-01-25 01:10:35 +00007183 // Ignore checking string literals that are in logical and operators.
7184 // This is a common pattern for asserts.
Richard Trieu021baa32011-09-23 20:10:00 +00007185 continue;
7186 AnalyzeImplicitConversions(S, ChildExpr, CC);
7187 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007188
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007189 if (BO && BO->isLogicalOp()) {
Richard Trieu791b86e2014-11-19 06:08:18 +00007190 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
7191 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007192 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Richard Trieu791b86e2014-11-19 06:08:18 +00007193
7194 SubExpr = BO->getRHS()->IgnoreParenImpCasts();
7195 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
Fariborz Jahanian0fc95ad2014-12-18 23:14:51 +00007196 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007197 }
Richard Trieu791b86e2014-11-19 06:08:18 +00007198
Fariborz Jahanianb7859dd2014-11-14 17:12:50 +00007199 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
7200 if (U->getOpcode() == UO_LNot)
Richard Trieu65724892014-11-15 06:37:39 +00007201 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007202}
7203
7204} // end anonymous namespace
7205
Richard Trieu3bb8b562014-02-26 02:36:06 +00007206enum {
7207 AddressOf,
7208 FunctionPointer,
7209 ArrayPointer
7210};
7211
Richard Trieuc1888e02014-06-28 23:25:37 +00007212// Helper function for Sema::DiagnoseAlwaysNonNullPointer.
7213// Returns true when emitting a warning about taking the address of a reference.
7214static bool CheckForReference(Sema &SemaRef, const Expr *E,
7215 PartialDiagnostic PD) {
7216 E = E->IgnoreParenImpCasts();
7217
7218 const FunctionDecl *FD = nullptr;
7219
7220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7221 if (!DRE->getDecl()->getType()->isReferenceType())
7222 return false;
7223 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7224 if (!M->getMemberDecl()->getType()->isReferenceType())
7225 return false;
7226 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
David Majnemerced8bdf2015-02-25 17:36:15 +00007227 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
Richard Trieuc1888e02014-06-28 23:25:37 +00007228 return false;
7229 FD = Call->getDirectCallee();
7230 } else {
7231 return false;
7232 }
7233
7234 SemaRef.Diag(E->getExprLoc(), PD);
7235
7236 // If possible, point to location of function.
7237 if (FD) {
7238 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
7239 }
7240
7241 return true;
7242}
7243
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007244// Returns true if the SourceLocation is expanded from any macro body.
7245// Returns false if the SourceLocation is invalid, is from not in a macro
7246// expansion, or is from expanded from a top-level macro argument.
7247static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
7248 if (Loc.isInvalid())
7249 return false;
7250
7251 while (Loc.isMacroID()) {
7252 if (SM.isMacroBodyExpansion(Loc))
7253 return true;
7254 Loc = SM.getImmediateMacroCallerLoc(Loc);
7255 }
7256
7257 return false;
7258}
7259
Richard Trieu3bb8b562014-02-26 02:36:06 +00007260/// \brief Diagnose pointers that are always non-null.
7261/// \param E the expression containing the pointer
7262/// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
7263/// compared to a null pointer
7264/// \param IsEqual True when the comparison is equal to a null pointer
7265/// \param Range Extra SourceRange to highlight in the diagnostic
7266void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
7267 Expr::NullPointerConstantKind NullKind,
7268 bool IsEqual, SourceRange Range) {
Richard Trieuddd01ce2014-06-09 22:53:25 +00007269 if (!E)
7270 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007271
7272 // Don't warn inside macros.
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007273 if (E->getExprLoc().isMacroID()) {
7274 const SourceManager &SM = getSourceManager();
7275 if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
7276 IsInAnyMacroBody(SM, Range.getBegin()))
Richard Trieu3bb8b562014-02-26 02:36:06 +00007277 return;
Richard Trieu4cbff5c2014-08-08 22:41:43 +00007278 }
Richard Trieu3bb8b562014-02-26 02:36:06 +00007279 E = E->IgnoreImpCasts();
7280
7281 const bool IsCompare = NullKind != Expr::NPCK_NotNull;
7282
Richard Trieuf7432752014-06-06 21:39:26 +00007283 if (isa<CXXThisExpr>(E)) {
7284 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7285 : diag::warn_this_bool_conversion;
7286 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7287 return;
7288 }
7289
Richard Trieu3bb8b562014-02-26 02:36:06 +00007290 bool IsAddressOf = false;
7291
7292 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7293 if (UO->getOpcode() != UO_AddrOf)
7294 return;
7295 IsAddressOf = true;
7296 E = UO->getSubExpr();
7297 }
7298
Richard Trieuc1888e02014-06-28 23:25:37 +00007299 if (IsAddressOf) {
7300 unsigned DiagID = IsCompare
7301 ? diag::warn_address_of_reference_null_compare
7302 : diag::warn_address_of_reference_bool_conversion;
7303 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
7304 << IsEqual;
7305 if (CheckForReference(*this, E, PD)) {
7306 return;
7307 }
7308 }
7309
Richard Trieu3bb8b562014-02-26 02:36:06 +00007310 // Expect to find a single Decl. Skip anything more complicated.
Craig Topperc3ec1492014-05-26 06:22:03 +00007311 ValueDecl *D = nullptr;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007312 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
7313 D = R->getDecl();
7314 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7315 D = M->getMemberDecl();
7316 }
7317
7318 // Weak Decls can be null.
7319 if (!D || D->isWeak())
7320 return;
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007321
7322 // Check for parameter decl with nonnull attribute
7323 if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7324 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7325 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7326 unsigned NumArgs = FD->getNumParams();
7327 llvm::SmallBitVector AttrNonNull(NumArgs);
7328 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
7329 if (!NonNull->args_size()) {
7330 AttrNonNull.set(0, NumArgs);
7331 break;
7332 }
7333 for (unsigned Val : NonNull->args()) {
7334 if (Val >= NumArgs)
7335 continue;
7336 AttrNonNull.set(Val);
7337 }
7338 }
7339 if (!AttrNonNull.empty())
7340 for (unsigned i = 0; i < NumArgs; ++i)
Aaron Ballman2521f362014-12-11 19:35:42 +00007341 if (FD->getParamDecl(i) == PV &&
7342 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
Fariborz Jahanianef202d92014-11-18 21:57:54 +00007343 std::string Str;
7344 llvm::raw_string_ostream S(Str);
7345 E->printPretty(S, nullptr, getPrintingPolicy());
7346 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7347 : diag::warn_cast_nonnull_to_bool;
7348 Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
7349 << Range << IsEqual;
7350 return;
7351 }
7352 }
7353 }
7354
Richard Trieu3bb8b562014-02-26 02:36:06 +00007355 QualType T = D->getType();
7356 const bool IsArray = T->isArrayType();
7357 const bool IsFunction = T->isFunctionType();
7358
Richard Trieuc1888e02014-06-28 23:25:37 +00007359 // Address of function is used to silence the function warning.
7360 if (IsAddressOf && IsFunction) {
7361 return;
Richard Trieu3bb8b562014-02-26 02:36:06 +00007362 }
7363
7364 // Found nothing.
7365 if (!IsAddressOf && !IsFunction && !IsArray)
7366 return;
7367
7368 // Pretty print the expression for the diagnostic.
7369 std::string Str;
7370 llvm::raw_string_ostream S(Str);
Craig Topperc3ec1492014-05-26 06:22:03 +00007371 E->printPretty(S, nullptr, getPrintingPolicy());
Richard Trieu3bb8b562014-02-26 02:36:06 +00007372
7373 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7374 : diag::warn_impcast_pointer_to_bool;
7375 unsigned DiagType;
7376 if (IsAddressOf)
7377 DiagType = AddressOf;
7378 else if (IsFunction)
7379 DiagType = FunctionPointer;
7380 else if (IsArray)
7381 DiagType = ArrayPointer;
7382 else
7383 llvm_unreachable("Could not determine diagnostic.");
7384 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7385 << Range << IsEqual;
7386
7387 if (!IsFunction)
7388 return;
7389
7390 // Suggest '&' to silence the function warning.
7391 Diag(E->getExprLoc(), diag::note_function_warning_silence)
7392 << FixItHint::CreateInsertion(E->getLocStart(), "&");
7393
7394 // Check to see if '()' fixit should be emitted.
7395 QualType ReturnType;
7396 UnresolvedSet<4> NonTemplateOverloads;
7397 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7398 if (ReturnType.isNull())
7399 return;
7400
7401 if (IsCompare) {
7402 // There are two cases here. If there is null constant, the only suggest
7403 // for a pointer return type. If the null is 0, then suggest if the return
7404 // type is a pointer or an integer type.
7405 if (!ReturnType->isPointerType()) {
7406 if (NullKind == Expr::NPCK_ZeroExpression ||
7407 NullKind == Expr::NPCK_ZeroLiteral) {
7408 if (!ReturnType->isIntegerType())
7409 return;
7410 } else {
7411 return;
7412 }
7413 }
7414 } else { // !IsCompare
7415 // For function to bool, only suggest if the function pointer has bool
7416 // return type.
7417 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7418 return;
7419 }
7420 Diag(E->getExprLoc(), diag::note_function_to_function_call)
Alp Tokerb6cc5922014-05-03 03:45:55 +00007421 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
Richard Trieu3bb8b562014-02-26 02:36:06 +00007422}
7423
7424
John McCallcc7e5bf2010-05-06 08:58:33 +00007425/// Diagnoses "dangerous" implicit conversions within the given
7426/// expression (which is a full expression). Implements -Wconversion
7427/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00007428///
7429/// \param CC the "context" location of the implicit conversion, i.e.
7430/// the most location of the syntactic entity requiring the implicit
7431/// conversion
7432void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00007433 // Don't diagnose in unevaluated contexts.
David Blaikie131fcb42012-08-06 22:47:24 +00007434 if (isUnevaluatedContext())
John McCallcc7e5bf2010-05-06 08:58:33 +00007435 return;
7436
7437 // Don't diagnose for value- or type-dependent expressions.
7438 if (E->isTypeDependent() || E->isValueDependent())
7439 return;
7440
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007441 // Check for array bounds violations in cases where the check isn't triggered
7442 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7443 // ArraySubscriptExpr is on the RHS of a variable initialization.
7444 CheckArrayAccess(E);
7445
John McCallacf0ee52010-10-08 02:01:28 +00007446 // This is not the right CC for (e.g.) a variable initialization.
7447 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00007448}
7449
Richard Trieu65724892014-11-15 06:37:39 +00007450/// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7451/// Input argument E is a logical expression.
7452void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7453 ::CheckBoolLikeConversion(*this, E, CC);
7454}
7455
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007456/// Diagnose when expression is an integer constant expression and its evaluation
7457/// results in integer overflow
7458void Sema::CheckForIntOverflow (Expr *E) {
Fariborz Jahanianc694e692014-10-14 20:27:05 +00007459 if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7460 E->IgnoreParenCasts()->EvaluateForOverflow(Context);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007461}
7462
Richard Smithc406cb72013-01-17 01:17:56 +00007463namespace {
7464/// \brief Visitor for expressions which looks for unsequenced operations on the
7465/// same object.
7466class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007467 typedef EvaluatedExprVisitor<SequenceChecker> Base;
7468
Richard Smithc406cb72013-01-17 01:17:56 +00007469 /// \brief A tree of sequenced regions within an expression. Two regions are
7470 /// unsequenced if one is an ancestor or a descendent of the other. When we
7471 /// finish processing an expression with sequencing, such as a comma
7472 /// expression, we fold its tree nodes into its parent, since they are
7473 /// unsequenced with respect to nodes we will visit later.
7474 class SequenceTree {
7475 struct Value {
7476 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7477 unsigned Parent : 31;
7478 bool Merged : 1;
7479 };
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007480 SmallVector<Value, 8> Values;
Richard Smithc406cb72013-01-17 01:17:56 +00007481
7482 public:
7483 /// \brief A region within an expression which may be sequenced with respect
7484 /// to some other region.
7485 class Seq {
7486 explicit Seq(unsigned N) : Index(N) {}
7487 unsigned Index;
7488 friend class SequenceTree;
7489 public:
7490 Seq() : Index(0) {}
7491 };
7492
7493 SequenceTree() { Values.push_back(Value(0)); }
7494 Seq root() const { return Seq(0); }
7495
7496 /// \brief Create a new sequence of operations, which is an unsequenced
7497 /// subset of \p Parent. This sequence of operations is sequenced with
7498 /// respect to other children of \p Parent.
7499 Seq allocate(Seq Parent) {
7500 Values.push_back(Value(Parent.Index));
7501 return Seq(Values.size() - 1);
7502 }
7503
7504 /// \brief Merge a sequence of operations into its parent.
7505 void merge(Seq S) {
7506 Values[S.Index].Merged = true;
7507 }
7508
7509 /// \brief Determine whether two operations are unsequenced. This operation
7510 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7511 /// should have been merged into its parent as appropriate.
7512 bool isUnsequenced(Seq Cur, Seq Old) {
7513 unsigned C = representative(Cur.Index);
7514 unsigned Target = representative(Old.Index);
7515 while (C >= Target) {
7516 if (C == Target)
7517 return true;
7518 C = Values[C].Parent;
7519 }
7520 return false;
7521 }
7522
7523 private:
7524 /// \brief Pick a representative for a sequence.
7525 unsigned representative(unsigned K) {
7526 if (Values[K].Merged)
7527 // Perform path compression as we go.
7528 return Values[K].Parent = representative(Values[K].Parent);
7529 return K;
7530 }
7531 };
7532
7533 /// An object for which we can track unsequenced uses.
7534 typedef NamedDecl *Object;
7535
7536 /// Different flavors of object usage which we track. We only track the
7537 /// least-sequenced usage of each kind.
7538 enum UsageKind {
7539 /// A read of an object. Multiple unsequenced reads are OK.
7540 UK_Use,
7541 /// A modification of an object which is sequenced before the value
Richard Smith83e37bee2013-06-26 23:16:51 +00007542 /// computation of the expression, such as ++n in C++.
Richard Smithc406cb72013-01-17 01:17:56 +00007543 UK_ModAsValue,
7544 /// A modification of an object which is not sequenced before the value
7545 /// computation of the expression, such as n++.
7546 UK_ModAsSideEffect,
7547
7548 UK_Count = UK_ModAsSideEffect + 1
7549 };
7550
7551 struct Usage {
Craig Topperc3ec1492014-05-26 06:22:03 +00007552 Usage() : Use(nullptr), Seq() {}
Richard Smithc406cb72013-01-17 01:17:56 +00007553 Expr *Use;
7554 SequenceTree::Seq Seq;
7555 };
7556
7557 struct UsageInfo {
7558 UsageInfo() : Diagnosed(false) {}
7559 Usage Uses[UK_Count];
7560 /// Have we issued a diagnostic for this variable already?
7561 bool Diagnosed;
7562 };
7563 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7564
7565 Sema &SemaRef;
7566 /// Sequenced regions within the expression.
7567 SequenceTree Tree;
7568 /// Declaration modifications and references which we have seen.
7569 UsageInfoMap UsageMap;
7570 /// The region we are currently within.
7571 SequenceTree::Seq Region;
7572 /// Filled in with declarations which were modified as a side-effect
7573 /// (that is, post-increment operations).
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007574 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
Richard Smithd33f5202013-01-17 23:18:09 +00007575 /// Expressions to check later. We defer checking these to reduce
7576 /// stack usage.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007577 SmallVectorImpl<Expr *> &WorkList;
Richard Smithc406cb72013-01-17 01:17:56 +00007578
7579 /// RAII object wrapping the visitation of a sequenced subexpression of an
7580 /// expression. At the end of this process, the side-effects of the evaluation
7581 /// become sequenced with respect to the value computation of the result, so
7582 /// we downgrade any UK_ModAsSideEffect within the evaluation to
7583 /// UK_ModAsValue.
7584 struct SequencedSubexpression {
7585 SequencedSubexpression(SequenceChecker &Self)
7586 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7587 Self.ModAsSideEffect = &ModAsSideEffect;
7588 }
7589 ~SequencedSubexpression() {
Richard Smithe8efd992014-12-03 01:05:50 +00007590 for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7591 MI != ME; ++MI) {
7592 UsageInfo &U = Self.UsageMap[MI->first];
7593 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7594 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7595 SideEffectUsage = MI->second;
Richard Smithc406cb72013-01-17 01:17:56 +00007596 }
7597 Self.ModAsSideEffect = OldModAsSideEffect;
7598 }
7599
7600 SequenceChecker &Self;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007601 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7602 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
Richard Smithc406cb72013-01-17 01:17:56 +00007603 };
7604
Richard Smith40238f02013-06-20 22:21:56 +00007605 /// RAII object wrapping the visitation of a subexpression which we might
7606 /// choose to evaluate as a constant. If any subexpression is evaluated and
7607 /// found to be non-constant, this allows us to suppress the evaluation of
7608 /// the outer expression.
7609 class EvaluationTracker {
7610 public:
7611 EvaluationTracker(SequenceChecker &Self)
7612 : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7613 Self.EvalTracker = this;
7614 }
7615 ~EvaluationTracker() {
7616 Self.EvalTracker = Prev;
7617 if (Prev)
7618 Prev->EvalOK &= EvalOK;
7619 }
7620
7621 bool evaluate(const Expr *E, bool &Result) {
7622 if (!EvalOK || E->isValueDependent())
7623 return false;
7624 EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7625 return EvalOK;
7626 }
7627
7628 private:
7629 SequenceChecker &Self;
7630 EvaluationTracker *Prev;
7631 bool EvalOK;
7632 } *EvalTracker;
7633
Richard Smithc406cb72013-01-17 01:17:56 +00007634 /// \brief Find the object which is produced by the specified expression,
7635 /// if any.
7636 Object getObject(Expr *E, bool Mod) const {
7637 E = E->IgnoreParenCasts();
7638 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7639 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7640 return getObject(UO->getSubExpr(), Mod);
7641 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7642 if (BO->getOpcode() == BO_Comma)
7643 return getObject(BO->getRHS(), Mod);
7644 if (Mod && BO->isAssignmentOp())
7645 return getObject(BO->getLHS(), Mod);
7646 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7647 // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7648 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7649 return ME->getMemberDecl();
7650 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7651 // FIXME: If this is a reference, map through to its value.
7652 return DRE->getDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00007653 return nullptr;
Richard Smithc406cb72013-01-17 01:17:56 +00007654 }
7655
7656 /// \brief Note that an object was modified or used by an expression.
7657 void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7658 Usage &U = UI.Uses[UK];
7659 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7660 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7661 ModAsSideEffect->push_back(std::make_pair(O, U));
7662 U.Use = Ref;
7663 U.Seq = Region;
7664 }
7665 }
7666 /// \brief Check whether a modification or use conflicts with a prior usage.
7667 void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7668 bool IsModMod) {
7669 if (UI.Diagnosed)
7670 return;
7671
7672 const Usage &U = UI.Uses[OtherKind];
7673 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7674 return;
7675
7676 Expr *Mod = U.Use;
7677 Expr *ModOrUse = Ref;
7678 if (OtherKind == UK_Use)
7679 std::swap(Mod, ModOrUse);
7680
7681 SemaRef.Diag(Mod->getExprLoc(),
7682 IsModMod ? diag::warn_unsequenced_mod_mod
7683 : diag::warn_unsequenced_mod_use)
7684 << O << SourceRange(ModOrUse->getExprLoc());
7685 UI.Diagnosed = true;
7686 }
7687
7688 void notePreUse(Object O, Expr *Use) {
7689 UsageInfo &U = UsageMap[O];
7690 // Uses conflict with other modifications.
7691 checkUsage(O, U, Use, UK_ModAsValue, false);
7692 }
7693 void notePostUse(Object O, Expr *Use) {
7694 UsageInfo &U = UsageMap[O];
7695 checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7696 addUsage(U, O, Use, UK_Use);
7697 }
7698
7699 void notePreMod(Object O, Expr *Mod) {
7700 UsageInfo &U = UsageMap[O];
7701 // Modifications conflict with other modifications and with uses.
7702 checkUsage(O, U, Mod, UK_ModAsValue, true);
7703 checkUsage(O, U, Mod, UK_Use, false);
7704 }
7705 void notePostMod(Object O, Expr *Use, UsageKind UK) {
7706 UsageInfo &U = UsageMap[O];
7707 checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7708 addUsage(U, O, Use, UK);
7709 }
7710
7711public:
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007712 SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
Craig Topperc3ec1492014-05-26 06:22:03 +00007713 : Base(S.Context), SemaRef(S), Region(Tree.root()),
7714 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007715 Visit(E);
7716 }
7717
7718 void VisitStmt(Stmt *S) {
7719 // Skip all statements which aren't expressions for now.
7720 }
7721
7722 void VisitExpr(Expr *E) {
7723 // By default, just recurse to evaluated subexpressions.
Richard Smithe3dbfe02013-06-30 10:40:20 +00007724 Base::VisitStmt(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007725 }
7726
7727 void VisitCastExpr(CastExpr *E) {
7728 Object O = Object();
7729 if (E->getCastKind() == CK_LValueToRValue)
7730 O = getObject(E->getSubExpr(), false);
7731
7732 if (O)
7733 notePreUse(O, E);
7734 VisitExpr(E);
7735 if (O)
7736 notePostUse(O, E);
7737 }
7738
7739 void VisitBinComma(BinaryOperator *BO) {
7740 // C++11 [expr.comma]p1:
7741 // Every value computation and side effect associated with the left
7742 // expression is sequenced before every value computation and side
7743 // effect associated with the right expression.
7744 SequenceTree::Seq LHS = Tree.allocate(Region);
7745 SequenceTree::Seq RHS = Tree.allocate(Region);
7746 SequenceTree::Seq OldRegion = Region;
7747
7748 {
7749 SequencedSubexpression SeqLHS(*this);
7750 Region = LHS;
7751 Visit(BO->getLHS());
7752 }
7753
7754 Region = RHS;
7755 Visit(BO->getRHS());
7756
7757 Region = OldRegion;
7758
7759 // Forget that LHS and RHS are sequenced. They are both unsequenced
7760 // with respect to other stuff.
7761 Tree.merge(LHS);
7762 Tree.merge(RHS);
7763 }
7764
7765 void VisitBinAssign(BinaryOperator *BO) {
7766 // The modification is sequenced after the value computation of the LHS
7767 // and RHS, so check it before inspecting the operands and update the
7768 // map afterwards.
7769 Object O = getObject(BO->getLHS(), true);
7770 if (!O)
7771 return VisitExpr(BO);
7772
7773 notePreMod(O, BO);
7774
7775 // C++11 [expr.ass]p7:
7776 // E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7777 // only once.
7778 //
7779 // Therefore, for a compound assignment operator, O is considered used
7780 // everywhere except within the evaluation of E1 itself.
7781 if (isa<CompoundAssignOperator>(BO))
7782 notePreUse(O, BO);
7783
7784 Visit(BO->getLHS());
7785
7786 if (isa<CompoundAssignOperator>(BO))
7787 notePostUse(O, BO);
7788
7789 Visit(BO->getRHS());
7790
Richard Smith83e37bee2013-06-26 23:16:51 +00007791 // C++11 [expr.ass]p1:
7792 // the assignment is sequenced [...] before the value computation of the
7793 // assignment expression.
7794 // C11 6.5.16/3 has no such rule.
7795 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7796 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007797 }
7798 void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7799 VisitBinAssign(CAO);
7800 }
7801
7802 void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7803 void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7804 void VisitUnaryPreIncDec(UnaryOperator *UO) {
7805 Object O = getObject(UO->getSubExpr(), true);
7806 if (!O)
7807 return VisitExpr(UO);
7808
7809 notePreMod(O, UO);
7810 Visit(UO->getSubExpr());
Richard Smith83e37bee2013-06-26 23:16:51 +00007811 // C++11 [expr.pre.incr]p1:
7812 // the expression ++x is equivalent to x+=1
7813 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7814 : UK_ModAsSideEffect);
Richard Smithc406cb72013-01-17 01:17:56 +00007815 }
7816
7817 void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7818 void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7819 void VisitUnaryPostIncDec(UnaryOperator *UO) {
7820 Object O = getObject(UO->getSubExpr(), true);
7821 if (!O)
7822 return VisitExpr(UO);
7823
7824 notePreMod(O, UO);
7825 Visit(UO->getSubExpr());
7826 notePostMod(O, UO, UK_ModAsSideEffect);
7827 }
7828
7829 /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7830 void VisitBinLOr(BinaryOperator *BO) {
7831 // The side-effects of the LHS of an '&&' are sequenced before the
7832 // value computation of the RHS, and hence before the value computation
7833 // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7834 // as if they were unconditionally sequenced.
Richard Smith40238f02013-06-20 22:21:56 +00007835 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007836 {
7837 SequencedSubexpression Sequenced(*this);
7838 Visit(BO->getLHS());
7839 }
7840
7841 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007842 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007843 if (!Result)
7844 Visit(BO->getRHS());
7845 } else {
7846 // Check for unsequenced operations in the RHS, treating it as an
7847 // entirely separate evaluation.
7848 //
7849 // FIXME: If there are operations in the RHS which are unsequenced
7850 // with respect to operations outside the RHS, and those operations
7851 // are unconditionally evaluated, diagnose them.
Richard Smithd33f5202013-01-17 23:18:09 +00007852 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007853 }
Richard Smithc406cb72013-01-17 01:17:56 +00007854 }
7855 void VisitBinLAnd(BinaryOperator *BO) {
Richard Smith40238f02013-06-20 22:21:56 +00007856 EvaluationTracker Eval(*this);
Richard Smithc406cb72013-01-17 01:17:56 +00007857 {
7858 SequencedSubexpression Sequenced(*this);
7859 Visit(BO->getLHS());
7860 }
7861
7862 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007863 if (Eval.evaluate(BO->getLHS(), Result)) {
Richard Smith01a7fba2013-01-17 22:06:26 +00007864 if (Result)
7865 Visit(BO->getRHS());
7866 } else {
Richard Smithd33f5202013-01-17 23:18:09 +00007867 WorkList.push_back(BO->getRHS());
Richard Smith01a7fba2013-01-17 22:06:26 +00007868 }
Richard Smithc406cb72013-01-17 01:17:56 +00007869 }
7870
7871 // Only visit the condition, unless we can be sure which subexpression will
7872 // be chosen.
7873 void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
Richard Smith40238f02013-06-20 22:21:56 +00007874 EvaluationTracker Eval(*this);
Richard Smith83e37bee2013-06-26 23:16:51 +00007875 {
7876 SequencedSubexpression Sequenced(*this);
7877 Visit(CO->getCond());
7878 }
Richard Smithc406cb72013-01-17 01:17:56 +00007879
7880 bool Result;
Richard Smith40238f02013-06-20 22:21:56 +00007881 if (Eval.evaluate(CO->getCond(), Result))
Richard Smithc406cb72013-01-17 01:17:56 +00007882 Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007883 else {
Richard Smithd33f5202013-01-17 23:18:09 +00007884 WorkList.push_back(CO->getTrueExpr());
7885 WorkList.push_back(CO->getFalseExpr());
Richard Smith01a7fba2013-01-17 22:06:26 +00007886 }
Richard Smithc406cb72013-01-17 01:17:56 +00007887 }
7888
Richard Smithe3dbfe02013-06-30 10:40:20 +00007889 void VisitCallExpr(CallExpr *CE) {
7890 // C++11 [intro.execution]p15:
7891 // When calling a function [...], every value computation and side effect
7892 // associated with any argument expression, or with the postfix expression
7893 // designating the called function, is sequenced before execution of every
7894 // expression or statement in the body of the function [and thus before
7895 // the value computation of its result].
7896 SequencedSubexpression Sequenced(*this);
7897 Base::VisitCallExpr(CE);
7898
7899 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7900 }
7901
Richard Smithc406cb72013-01-17 01:17:56 +00007902 void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
Richard Smithe3dbfe02013-06-30 10:40:20 +00007903 // This is a call, so all subexpressions are sequenced before the result.
7904 SequencedSubexpression Sequenced(*this);
7905
Richard Smithc406cb72013-01-17 01:17:56 +00007906 if (!CCE->isListInitialization())
7907 return VisitExpr(CCE);
7908
7909 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007910 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007911 SequenceTree::Seq Parent = Region;
7912 for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7913 E = CCE->arg_end();
7914 I != E; ++I) {
7915 Region = Tree.allocate(Parent);
7916 Elts.push_back(Region);
7917 Visit(*I);
7918 }
7919
7920 // Forget that the initializers are sequenced.
7921 Region = Parent;
7922 for (unsigned I = 0; I < Elts.size(); ++I)
7923 Tree.merge(Elts[I]);
7924 }
7925
7926 void VisitInitListExpr(InitListExpr *ILE) {
7927 if (!SemaRef.getLangOpts().CPlusPlus11)
7928 return VisitExpr(ILE);
7929
7930 // In C++11, list initializations are sequenced.
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007931 SmallVector<SequenceTree::Seq, 32> Elts;
Richard Smithc406cb72013-01-17 01:17:56 +00007932 SequenceTree::Seq Parent = Region;
7933 for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7934 Expr *E = ILE->getInit(I);
7935 if (!E) continue;
7936 Region = Tree.allocate(Parent);
7937 Elts.push_back(Region);
7938 Visit(E);
7939 }
7940
7941 // Forget that the initializers are sequenced.
7942 Region = Parent;
7943 for (unsigned I = 0; I < Elts.size(); ++I)
7944 Tree.merge(Elts[I]);
7945 }
7946};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007947}
Richard Smithc406cb72013-01-17 01:17:56 +00007948
7949void Sema::CheckUnsequencedOperations(Expr *E) {
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00007950 SmallVector<Expr *, 8> WorkList;
Richard Smithd33f5202013-01-17 23:18:09 +00007951 WorkList.push_back(E);
7952 while (!WorkList.empty()) {
Robert Wilhelm25284cc2013-08-23 16:11:15 +00007953 Expr *Item = WorkList.pop_back_val();
Richard Smithd33f5202013-01-17 23:18:09 +00007954 SequenceChecker(*this, Item, WorkList);
7955 }
Richard Smithc406cb72013-01-17 01:17:56 +00007956}
7957
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007958void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7959 bool IsConstexpr) {
Richard Smithc406cb72013-01-17 01:17:56 +00007960 CheckImplicitConversions(E, CheckLoc);
7961 CheckUnsequencedOperations(E);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00007962 if (!IsConstexpr && !E->isValueDependent())
7963 CheckForIntOverflow(E);
Richard Smithc406cb72013-01-17 01:17:56 +00007964}
7965
John McCall1f425642010-11-11 03:21:53 +00007966void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7967 FieldDecl *BitField,
7968 Expr *Init) {
7969 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7970}
7971
David Majnemer61a5bbf2015-04-07 22:08:51 +00007972static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
7973 SourceLocation Loc) {
7974 if (!PType->isVariablyModifiedType())
7975 return;
7976 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
7977 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
7978 return;
7979 }
David Majnemerdf8f73f2015-04-09 19:53:25 +00007980 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
7981 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
7982 return;
7983 }
David Majnemer61a5bbf2015-04-07 22:08:51 +00007984 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
7985 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
7986 return;
7987 }
7988
7989 const ArrayType *AT = S.Context.getAsArrayType(PType);
7990 if (!AT)
7991 return;
7992
7993 if (AT->getSizeModifier() != ArrayType::Star) {
7994 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
7995 return;
7996 }
7997
7998 S.Diag(Loc, diag::err_array_star_in_function_definition);
7999}
8000
Mike Stump0c2ec772010-01-21 03:59:47 +00008001/// CheckParmsForFunctionDef - Check that the parameters of the given
8002/// function are appropriate for the definition of a function. This
8003/// takes care of any checks that cannot be performed on the
8004/// declaration itself, e.g., that the types of each of the function
8005/// parameters are complete.
Reid Kleckner5a115802013-06-24 14:38:26 +00008006bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8007 ParmVarDecl *const *PEnd,
Douglas Gregorb524d902010-11-01 18:37:59 +00008008 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008009 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00008010 for (; P != PEnd; ++P) {
8011 ParmVarDecl *Param = *P;
8012
Mike Stump0c2ec772010-01-21 03:59:47 +00008013 // C99 6.7.5.3p4: the parameters in a parameter type list in a
8014 // function declarator that is part of a function definition of
8015 // that function shall not have incomplete type.
8016 //
8017 // This is also C++ [dcl.fct]p6.
8018 if (!Param->isInvalidDecl() &&
8019 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008020 diag::err_typecheck_decl_incomplete_type)) {
Mike Stump0c2ec772010-01-21 03:59:47 +00008021 Param->setInvalidDecl();
8022 HasInvalidParm = true;
8023 }
8024
8025 // C99 6.9.1p5: If the declarator includes a parameter type list, the
8026 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00008027 if (CheckParameterNames &&
Craig Topperc3ec1492014-05-26 06:22:03 +00008028 Param->getIdentifier() == nullptr &&
Mike Stump0c2ec772010-01-21 03:59:47 +00008029 !Param->isImplicit() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008030 !getLangOpts().CPlusPlus)
Mike Stump0c2ec772010-01-21 03:59:47 +00008031 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00008032
8033 // C99 6.7.5.3p12:
8034 // If the function declarator is not part of a definition of that
8035 // function, parameters may have incomplete type and may use the [*]
8036 // notation in their sequences of declarator specifiers to specify
8037 // variable length array types.
8038 QualType PType = Param->getOriginalType();
David Majnemer61a5bbf2015-04-07 22:08:51 +00008039 // FIXME: This diagnostic should point the '[*]' if source-location
8040 // information is added for it.
8041 diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008042
8043 // MSVC destroys objects passed by value in the callee. Therefore a
8044 // function definition which takes such a parameter must be able to call the
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008045 // object's destructor. However, we don't perform any direct access check
8046 // on the dtor.
Reid Kleckner739756c2013-12-04 19:23:12 +00008047 if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8048 .getCXXABI()
8049 .areArgsDestroyedLeftToRightInCallee()) {
Hans Wennborg13ac4bd2014-01-13 19:24:31 +00008050 if (!Param->isInvalidDecl()) {
8051 if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8052 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8053 if (!ClassDecl->isInvalidDecl() &&
8054 !ClassDecl->hasIrrelevantDestructor() &&
8055 !ClassDecl->isDependentContext()) {
8056 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8057 MarkFunctionReferenced(Param->getLocation(), Destructor);
8058 DiagnoseUseOfDecl(Destructor, Param->getLocation());
8059 }
Hans Wennborg0f3c10c2014-01-13 17:23:24 +00008060 }
8061 }
Reid Kleckner23f4c4b2013-06-21 12:45:15 +00008062 }
Mike Stump0c2ec772010-01-21 03:59:47 +00008063 }
8064
8065 return HasInvalidParm;
8066}
John McCall2b5c1b22010-08-12 21:44:57 +00008067
8068/// CheckCastAlign - Implements -Wcast-align, which warns when a
8069/// pointer cast increases the alignment requirements.
8070void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
8071 // This is actually a lot of work to potentially be doing on every
8072 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008073 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
John McCall2b5c1b22010-08-12 21:44:57 +00008074 return;
8075
8076 // Ignore dependent types.
8077 if (T->isDependentType() || Op->getType()->isDependentType())
8078 return;
8079
8080 // Require that the destination be a pointer type.
8081 const PointerType *DestPtr = T->getAs<PointerType>();
8082 if (!DestPtr) return;
8083
8084 // If the destination has alignment 1, we're done.
8085 QualType DestPointee = DestPtr->getPointeeType();
8086 if (DestPointee->isIncompleteType()) return;
8087 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
8088 if (DestAlign.isOne()) return;
8089
8090 // Require that the source be a pointer type.
8091 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
8092 if (!SrcPtr) return;
8093 QualType SrcPointee = SrcPtr->getPointeeType();
8094
8095 // Whitelist casts from cv void*. We already implicitly
8096 // whitelisted casts to cv void*, since they have alignment 1.
8097 // Also whitelist casts involving incomplete types, which implicitly
8098 // includes 'void'.
8099 if (SrcPointee->isIncompleteType()) return;
8100
8101 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
8102 if (SrcAlign >= DestAlign) return;
8103
8104 Diag(TRange.getBegin(), diag::warn_cast_align)
8105 << Op->getType() << T
8106 << static_cast<unsigned>(SrcAlign.getQuantity())
8107 << static_cast<unsigned>(DestAlign.getQuantity())
8108 << TRange << Op->getSourceRange();
8109}
8110
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008111static const Type* getElementType(const Expr *BaseExpr) {
8112 const Type* EltType = BaseExpr->getType().getTypePtr();
8113 if (EltType->isAnyPointerType())
8114 return EltType->getPointeeType().getTypePtr();
8115 else if (EltType->isArrayType())
8116 return EltType->getBaseElementTypeUnsafe();
8117 return EltType;
8118}
8119
Chandler Carruth28389f02011-08-05 09:10:50 +00008120/// \brief Check whether this array fits the idiom of a size-one tail padded
8121/// array member of a struct.
8122///
8123/// We avoid emitting out-of-bounds access warnings for such arrays as they are
8124/// commonly used to emulate flexible arrays in C89 code.
8125static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
8126 const NamedDecl *ND) {
8127 if (Size != 1 || !ND) return false;
8128
8129 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
8130 if (!FD) return false;
8131
8132 // Don't consider sizes resulting from macro expansions or template argument
8133 // substitution to form C89 tail-padded arrays.
Sean Callanan06a48a62012-05-04 18:22:53 +00008134
8135 TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008136 while (TInfo) {
8137 TypeLoc TL = TInfo->getTypeLoc();
8138 // Look through typedefs.
David Blaikie6adc78e2013-02-18 22:06:02 +00008139 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
8140 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008141 TInfo = TDL->getTypeSourceInfo();
8142 continue;
8143 }
David Blaikie6adc78e2013-02-18 22:06:02 +00008144 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
8145 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
Chad Rosier70299922013-02-06 00:58:34 +00008146 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
8147 return false;
8148 }
Ted Kremenek7ebb4932012-05-09 05:35:08 +00008149 break;
Sean Callanan06a48a62012-05-04 18:22:53 +00008150 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008151
8152 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
Matt Beaumont-Gayc93b4892011-11-29 22:43:53 +00008153 if (!RD) return false;
8154 if (RD->isUnion()) return false;
8155 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8156 if (!CRD->isStandardLayout()) return false;
8157 }
Chandler Carruth28389f02011-08-05 09:10:50 +00008158
Benjamin Kramer8c543672011-08-06 03:04:42 +00008159 // See if this is the last field decl in the record.
8160 const Decl *D = FD;
8161 while ((D = D->getNextDeclInContext()))
8162 if (isa<FieldDecl>(D))
8163 return false;
8164 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00008165}
8166
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008167void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008168 const ArraySubscriptExpr *ASE,
Richard Smith13f67182011-12-16 19:31:14 +00008169 bool AllowOnePastEnd, bool IndexNegated) {
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008170 IndexExpr = IndexExpr->IgnoreParenImpCasts();
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008171 if (IndexExpr->isValueDependent())
8172 return;
8173
Matt Beaumont-Gay9d570c42011-12-12 22:35:02 +00008174 const Type *EffectiveType = getElementType(BaseExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008175 BaseExpr = BaseExpr->IgnoreParenCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008176 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008177 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008178 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00008179 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00008180
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008181 llvm::APSInt index;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008182 if (!IndexExpr->EvaluateAsInt(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00008183 return;
Richard Smith13f67182011-12-16 19:31:14 +00008184 if (IndexNegated)
8185 index = -index;
Ted Kremenek108b2d52011-02-16 04:01:44 +00008186
Craig Topperc3ec1492014-05-26 06:22:03 +00008187 const NamedDecl *ND = nullptr;
Chandler Carruth126b1552011-08-05 08:07:29 +00008188 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8189 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00008190 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00008191 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00008192
Ted Kremeneke4b316c2011-02-23 23:06:04 +00008193 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008194 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00008195 if (!size.isStrictlyPositive())
8196 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008197
8198 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00008199 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008200 // Make sure we're comparing apples to apples when comparing index to size
8201 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
8202 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00008203 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00008204 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008205 if (ptrarith_typesize != array_typesize) {
8206 // There's a cast to a different size type involved
8207 uint64_t ratio = array_typesize / ptrarith_typesize;
8208 // TODO: Be smarter about handling cases where array_typesize is not a
8209 // multiple of ptrarith_typesize
8210 if (ptrarith_typesize * ratio == array_typesize)
8211 size *= llvm::APInt(size.getBitWidth(), ratio);
8212 }
8213 }
8214
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008215 if (size.getBitWidth() > index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008216 index = index.zext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008217 else if (size.getBitWidth() < index.getBitWidth())
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008218 size = size.zext(index.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00008219
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008220 // For array subscripting the index must be less than size, but for pointer
8221 // arithmetic also allow the index (offset) to be equal to size since
8222 // computing the next address after the end of the array is legal and
8223 // commonly done e.g. in C++ iterators and range-based for loops.
Eli Friedman84e6e5c2012-02-27 21:21:40 +00008224 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00008225 return;
8226
8227 // Also don't warn for arrays of size 1 which are members of some
8228 // structure. These are often used to approximate flexible arrays in C89
8229 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008230 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00008231 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008232
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008233 // Suppress the warning if the subscript expression (as identified by the
8234 // ']' location) and the index expression are both from macro expansions
8235 // within a system header.
8236 if (ASE) {
8237 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
8238 ASE->getRBracketLoc());
8239 if (SourceMgr.isInSystemHeader(RBracketLoc)) {
8240 SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
8241 IndexExpr->getLocStart());
Eli Friedman5ba37d52013-08-22 00:27:10 +00008242 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008243 return;
8244 }
8245 }
8246
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008247 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008248 if (ASE)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008249 DiagID = diag::warn_array_index_exceeds_bounds;
8250
8251 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8252 PDiag(DiagID) << index.toString(10, true)
8253 << size.toString(10, true)
8254 << (unsigned)size.getLimitedValue(~0U)
8255 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00008256 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008257 unsigned DiagID = diag::warn_array_index_precedes_bounds;
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008258 if (!ASE) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008259 DiagID = diag::warn_ptr_arith_precedes_bounds;
8260 if (index.isNegative()) index = -index;
8261 }
8262
8263 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8264 PDiag(DiagID) << index.toString(10, true)
8265 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00008266 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00008267
Matt Beaumont-Gayb2339822011-11-29 19:27:11 +00008268 if (!ND) {
8269 // Try harder to find a NamedDecl to point at in the note.
8270 while (const ArraySubscriptExpr *ASE =
8271 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8272 BaseExpr = ASE->getBase()->IgnoreParenCasts();
8273 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8274 ND = dyn_cast<NamedDecl>(DRE->getDecl());
8275 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8276 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8277 }
8278
Chandler Carruth1af88f12011-02-17 21:10:52 +00008279 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008280 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
8281 PDiag(diag::note_array_index_out_of_bounds)
8282 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00008283}
8284
Ted Kremenekdf26df72011-03-01 18:41:00 +00008285void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008286 int AllowOnePastEnd = 0;
8287 while (expr) {
8288 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00008289 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008290 case Stmt::ArraySubscriptExprClass: {
8291 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
Matt Beaumont-Gay5533a552011-12-14 16:02:15 +00008292 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008293 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00008294 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008295 }
8296 case Stmt::UnaryOperatorClass: {
8297 // Only unwrap the * and & unary operators
8298 const UnaryOperator *UO = cast<UnaryOperator>(expr);
8299 expr = UO->getSubExpr();
8300 switch (UO->getOpcode()) {
8301 case UO_AddrOf:
8302 AllowOnePastEnd++;
8303 break;
8304 case UO_Deref:
8305 AllowOnePastEnd--;
8306 break;
8307 default:
8308 return;
8309 }
8310 break;
8311 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008312 case Stmt::ConditionalOperatorClass: {
8313 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
8314 if (const Expr *lhs = cond->getLHS())
8315 CheckArrayAccess(lhs);
8316 if (const Expr *rhs = cond->getRHS())
8317 CheckArrayAccess(rhs);
8318 return;
8319 }
8320 default:
8321 return;
8322 }
Peter Collingbourne91147592011-04-15 00:35:48 +00008323 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00008324}
John McCall31168b02011-06-15 23:02:42 +00008325
8326//===--- CHECK: Objective-C retain cycles ----------------------------------//
8327
8328namespace {
8329 struct RetainCycleOwner {
Craig Topperc3ec1492014-05-26 06:22:03 +00008330 RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
John McCall31168b02011-06-15 23:02:42 +00008331 VarDecl *Variable;
8332 SourceRange Range;
8333 SourceLocation Loc;
8334 bool Indirect;
8335
8336 void setLocsFrom(Expr *e) {
8337 Loc = e->getExprLoc();
8338 Range = e->getSourceRange();
8339 }
8340 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008341}
John McCall31168b02011-06-15 23:02:42 +00008342
8343/// Consider whether capturing the given variable can possibly lead to
8344/// a retain cycle.
8345static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00008346 // In ARC, it's captured strongly iff the variable has __strong
John McCall31168b02011-06-15 23:02:42 +00008347 // lifetime. In MRR, it's captured strongly if the variable is
8348 // __block and has an appropriate type.
8349 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8350 return false;
8351
8352 owner.Variable = var;
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008353 if (ref)
8354 owner.setLocsFrom(ref);
John McCall31168b02011-06-15 23:02:42 +00008355 return true;
8356}
8357
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008358static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
John McCall31168b02011-06-15 23:02:42 +00008359 while (true) {
8360 e = e->IgnoreParens();
8361 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
8362 switch (cast->getCastKind()) {
8363 case CK_BitCast:
8364 case CK_LValueBitCast:
8365 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00008366 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00008367 e = cast->getSubExpr();
8368 continue;
8369
John McCall31168b02011-06-15 23:02:42 +00008370 default:
8371 return false;
8372 }
8373 }
8374
8375 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
8376 ObjCIvarDecl *ivar = ref->getDecl();
8377 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
8378 return false;
8379
8380 // Try to find a retain cycle in the base.
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008381 if (!findRetainCycleOwner(S, ref->getBase(), owner))
John McCall31168b02011-06-15 23:02:42 +00008382 return false;
8383
8384 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8385 owner.Indirect = true;
8386 return true;
8387 }
8388
8389 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8390 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8391 if (!var) return false;
8392 return considerVariable(var, ref, owner);
8393 }
8394
John McCall31168b02011-06-15 23:02:42 +00008395 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8396 if (member->isArrow()) return false;
8397
8398 // Don't count this as an indirect ownership.
8399 e = member->getBase();
8400 continue;
8401 }
8402
John McCallfe96e0b2011-11-06 09:01:30 +00008403 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8404 // Only pay attention to pseudo-objects on property references.
8405 ObjCPropertyRefExpr *pre
8406 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8407 ->IgnoreParens());
8408 if (!pre) return false;
8409 if (pre->isImplicitProperty()) return false;
8410 ObjCPropertyDecl *property = pre->getExplicitProperty();
8411 if (!property->isRetaining() &&
8412 !(property->getPropertyIvarDecl() &&
8413 property->getPropertyIvarDecl()->getType()
8414 .getObjCLifetime() == Qualifiers::OCL_Strong))
8415 return false;
8416
8417 owner.Indirect = true;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008418 if (pre->isSuperReceiver()) {
8419 owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8420 if (!owner.Variable)
8421 return false;
8422 owner.Loc = pre->getLocation();
8423 owner.Range = pre->getSourceRange();
8424 return true;
8425 }
John McCallfe96e0b2011-11-06 09:01:30 +00008426 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8427 ->getSourceExpr());
8428 continue;
8429 }
8430
John McCall31168b02011-06-15 23:02:42 +00008431 // Array ivars?
8432
8433 return false;
8434 }
8435}
8436
8437namespace {
8438 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8439 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8440 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008441 Context(Context), Variable(variable), Capturer(nullptr),
8442 VarWillBeReased(false) {}
8443 ASTContext &Context;
John McCall31168b02011-06-15 23:02:42 +00008444 VarDecl *Variable;
8445 Expr *Capturer;
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008446 bool VarWillBeReased;
John McCall31168b02011-06-15 23:02:42 +00008447
8448 void VisitDeclRefExpr(DeclRefExpr *ref) {
8449 if (ref->getDecl() == Variable && !Capturer)
8450 Capturer = ref;
8451 }
8452
John McCall31168b02011-06-15 23:02:42 +00008453 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8454 if (Capturer) return;
8455 Visit(ref->getBase());
8456 if (Capturer && ref->isFreeIvar())
8457 Capturer = ref;
8458 }
8459
8460 void VisitBlockExpr(BlockExpr *block) {
8461 // Look inside nested blocks
8462 if (block->getBlockDecl()->capturesVariable(Variable))
8463 Visit(block->getBlockDecl()->getBody());
8464 }
Fariborz Jahanian0e337542012-08-31 20:04:47 +00008465
8466 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8467 if (Capturer) return;
8468 if (OVE->getSourceExpr())
8469 Visit(OVE->getSourceExpr());
8470 }
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008471 void VisitBinaryOperator(BinaryOperator *BinOp) {
8472 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8473 return;
8474 Expr *LHS = BinOp->getLHS();
8475 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8476 if (DRE->getDecl() != Variable)
8477 return;
8478 if (Expr *RHS = BinOp->getRHS()) {
8479 RHS = RHS->IgnoreParenCasts();
8480 llvm::APSInt Value;
8481 VarWillBeReased =
8482 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8483 }
8484 }
8485 }
John McCall31168b02011-06-15 23:02:42 +00008486 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008487}
John McCall31168b02011-06-15 23:02:42 +00008488
8489/// Check whether the given argument is a block which captures a
8490/// variable.
8491static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8492 assert(owner.Variable && owner.Loc.isValid());
8493
8494 e = e->IgnoreParenCasts();
Jordan Rose67e887c2012-09-17 17:54:30 +00008495
8496 // Look through [^{...} copy] and Block_copy(^{...}).
8497 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8498 Selector Cmd = ME->getSelector();
8499 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8500 e = ME->getInstanceReceiver();
8501 if (!e)
Craig Topperc3ec1492014-05-26 06:22:03 +00008502 return nullptr;
Jordan Rose67e887c2012-09-17 17:54:30 +00008503 e = e->IgnoreParenCasts();
8504 }
8505 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8506 if (CE->getNumArgs() == 1) {
8507 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
Ted Kremenekb67c6cc2012-10-02 04:36:54 +00008508 if (Fn) {
8509 const IdentifierInfo *FnI = Fn->getIdentifier();
8510 if (FnI && FnI->isStr("_Block_copy")) {
8511 e = CE->getArg(0)->IgnoreParenCasts();
8512 }
8513 }
Jordan Rose67e887c2012-09-17 17:54:30 +00008514 }
8515 }
8516
John McCall31168b02011-06-15 23:02:42 +00008517 BlockExpr *block = dyn_cast<BlockExpr>(e);
8518 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
Craig Topperc3ec1492014-05-26 06:22:03 +00008519 return nullptr;
John McCall31168b02011-06-15 23:02:42 +00008520
8521 FindCaptureVisitor visitor(S.Context, owner.Variable);
8522 visitor.Visit(block->getBlockDecl()->getBody());
Fariborz Jahanian8df9e242014-06-12 20:57:14 +00008523 return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
John McCall31168b02011-06-15 23:02:42 +00008524}
8525
8526static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8527 RetainCycleOwner &owner) {
8528 assert(capturer);
8529 assert(owner.Variable && owner.Loc.isValid());
8530
8531 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8532 << owner.Variable << capturer->getSourceRange();
8533 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8534 << owner.Indirect << owner.Range;
8535}
8536
8537/// Check for a keyword selector that starts with the word 'add' or
8538/// 'set'.
8539static bool isSetterLikeSelector(Selector sel) {
8540 if (sel.isUnarySelector()) return false;
8541
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008542 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00008543 while (!str.empty() && str.front() == '_') str = str.substr(1);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008544 if (str.startswith("set"))
John McCall31168b02011-06-15 23:02:42 +00008545 str = str.substr(3);
Ted Kremenek764d63a2011-12-01 00:59:21 +00008546 else if (str.startswith("add")) {
8547 // Specially whitelist 'addOperationWithBlock:'.
8548 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8549 return false;
8550 str = str.substr(3);
8551 }
John McCall31168b02011-06-15 23:02:42 +00008552 else
8553 return false;
8554
8555 if (str.empty()) return true;
Jordan Rosea7d03842013-02-08 22:30:41 +00008556 return !isLowercase(str.front());
John McCall31168b02011-06-15 23:02:42 +00008557}
8558
Benjamin Kramer3a743452015-03-09 15:03:32 +00008559static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
8560 ObjCMessageExpr *Message) {
Alex Denisove1d882c2015-03-04 17:55:52 +00008561 if (S.NSMutableArrayPointer.isNull()) {
8562 IdentifierInfo *NSMutableArrayId =
8563 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableArray);
8564 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableArrayId,
8565 Message->getLocStart(),
8566 Sema::LookupOrdinaryName);
8567 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8568 if (!InterfaceDecl) {
8569 return None;
8570 }
8571 QualType NSMutableArrayObject =
8572 S.Context.getObjCInterfaceType(InterfaceDecl);
8573 S.NSMutableArrayPointer =
8574 S.Context.getObjCObjectPointerType(NSMutableArrayObject);
8575 }
8576
8577 if (S.NSMutableArrayPointer != Message->getReceiverType()) {
8578 return None;
8579 }
8580
8581 Selector Sel = Message->getSelector();
8582
8583 Optional<NSAPI::NSArrayMethodKind> MKOpt =
8584 S.NSAPIObj->getNSArrayMethodKind(Sel);
8585 if (!MKOpt) {
8586 return None;
8587 }
8588
8589 NSAPI::NSArrayMethodKind MK = *MKOpt;
8590
8591 switch (MK) {
8592 case NSAPI::NSMutableArr_addObject:
8593 case NSAPI::NSMutableArr_insertObjectAtIndex:
8594 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
8595 return 0;
8596 case NSAPI::NSMutableArr_replaceObjectAtIndex:
8597 return 1;
8598
8599 default:
8600 return None;
8601 }
8602
8603 return None;
8604}
8605
8606static
8607Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
8608 ObjCMessageExpr *Message) {
8609
8610 if (S.NSMutableDictionaryPointer.isNull()) {
8611 IdentifierInfo *NSMutableDictionaryId =
8612 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableDictionary);
8613 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableDictionaryId,
8614 Message->getLocStart(),
8615 Sema::LookupOrdinaryName);
8616 ObjCInterfaceDecl *InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8617 if (!InterfaceDecl) {
8618 return None;
8619 }
8620 QualType NSMutableDictionaryObject =
8621 S.Context.getObjCInterfaceType(InterfaceDecl);
8622 S.NSMutableDictionaryPointer =
8623 S.Context.getObjCObjectPointerType(NSMutableDictionaryObject);
8624 }
8625
8626 if (S.NSMutableDictionaryPointer != Message->getReceiverType()) {
8627 return None;
8628 }
8629
8630 Selector Sel = Message->getSelector();
8631
8632 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
8633 S.NSAPIObj->getNSDictionaryMethodKind(Sel);
8634 if (!MKOpt) {
8635 return None;
8636 }
8637
8638 NSAPI::NSDictionaryMethodKind MK = *MKOpt;
8639
8640 switch (MK) {
8641 case NSAPI::NSMutableDict_setObjectForKey:
8642 case NSAPI::NSMutableDict_setValueForKey:
8643 case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
8644 return 0;
8645
8646 default:
8647 return None;
8648 }
8649
8650 return None;
8651}
8652
8653static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
8654
8655 ObjCInterfaceDecl *InterfaceDecl;
8656 if (S.NSMutableSetPointer.isNull()) {
8657 IdentifierInfo *NSMutableSetId =
8658 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableSet);
8659 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSMutableSetId,
8660 Message->getLocStart(),
8661 Sema::LookupOrdinaryName);
8662 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8663 if (InterfaceDecl) {
8664 QualType NSMutableSetObject =
8665 S.Context.getObjCInterfaceType(InterfaceDecl);
8666 S.NSMutableSetPointer =
8667 S.Context.getObjCObjectPointerType(NSMutableSetObject);
8668 }
8669 }
8670
8671 if (S.NSCountedSetPointer.isNull()) {
8672 IdentifierInfo *NSCountedSetId =
8673 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSCountedSet);
8674 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSCountedSetId,
8675 Message->getLocStart(),
8676 Sema::LookupOrdinaryName);
8677 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8678 if (InterfaceDecl) {
8679 QualType NSCountedSetObject =
8680 S.Context.getObjCInterfaceType(InterfaceDecl);
8681 S.NSCountedSetPointer =
8682 S.Context.getObjCObjectPointerType(NSCountedSetObject);
8683 }
8684 }
8685
8686 if (S.NSMutableOrderedSetPointer.isNull()) {
8687 IdentifierInfo *NSOrderedSetId =
8688 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSMutableOrderedSet);
8689 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSOrderedSetId,
8690 Message->getLocStart(),
8691 Sema::LookupOrdinaryName);
8692 InterfaceDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
8693 if (InterfaceDecl) {
8694 QualType NSOrderedSetObject =
8695 S.Context.getObjCInterfaceType(InterfaceDecl);
8696 S.NSMutableOrderedSetPointer =
8697 S.Context.getObjCObjectPointerType(NSOrderedSetObject);
8698 }
8699 }
8700
8701 QualType ReceiverType = Message->getReceiverType();
8702
8703 bool IsMutableSet = !S.NSMutableSetPointer.isNull() &&
8704 ReceiverType == S.NSMutableSetPointer;
8705 bool IsMutableOrderedSet = !S.NSMutableOrderedSetPointer.isNull() &&
8706 ReceiverType == S.NSMutableOrderedSetPointer;
8707 bool IsCountedSet = !S.NSCountedSetPointer.isNull() &&
8708 ReceiverType == S.NSCountedSetPointer;
8709
8710 if (!IsMutableSet && !IsMutableOrderedSet && !IsCountedSet) {
8711 return None;
8712 }
8713
8714 Selector Sel = Message->getSelector();
8715
8716 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
8717 if (!MKOpt) {
8718 return None;
8719 }
8720
8721 NSAPI::NSSetMethodKind MK = *MKOpt;
8722
8723 switch (MK) {
8724 case NSAPI::NSMutableSet_addObject:
8725 case NSAPI::NSOrderedSet_setObjectAtIndex:
8726 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
8727 case NSAPI::NSOrderedSet_insertObjectAtIndex:
8728 return 0;
8729 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
8730 return 1;
8731 }
8732
8733 return None;
8734}
8735
8736void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
8737 if (!Message->isInstanceMessage()) {
8738 return;
8739 }
8740
8741 Optional<int> ArgOpt;
8742
8743 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
8744 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
8745 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
8746 return;
8747 }
8748
8749 int ArgIndex = *ArgOpt;
8750
8751 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
8752 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
8753 Receiver = OE->getSourceExpr()->IgnoreImpCasts();
8754 }
8755
8756 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
8757 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
8758 Arg = OE->getSourceExpr()->IgnoreImpCasts();
8759 }
8760
8761 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8762 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8763 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8764 ValueDecl *Decl = ReceiverRE->getDecl();
8765 Diag(Message->getSourceRange().getBegin(),
8766 diag::warn_objc_circular_container)
8767 << Decl->getName();
8768 Diag(Decl->getLocation(),
8769 diag::note_objc_circular_container_declared_here)
8770 << Decl->getName();
8771 }
8772 }
8773 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8774 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
8775 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8776 ObjCIvarDecl *Decl = IvarRE->getDecl();
8777 Diag(Message->getSourceRange().getBegin(),
8778 diag::warn_objc_circular_container)
8779 << Decl->getName();
8780 Diag(Decl->getLocation(),
8781 diag::note_objc_circular_container_declared_here)
8782 << Decl->getName();
8783 }
8784 }
8785 }
8786
8787}
8788
John McCall31168b02011-06-15 23:02:42 +00008789/// Check a message send to see if it's likely to cause a retain cycle.
8790void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8791 // Only check instance methods whose selector looks like a setter.
8792 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8793 return;
8794
8795 // Try to find a variable that the receiver is strongly owned by.
8796 RetainCycleOwner owner;
8797 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008798 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
John McCall31168b02011-06-15 23:02:42 +00008799 return;
8800 } else {
8801 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8802 owner.Variable = getCurMethodDecl()->getSelfDecl();
8803 owner.Loc = msg->getSuperLoc();
8804 owner.Range = msg->getSuperLoc();
8805 }
8806
8807 // Check whether the receiver is captured by any of the arguments.
8808 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8809 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8810 return diagnoseRetainCycle(*this, capturer, owner);
8811}
8812
8813/// Check a property assign to see if it's likely to cause a retain cycle.
8814void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8815 RetainCycleOwner owner;
Fariborz Jahanianedbc3452012-01-10 19:28:26 +00008816 if (!findRetainCycleOwner(*this, receiver, owner))
John McCall31168b02011-06-15 23:02:42 +00008817 return;
8818
8819 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8820 diagnoseRetainCycle(*this, capturer, owner);
8821}
8822
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008823void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8824 RetainCycleOwner Owner;
Craig Topperc3ec1492014-05-26 06:22:03 +00008825 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
Jordan Rosefa9e4ba2012-09-15 02:48:31 +00008826 return;
8827
8828 // Because we don't have an expression for the variable, we have to set the
8829 // location explicitly here.
8830 Owner.Loc = Var->getLocation();
8831 Owner.Range = Var->getSourceRange();
8832
8833 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8834 diagnoseRetainCycle(*this, Capturer, Owner);
8835}
8836
Ted Kremenek9304da92012-12-21 08:04:28 +00008837static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8838 Expr *RHS, bool isProperty) {
8839 // Check if RHS is an Objective-C object literal, which also can get
8840 // immediately zapped in a weak reference. Note that we explicitly
8841 // allow ObjCStringLiterals, since those are designed to never really die.
8842 RHS = RHS->IgnoreParenImpCasts();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008843
Ted Kremenek64873352012-12-21 22:46:35 +00008844 // This enum needs to match with the 'select' in
8845 // warn_objc_arc_literal_assign (off-by-1).
8846 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8847 if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8848 return false;
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008849
8850 S.Diag(Loc, diag::warn_arc_literal_assign)
Ted Kremenek64873352012-12-21 22:46:35 +00008851 << (unsigned) Kind
Ted Kremenek9304da92012-12-21 08:04:28 +00008852 << (isProperty ? 0 : 1)
8853 << RHS->getSourceRange();
Ted Kremenek44c2a2a2012-12-21 21:59:39 +00008854
8855 return true;
Ted Kremenek9304da92012-12-21 08:04:28 +00008856}
8857
Ted Kremenekc1f014a2012-12-21 19:45:30 +00008858static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8859 Qualifiers::ObjCLifetime LT,
8860 Expr *RHS, bool isProperty) {
8861 // Strip off any implicit cast added to get to the one ARC-specific.
8862 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8863 if (cast->getCastKind() == CK_ARCConsumeObject) {
8864 S.Diag(Loc, diag::warn_arc_retained_assign)
8865 << (LT == Qualifiers::OCL_ExplicitNone)
8866 << (isProperty ? 0 : 1)
8867 << RHS->getSourceRange();
8868 return true;
8869 }
8870 RHS = cast->getSubExpr();
8871 }
8872
8873 if (LT == Qualifiers::OCL_Weak &&
8874 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8875 return true;
8876
8877 return false;
8878}
8879
Ted Kremenekb36234d2012-12-21 08:04:20 +00008880bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8881 QualType LHS, Expr *RHS) {
8882 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8883
8884 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8885 return false;
8886
8887 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8888 return true;
8889
8890 return false;
8891}
8892
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008893void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8894 Expr *LHS, Expr *RHS) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008895 QualType LHSType;
8896 // PropertyRef on LHS type need be directly obtained from
Alp Tokerf6a24ce2013-12-05 16:25:25 +00008897 // its declaration as it has a PseudoType.
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008898 ObjCPropertyRefExpr *PRE
8899 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8900 if (PRE && !PRE->isImplicitProperty()) {
8901 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8902 if (PD)
8903 LHSType = PD->getType();
8904 }
8905
8906 if (LHSType.isNull())
8907 LHSType = LHS->getType();
Jordan Rose657b5f42012-09-28 22:21:35 +00008908
8909 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8910
8911 if (LT == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00008912 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
Jordan Rose657b5f42012-09-28 22:21:35 +00008913 getCurFunction()->markSafeWeakUse(LHS);
8914 }
8915
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008916 if (checkUnsafeAssigns(Loc, LHSType, RHS))
8917 return;
Jordan Rose657b5f42012-09-28 22:21:35 +00008918
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008919 // FIXME. Check for other life times.
8920 if (LT != Qualifiers::OCL_None)
8921 return;
8922
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008923 if (PRE) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008924 if (PRE->isImplicitProperty())
8925 return;
8926 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8927 if (!PD)
8928 return;
8929
Bill Wendling44426052012-12-20 19:22:21 +00008930 unsigned Attributes = PD->getPropertyAttributes();
8931 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008932 // when 'assign' attribute was not explicitly specified
8933 // by user, ignore it and rely on property type itself
8934 // for lifetime info.
8935 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8936 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8937 LHSType->isObjCRetainableType())
8938 return;
8939
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008940 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00008941 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008942 Diag(Loc, diag::warn_arc_retained_property_assign)
8943 << RHS->getSourceRange();
8944 return;
8945 }
8946 RHS = cast->getSubExpr();
8947 }
Fariborz Jahanianc72a8072012-01-17 22:58:16 +00008948 }
Bill Wendling44426052012-12-20 19:22:21 +00008949 else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
Ted Kremenekb36234d2012-12-21 08:04:20 +00008950 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8951 return;
Fariborz Jahaniandabd1332012-07-06 21:09:27 +00008952 }
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00008953 }
8954}
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008955
8956//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8957
8958namespace {
8959bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8960 SourceLocation StmtLoc,
8961 const NullStmt *Body) {
8962 // Do not warn if the body is a macro that expands to nothing, e.g:
8963 //
8964 // #define CALL(x)
8965 // if (condition)
8966 // CALL(0);
8967 //
8968 if (Body->hasLeadingEmptyMacro())
8969 return false;
8970
8971 // Get line numbers of statement and body.
8972 bool StmtLineInvalid;
Dmitri Gribenkoad80af82015-03-15 01:08:23 +00008973 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00008974 &StmtLineInvalid);
8975 if (StmtLineInvalid)
8976 return false;
8977
8978 bool BodyLineInvalid;
8979 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8980 &BodyLineInvalid);
8981 if (BodyLineInvalid)
8982 return false;
8983
8984 // Warn if null statement and body are on the same line.
8985 if (StmtLine != BodyLine)
8986 return false;
8987
8988 return true;
8989}
8990} // Unnamed namespace
8991
8992void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8993 const Stmt *Body,
8994 unsigned DiagID) {
8995 // Since this is a syntactic check, don't emit diagnostic for template
8996 // instantiations, this just adds noise.
8997 if (CurrentInstantiationScope)
8998 return;
8999
9000 // The body should be a null statement.
9001 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9002 if (!NBody)
9003 return;
9004
9005 // Do the usual checks.
9006 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9007 return;
9008
9009 Diag(NBody->getSemiLoc(), DiagID);
9010 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9011}
9012
9013void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9014 const Stmt *PossibleBody) {
9015 assert(!CurrentInstantiationScope); // Ensured by caller
9016
9017 SourceLocation StmtLoc;
9018 const Stmt *Body;
9019 unsigned DiagID;
9020 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9021 StmtLoc = FS->getRParenLoc();
9022 Body = FS->getBody();
9023 DiagID = diag::warn_empty_for_body;
9024 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9025 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9026 Body = WS->getBody();
9027 DiagID = diag::warn_empty_while_body;
9028 } else
9029 return; // Neither `for' nor `while'.
9030
9031 // The body should be a null statement.
9032 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9033 if (!NBody)
9034 return;
9035
9036 // Skip expensive checks if diagnostic is disabled.
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00009037 if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
Dmitri Gribenko800ddf32012-02-14 22:14:32 +00009038 return;
9039
9040 // Do the usual checks.
9041 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9042 return;
9043
9044 // `for(...);' and `while(...);' are popular idioms, so in order to keep
9045 // noise level low, emit diagnostics only if for/while is followed by a
9046 // CompoundStmt, e.g.:
9047 // for (int i = 0; i < n; i++);
9048 // {
9049 // a(i);
9050 // }
9051 // or if for/while is followed by a statement with more indentation
9052 // than for/while itself:
9053 // for (int i = 0; i < n; i++);
9054 // a(i);
9055 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9056 if (!ProbableTypo) {
9057 bool BodyColInvalid;
9058 unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9059 PossibleBody->getLocStart(),
9060 &BodyColInvalid);
9061 if (BodyColInvalid)
9062 return;
9063
9064 bool StmtColInvalid;
9065 unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9066 S->getLocStart(),
9067 &StmtColInvalid);
9068 if (StmtColInvalid)
9069 return;
9070
9071 if (BodyCol > StmtCol)
9072 ProbableTypo = true;
9073 }
9074
9075 if (ProbableTypo) {
9076 Diag(NBody->getSemiLoc(), DiagID);
9077 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9078 }
9079}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009080
Richard Trieu36d0b2b2015-01-13 02:32:02 +00009081//===--- CHECK: Warn on self move with std::move. -------------------------===//
9082
9083/// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9084void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9085 SourceLocation OpLoc) {
9086
9087 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9088 return;
9089
9090 if (!ActiveTemplateInstantiations.empty())
9091 return;
9092
9093 // Strip parens and casts away.
9094 LHSExpr = LHSExpr->IgnoreParenImpCasts();
9095 RHSExpr = RHSExpr->IgnoreParenImpCasts();
9096
9097 // Check for a call expression
9098 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9099 if (!CE || CE->getNumArgs() != 1)
9100 return;
9101
9102 // Check for a call to std::move
9103 const FunctionDecl *FD = CE->getDirectCallee();
9104 if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9105 !FD->getIdentifier()->isStr("move"))
9106 return;
9107
9108 // Get argument from std::move
9109 RHSExpr = CE->getArg(0);
9110
9111 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9112 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9113
9114 // Two DeclRefExpr's, check that the decls are the same.
9115 if (LHSDeclRef && RHSDeclRef) {
9116 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9117 return;
9118 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9119 RHSDeclRef->getDecl()->getCanonicalDecl())
9120 return;
9121
9122 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9123 << LHSExpr->getSourceRange()
9124 << RHSExpr->getSourceRange();
9125 return;
9126 }
9127
9128 // Member variables require a different approach to check for self moves.
9129 // MemberExpr's are the same if every nested MemberExpr refers to the same
9130 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
9131 // the base Expr's are CXXThisExpr's.
9132 const Expr *LHSBase = LHSExpr;
9133 const Expr *RHSBase = RHSExpr;
9134 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
9135 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
9136 if (!LHSME || !RHSME)
9137 return;
9138
9139 while (LHSME && RHSME) {
9140 if (LHSME->getMemberDecl()->getCanonicalDecl() !=
9141 RHSME->getMemberDecl()->getCanonicalDecl())
9142 return;
9143
9144 LHSBase = LHSME->getBase();
9145 RHSBase = RHSME->getBase();
9146 LHSME = dyn_cast<MemberExpr>(LHSBase);
9147 RHSME = dyn_cast<MemberExpr>(RHSBase);
9148 }
9149
9150 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
9151 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
9152 if (LHSDeclRef && RHSDeclRef) {
9153 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
9154 return;
9155 if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
9156 RHSDeclRef->getDecl()->getCanonicalDecl())
9157 return;
9158
9159 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9160 << LHSExpr->getSourceRange()
9161 << RHSExpr->getSourceRange();
9162 return;
9163 }
9164
9165 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9166 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
9167 << LHSExpr->getSourceRange()
9168 << RHSExpr->getSourceRange();
9169}
9170
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009171//===--- Layout compatibility ----------------------------------------------//
9172
9173namespace {
9174
9175bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
9176
9177/// \brief Check if two enumeration types are layout-compatible.
9178bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
9179 // C++11 [dcl.enum] p8:
9180 // Two enumeration types are layout-compatible if they have the same
9181 // underlying type.
9182 return ED1->isComplete() && ED2->isComplete() &&
9183 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
9184}
9185
9186/// \brief Check if two fields are layout-compatible.
9187bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
9188 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
9189 return false;
9190
9191 if (Field1->isBitField() != Field2->isBitField())
9192 return false;
9193
9194 if (Field1->isBitField()) {
9195 // Make sure that the bit-fields are the same length.
9196 unsigned Bits1 = Field1->getBitWidthValue(C);
9197 unsigned Bits2 = Field2->getBitWidthValue(C);
9198
9199 if (Bits1 != Bits2)
9200 return false;
9201 }
9202
9203 return true;
9204}
9205
9206/// \brief Check if two standard-layout structs are layout-compatible.
9207/// (C++11 [class.mem] p17)
9208bool isLayoutCompatibleStruct(ASTContext &C,
9209 RecordDecl *RD1,
9210 RecordDecl *RD2) {
9211 // If both records are C++ classes, check that base classes match.
9212 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9213 // If one of records is a CXXRecordDecl we are in C++ mode,
9214 // thus the other one is a CXXRecordDecl, too.
9215 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
9216 // Check number of base classes.
9217 if (D1CXX->getNumBases() != D2CXX->getNumBases())
9218 return false;
9219
9220 // Check the base classes.
9221 for (CXXRecordDecl::base_class_const_iterator
9222 Base1 = D1CXX->bases_begin(),
9223 BaseEnd1 = D1CXX->bases_end(),
9224 Base2 = D2CXX->bases_begin();
9225 Base1 != BaseEnd1;
9226 ++Base1, ++Base2) {
9227 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9228 return false;
9229 }
9230 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9231 // If only RD2 is a C++ class, it should have zero base classes.
9232 if (D2CXX->getNumBases() > 0)
9233 return false;
9234 }
9235
9236 // Check the fields.
9237 RecordDecl::field_iterator Field2 = RD2->field_begin(),
9238 Field2End = RD2->field_end(),
9239 Field1 = RD1->field_begin(),
9240 Field1End = RD1->field_end();
9241 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9242 if (!isLayoutCompatible(C, *Field1, *Field2))
9243 return false;
9244 }
9245 if (Field1 != Field1End || Field2 != Field2End)
9246 return false;
9247
9248 return true;
9249}
9250
9251/// \brief Check if two standard-layout unions are layout-compatible.
9252/// (C++11 [class.mem] p18)
9253bool isLayoutCompatibleUnion(ASTContext &C,
9254 RecordDecl *RD1,
9255 RecordDecl *RD2) {
9256 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009257 for (auto *Field2 : RD2->fields())
9258 UnmatchedFields.insert(Field2);
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009259
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009260 for (auto *Field1 : RD1->fields()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009261 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9262 I = UnmatchedFields.begin(),
9263 E = UnmatchedFields.end();
9264
9265 for ( ; I != E; ++I) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00009266 if (isLayoutCompatible(C, Field1, *I)) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009267 bool Result = UnmatchedFields.erase(*I);
9268 (void) Result;
9269 assert(Result);
9270 break;
9271 }
9272 }
9273 if (I == E)
9274 return false;
9275 }
9276
9277 return UnmatchedFields.empty();
9278}
9279
9280bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
9281 if (RD1->isUnion() != RD2->isUnion())
9282 return false;
9283
9284 if (RD1->isUnion())
9285 return isLayoutCompatibleUnion(C, RD1, RD2);
9286 else
9287 return isLayoutCompatibleStruct(C, RD1, RD2);
9288}
9289
9290/// \brief Check if two types are layout-compatible in C++11 sense.
9291bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
9292 if (T1.isNull() || T2.isNull())
9293 return false;
9294
9295 // C++11 [basic.types] p11:
9296 // If two types T1 and T2 are the same type, then T1 and T2 are
9297 // layout-compatible types.
9298 if (C.hasSameType(T1, T2))
9299 return true;
9300
9301 T1 = T1.getCanonicalType().getUnqualifiedType();
9302 T2 = T2.getCanonicalType().getUnqualifiedType();
9303
9304 const Type::TypeClass TC1 = T1->getTypeClass();
9305 const Type::TypeClass TC2 = T2->getTypeClass();
9306
9307 if (TC1 != TC2)
9308 return false;
9309
9310 if (TC1 == Type::Enum) {
9311 return isLayoutCompatible(C,
9312 cast<EnumType>(T1)->getDecl(),
9313 cast<EnumType>(T2)->getDecl());
9314 } else if (TC1 == Type::Record) {
9315 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
9316 return false;
9317
9318 return isLayoutCompatible(C,
9319 cast<RecordType>(T1)->getDecl(),
9320 cast<RecordType>(T2)->getDecl());
9321 }
9322
9323 return false;
9324}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009325}
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009326
9327//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
9328
9329namespace {
9330/// \brief Given a type tag expression find the type tag itself.
9331///
9332/// \param TypeExpr Type tag expression, as it appears in user's code.
9333///
9334/// \param VD Declaration of an identifier that appears in a type tag.
9335///
9336/// \param MagicValue Type tag magic value.
9337bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
9338 const ValueDecl **VD, uint64_t *MagicValue) {
9339 while(true) {
9340 if (!TypeExpr)
9341 return false;
9342
9343 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
9344
9345 switch (TypeExpr->getStmtClass()) {
9346 case Stmt::UnaryOperatorClass: {
9347 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
9348 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
9349 TypeExpr = UO->getSubExpr();
9350 continue;
9351 }
9352 return false;
9353 }
9354
9355 case Stmt::DeclRefExprClass: {
9356 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9357 *VD = DRE->getDecl();
9358 return true;
9359 }
9360
9361 case Stmt::IntegerLiteralClass: {
9362 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
9363 llvm::APInt MagicValueAPInt = IL->getValue();
9364 if (MagicValueAPInt.getActiveBits() <= 64) {
9365 *MagicValue = MagicValueAPInt.getZExtValue();
9366 return true;
9367 } else
9368 return false;
9369 }
9370
9371 case Stmt::BinaryConditionalOperatorClass:
9372 case Stmt::ConditionalOperatorClass: {
9373 const AbstractConditionalOperator *ACO =
9374 cast<AbstractConditionalOperator>(TypeExpr);
9375 bool Result;
9376 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
9377 if (Result)
9378 TypeExpr = ACO->getTrueExpr();
9379 else
9380 TypeExpr = ACO->getFalseExpr();
9381 continue;
9382 }
9383 return false;
9384 }
9385
9386 case Stmt::BinaryOperatorClass: {
9387 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
9388 if (BO->getOpcode() == BO_Comma) {
9389 TypeExpr = BO->getRHS();
9390 continue;
9391 }
9392 return false;
9393 }
9394
9395 default:
9396 return false;
9397 }
9398 }
9399}
9400
9401/// \brief Retrieve the C type corresponding to type tag TypeExpr.
9402///
9403/// \param TypeExpr Expression that specifies a type tag.
9404///
9405/// \param MagicValues Registered magic values.
9406///
9407/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
9408/// kind.
9409///
9410/// \param TypeInfo Information about the corresponding C type.
9411///
9412/// \returns true if the corresponding C type was found.
9413bool GetMatchingCType(
9414 const IdentifierInfo *ArgumentKind,
9415 const Expr *TypeExpr, const ASTContext &Ctx,
9416 const llvm::DenseMap<Sema::TypeTagMagicValue,
9417 Sema::TypeTagData> *MagicValues,
9418 bool &FoundWrongKind,
9419 Sema::TypeTagData &TypeInfo) {
9420 FoundWrongKind = false;
9421
9422 // Variable declaration that has type_tag_for_datatype attribute.
Craig Topperc3ec1492014-05-26 06:22:03 +00009423 const ValueDecl *VD = nullptr;
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009424
9425 uint64_t MagicValue;
9426
9427 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9428 return false;
9429
9430 if (VD) {
Benjamin Kramerae852a62014-02-23 14:34:50 +00009431 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009432 if (I->getArgumentKind() != ArgumentKind) {
9433 FoundWrongKind = true;
9434 return false;
9435 }
9436 TypeInfo.Type = I->getMatchingCType();
9437 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
9438 TypeInfo.MustBeNull = I->getMustBeNull();
9439 return true;
9440 }
9441 return false;
9442 }
9443
9444 if (!MagicValues)
9445 return false;
9446
9447 llvm::DenseMap<Sema::TypeTagMagicValue,
9448 Sema::TypeTagData>::const_iterator I =
9449 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9450 if (I == MagicValues->end())
9451 return false;
9452
9453 TypeInfo = I->second;
9454 return true;
9455}
9456} // unnamed namespace
9457
9458void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
9459 uint64_t MagicValue, QualType Type,
9460 bool LayoutCompatible,
9461 bool MustBeNull) {
9462 if (!TypeTagForDatatypeMagicValues)
9463 TypeTagForDatatypeMagicValues.reset(
9464 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9465
9466 TypeTagMagicValue Magic(ArgumentKind, MagicValue);
9467 (*TypeTagForDatatypeMagicValues)[Magic] =
9468 TypeTagData(Type, LayoutCompatible, MustBeNull);
9469}
9470
9471namespace {
9472bool IsSameCharType(QualType T1, QualType T2) {
9473 const BuiltinType *BT1 = T1->getAs<BuiltinType>();
9474 if (!BT1)
9475 return false;
9476
9477 const BuiltinType *BT2 = T2->getAs<BuiltinType>();
9478 if (!BT2)
9479 return false;
9480
9481 BuiltinType::Kind T1Kind = BT1->getKind();
9482 BuiltinType::Kind T2Kind = BT2->getKind();
9483
9484 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9485 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9486 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9487 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9488}
9489} // unnamed namespace
9490
9491void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
9492 const Expr * const *ExprArgs) {
9493 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
9494 bool IsPointerAttr = Attr->getIsPointer();
9495
9496 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9497 bool FoundWrongKind;
9498 TypeTagData TypeInfo;
9499 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9500 TypeTagForDatatypeMagicValues.get(),
9501 FoundWrongKind, TypeInfo)) {
9502 if (FoundWrongKind)
9503 Diag(TypeTagExpr->getExprLoc(),
9504 diag::warn_type_tag_for_datatype_wrong_kind)
9505 << TypeTagExpr->getSourceRange();
9506 return;
9507 }
9508
9509 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9510 if (IsPointerAttr) {
9511 // Skip implicit cast of pointer to `void *' (as a function argument).
9512 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
Dmitri Gribenko5ac744e2012-11-03 16:07:49 +00009513 if (ICE->getType()->isVoidPointerType() &&
Dmitri Gribenkof21203b2012-11-03 22:10:18 +00009514 ICE->getCastKind() == CK_BitCast)
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009515 ArgumentExpr = ICE->getSubExpr();
9516 }
9517 QualType ArgumentType = ArgumentExpr->getType();
9518
9519 // Passing a `void*' pointer shouldn't trigger a warning.
9520 if (IsPointerAttr && ArgumentType->isVoidPointerType())
9521 return;
9522
9523 if (TypeInfo.MustBeNull) {
9524 // Type tag with matching void type requires a null pointer.
9525 if (!ArgumentExpr->isNullPointerConstant(Context,
9526 Expr::NPC_ValueDependentIsNotNull)) {
9527 Diag(ArgumentExpr->getExprLoc(),
9528 diag::warn_type_safety_null_pointer_required)
9529 << ArgumentKind->getName()
9530 << ArgumentExpr->getSourceRange()
9531 << TypeTagExpr->getSourceRange();
9532 }
9533 return;
9534 }
9535
9536 QualType RequiredType = TypeInfo.Type;
9537 if (IsPointerAttr)
9538 RequiredType = Context.getPointerType(RequiredType);
9539
9540 bool mismatch = false;
9541 if (!TypeInfo.LayoutCompatible) {
9542 mismatch = !Context.hasSameType(ArgumentType, RequiredType);
9543
9544 // C++11 [basic.fundamental] p1:
9545 // Plain char, signed char, and unsigned char are three distinct types.
9546 //
9547 // But we treat plain `char' as equivalent to `signed char' or `unsigned
9548 // char' depending on the current char signedness mode.
9549 if (mismatch)
9550 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
9551 RequiredType->getPointeeType())) ||
9552 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9553 mismatch = false;
9554 } else
9555 if (IsPointerAttr)
9556 mismatch = !isLayoutCompatible(Context,
9557 ArgumentType->getPointeeType(),
9558 RequiredType->getPointeeType());
9559 else
9560 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9561
9562 if (mismatch)
9563 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
Aaron Ballman25dc1e12014-01-03 02:14:08 +00009564 << ArgumentType << ArgumentKind
Dmitri Gribenkoe4a5a902012-08-17 00:08:38 +00009565 << TypeInfo.LayoutCompatible << RequiredType
9566 << ArgumentExpr->getSourceRange()
9567 << TypeTagExpr->getSourceRange();
9568}
Richard Trieu7eb0b2c2014-02-26 01:17:28 +00009569